"""Seven-day inventory practice, no transfers/backlog; 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):
 if d["period_days"]!=7:raise ValueError("Seven-day case only")
 day=integer(d["additional_day"])
 if day>6:raise ValueError("Delivery day outside week")
 pool=integer(d["pool"]);alloc=d["allocation"]
 if sum(integer(v) for v in alloc.values())>pool:raise ValueError("Allocation exceeds central supply")
 identifiers=[s["id"] for s in d["stores"]]
 if len(set(identifiers))!=len(identifiers) or set(alloc)!=set(identifiers):raise ValueError("Store identifiers inconsistent")
 rows=[]
 for s in d["stores"]:
  weekly=integer(s["weekly_demand"])
  if weekly%7:raise ValueError("Case requires whole uniform daily demand")
  daily=weekly//7;stock=integer(s["opening_stock"]);tue=integer(s["tuesday"]);lost=0;after=[]
  for i in range(7):
   if i==1:stock+=tue
   if i==day:stock+=alloc[s["id"]]
   sold=min(stock,daily);stock-=sold;lost+=daily-sold;after.append(stock)
  shortage=max(0,weekly-s["opening_stock"]-tue)
  rows.append({"id":s["id"],"daily_demand":daily,"before_additional_shortage":shortage,"lost_sales":lost,"fulfilled":weekly-lost,"ending_stock":stock,"after_friday":after[4],"daily_ending_stock":after})
 return {"stores":rows,"central_remaining":pool-sum(alloc.values()),"total_lost_sales":sum(r["lost_sales"] for r in rows)}
if __name__=="__main__":
 print(json.dumps(calculate(json.loads(Path(__file__).with_name("stores.json").read_text())),indent=2))
