"""Original numeric practice. Exact Fraction arithmetic; Python 3.9."""
import json
from fractions import Fraction as F
from pathlib import Path
def calculate(d):
 for k,v in d.items():
  if k=="groups":continue
  if not isinstance(v,int) or isinstance(v,bool) or v<0:raise ValueError("Nonnegative integer required: "+k)
 rows=d["groups"];fulfilled=0;revenue=0
 for r in rows:
  for v in r.values():
   if not isinstance(v,int) or isinstance(v,bool) or v<0:raise ValueError("Invalid group value")
  if r["cancelled"]>r["received"]:raise ValueError("Cancellations exceed received")
  done=r["received"]-r["cancelled"];fulfilled+=done;revenue+=done*r["price"]
 if d["discount_percent"]>100 or d["order_contribution"]==0:raise ValueError("Invalid discount or contribution")
 final=F(d["initial_price"])*(1-F(d["discount_percent"],100))*(1+F(d["later_increase_percent"],100))
 fx=F(d["eur_invoice"]*d["rubles_per_eur"])*(1+F(d["fee_percent"],100))
 before=F(d["revenue_before"]*d["margin_before_percent"],100);after=F(d["revenue_after"]*d["margin_after_percent"],100)
 needed=(d["fixed_cost"]+d["order_contribution"]-1)//d["order_contribution"]
 return {"fulfilled":fulfilled,"revenue":revenue,"weighted_average":str(F(revenue,fulfilled)) if fulfilled else None,
         "final_price":str(final),"price_change":str((final-d["initial_price"])/d["initial_price"]) if d["initial_price"] else None,
         "invoice_total":str(fx),"gross_before":str(before),"gross_after":str(after),"gross_change":str((after-before)/before) if before else None,
         "break_even_orders":needed,"capacity_covers":d["capacity"]>=needed}
if __name__=="__main__":
 print(json.dumps(calculate(json.loads(Path(__file__).with_name("numbers.json").read_text())),indent=2))
