"""Bounded aggregate reproduction and explicitly illustrative sensitivities. Stdlib only."""
import json, math
from pathlib import Path

BASE = Path(__file__).resolve().parent
a, n1, c, n0 = 4, 77, 5, 76
rr = (a/n1)/(c/n0)
se = math.sqrt(1/a-1/n1+1/c-1/n0)
ci = [math.exp(math.log(rr)-1.96*se), math.exp(math.log(rr)+1.96*se)]
def pmf(x):
    return math.comb(n1,x)*math.comb(n0,a+c-x)/math.comb(n1+n0,a+c)
fisher_greater = sum(pmf(x) for x in range(a,a+c+1))
assert abs(sum(pmf(x) for x in range(a+c+1))-1)<1e-12
assert round(rr,2)==.79 and round(fisher_greater,3)==.759
def rr_score(r):
    # Constrained binomial MLE under p1 = r*p0; numerically stable quadratic root.
    B=a+r*c+r*n1+n0
    p=2*(a+c)/(B+math.sqrt(B*B-4*r*(n1+n0)*(a+c)))
    variance=r*p*(1-r*p)/n1+r*r*p*(1-p)/n0
    return (a/n1-r*c/n0)**2/variance
critical=3.841458820694124
def bisect_score(lo,hi):
    assert (rr_score(lo)-critical)*(rr_score(hi)-critical)<0
    for _ in range(100):
        mid=(lo+hi)/2
        if (rr_score(lo)-critical)*(rr_score(mid)-critical)>0: lo=mid
        else: hi=mid
    return (lo+hi)/2
score_ci=[bisect_score(.001,rr),bisect_score(rr,10)]
assert [round(x,3) for x in score_ci]==[.237,2.624]
assert all(abs(rr_score(x)-critical)<1e-10 for x in score_ci)
theta, p0 = 4.16, .05
p1=theta*p0/(1-p0+theta*p0)
assert math.isclose((p1/(1-p1))/(p0/(1-p0)),theta)
uplift=[dict(initial_uplift=u,doubling_months=d,target_uplift=20,
              months=d*math.log2(19/(u-1))) for u in [1.25,2,3] for d in [3,5,9]]
for row in uplift:
    assert math.isclose(1+(row['initial_uplift']-1)*2**(row['months']/row['doubling_months']),20)
displacement=[dict(blocked_fraction=b,substitution=s,relative_harm=k,
                   remaining_harm_ratio=1-b+b*s*k,reduction=b*(1-s*k))
              for b in [.25,.5,.75] for s in [0,.2,.5,.8,1] for k in [.5,1,2]]
for row in displacement:
    assert math.isclose(row['remaining_harm_ratio']+row['reduction'],1)
assert math.isclose(.5*(1-.8*2),-.3)
report={
 'status':'passed','scope':'Published 2x2 aggregate consistency check plus illustrative arithmetic; no private-data or model-experiment replication.',
 'biology_aggregate':{'llm_successes':a,'llm_total':n1,'control_successes':c,'control_total':n0,
   'risk_ratio':rr,'absolute_risk_difference':a/n1-c/n0,'fisher_one_sided_greater':fisher_greater,
   'koopman_score_95_ci':score_ci,'log_wald_95_ci':ci,'reported_95_ci':[.237,2.624],
   'ci_note':'Score-test inversion reproduces the published rounding; generic log-Wald is a different interval. No participant-level model is reproduced.'},
 'odds_example':{'baseline':p0,'odds_ratio':theta,'treated_probability':p1,'risk_ratio':p1/p0},
 'uplift_sensitivity':uplift,'uplift_range_months':[min(r['months'] for r in uplift),max(r['months'] for r in uplift)],
 'policy_displacement':displacement,
 'darpa_denominators':{'found_fraction':54/63,'patch_fraction_all':43/63,'patch_fraction_found':43/54},
 'macro_illustration':{'affected_share':.3,'adoption':.5,'cost_saving':.2,'product':.3*.5*.2},
 'alert_example':{'benign_actions':1000000,'false_positive_rate':.001,'expected_false_alerts':1000},
 'checks':'Hypergeometric mass sums to one; Fisher tail and point estimate match reported rounding; odds identity and uplift inverse checked; displacement mass balance checked.'
}
(BASE/'aggregate-and-sensitivity-results.json').write_text(json.dumps(report,indent=2)+'\n',encoding='utf-8')
print(json.dumps({k:report[k] for k in ['status','biology_aggregate','odds_example','uplift_range_months','darpa_denominators']},indent=2))
