"""Four-week fictional rental case, prices in rubles. Python 3.9."""
import json
from pathlib import Path
def integer(v):
 if not isinstance(v,int) or isinstance(v,bool) or v<0:raise ValueError("Nonnegative integer required")
 return v
def calculate(d):
 for k in ("fleet","price","variable_cost","fixed_cost","extra_rental_whole_pilot"):integer(d[k])
 weekly=[integer(v) for v in d["weekly_demand"]]
 if len(weekly)!=4:raise ValueError("Four weeks required")
 people=sum(integer(g["people"]) for g in d["groups"])
 planned=sum(integer(g["people"])*integer(g["weeks_each"]) for g in d["groups"])
 if any(g["weeks_each"]>4 for g in d["groups"]):raise ValueError("More active weeks than calendar")
 if planned!=sum(weekly):raise ValueError("Group forecast does not match weekly demand")
 margin=d["price"]-d["variable_cost"];extra=max(0,max(weekly)-d["fleet"])
 rental=extra*d["extra_rental_whole_pilot"];base=planned*margin-d["fixed_cost"]
 cost=d["fixed_cost"]+rental
 return {"people":people,"planned_paid_weeks":planned,"revenue":planned*d["price"],"variable_cost":planned*d["variable_cost"],
         "contribution":planned*margin,"before_extra_rental":base,"peak":max(weekly),"extra_sets":extra,"rental_cost":rental,
         "full_result":base-rental,"break_even_given_rental":(cost+margin-1)//margin if margin>0 else None,
         "capped_paid_weeks":sum(min(d["fleet"],x) for x in weekly),
         "capped_result":sum(min(d["fleet"],x) for x in weekly)*margin-d["fixed_cost"]}
if __name__=="__main__":
 print(json.dumps(calculate(json.loads(Path(__file__).with_name("rental.json").read_text())),indent=2))
