"""Fixed weekly stock checks, independent balance and changed delivery."""
import json,copy,sys
from pathlib import Path
from calculate import calculate
def check(c,m):
 if not c:raise AssertionError(m)
def main():
 d=json.loads(Path(__file__).with_name("stores.json").read_text());r=calculate(d);s={x["id"]:x for x in r["stores"]}
 for key,shortage,friday,end in (("A",18,20,0),("B",0,45,35),("C",28,16,0),("D",0,6,0)):
  check((s[key]["before_additional_shortage"],s[key]["after_friday"],s[key]["ending_stock"],s[key]["lost_sales"])==(shortage,friday,end,0),"Fixed store mismatch "+key)
 check(r["central_remaining"]==4,"Central remaining")
 # Independent total balance, no daily engine.
 check(96+75+50==182+35+4,"Independent stock balance")
 check(70-52+56-28==46 and 182-171==11,"Stranded stock distinction")
 changed=copy.deepcopy(d);changed["pool"]=30;changed["allocation"]={"A":2,"B":0,"C":28,"D":0};x=calculate(changed)
 check(x["total_lost_sales"]==16 and x["stores"][0]["fulfilled"]==54,"Reduced delivery")
 changed=copy.deepcopy(d);changed["additional_day"]=4;x=calculate(changed)
 check(x["stores"][2]["lost_sales"]==4 and x["stores"][2]["ending_stock"]==4,"Late delivery cannot recover lost demand")
 changed=copy.deepcopy(d);changed["pool"]=0;changed["allocation"]={k:0 for k in changed["allocation"]}
 check(calculate(changed)["total_lost_sales"]==46,"No additional supply")
 bads=[]
 bad=copy.deepcopy(d);bad["allocation"]["A"]=100;bads.append(bad)
 bad=copy.deepcopy(d);bad["stores"][0]["opening_stock"]=-1;bads.append(bad)
 bad=copy.deepcopy(d);bad["stores"][0]["weekly_demand"]=71;bads.append(bad)
 bad=copy.deepcopy(d);bad["additional_day"]=7;bads.append(bad)
 for bad in bads:
  try:calculate(bad)
  except ValueError:pass
  else:raise AssertionError("Invalid input accepted")
 print(json.dumps({"fixed_stores":4,"independent_balance":True,"edges":["central supply 30","delivery Friday","no Thursday supply"],"invalid_inputs_rejected":len(bads)}))
if __name__=="__main__":
 try:main()
 except Exception as error:print("FAIL: "+str(error),file=sys.stderr);sys.exit(1)
