"""Recompute business checks using only the bundled source assumptions."""
import json, math
from pathlib import Path
ROOT = Path(__file__).resolve().parent

def sample(N,e):
    n0=1.96**2*.5*.5/e**2
    return {'unrounded_n0':n0,'unrounded_fpc':n0/(1+(n0-1)/N),'required':math.ceil(n0/(1+(n0-1)/N))}
def moe(N,n):
    return 1.96*math.sqrt(.25/n*(N-n)/(N-1)) if N>1 else 0
strata=[(6000,222,.6),(4000,151,.4)]
variance=sum(w*w*.25/n*(N-n)/(N-1) for N,n,w in strata)
result={
 'main':{'overall':sample(10000,.05),'commuter_fpc':sample(6000,.08),'desk_fpc':sample(4000,.08),
 'invitations':{'commuter':math.ceil(222/.25),'desk':math.ceil(151/.25)},
 'achieved_moe':{'overall_weighted':1.96*math.sqrt(variance),'commuter':moe(6000,222),'desk':moe(4000,151)},
 'capacity_revenue':8000*24,'capacity_utilization':8000/8000},
 'boundary':{'overall':sample(100,.05),'commuter_fpc':sample(90,.08),'desk_fpc':sample(10,.08),
 'max_expected_completes_at_25pct':{'commuter':90*.25,'desk':10*.25},
 'impossible_expected_invitation_needs':{'commuter':math.ceil(sample(90,.08)['required']/.25),'desk':math.ceil(sample(10,.08)['required']/.25)},
 'feasible_boundary_completes':{'commuter':72,'desk':10,'weighted_moe':1.96*math.sqrt(.9**2*.25/72*(90-72)/(90-1))},
 'buyer_count_to_match_top_down':48000000/24,
 'top_down_value_to_match_bottom_up':1000000*24,
 'divergence':abs(48000000-24000000)/48000000},
 'sensitivity':[{'adoption':a,'demand_units':800000*a,'capacity_capped_units':min(8000,800000*a),'revenue':min(8000,800000*a)*24} for a in [.005,.01,.015]]}
assert sum(math.ceil(n/.25) for _,n,_ in strata)==1492
assert result['main']['achieved_moe']['overall_weighted']<.05
assert all(moe(N,n)<.08 for N,n,_ in strata)
(ROOT/'calculation-checks.json').write_text(json.dumps(result,indent=2)+'\n')
print(json.dumps(result,indent=2))
