"""Rebuild dose outputs from equations without importing forecast code."""
import json
import math
from pathlib import Path
HERE=Path(__file__).resolve().parent

def calc(w,m,p):
    u,k=p['survival'],p['capacity']
    B={'null':0,'surviving_burden':u,'failed_processing':1-u,
       'surviving_defective':u-u*u}[p['burden_model']]
    q=p['competition']+p['susceptibility']*B
    wd=w+m if p['delivery_model']=='joint_total_input' else w
    md=m if p['delivery_model']=='independent' else w+m
    sw=(1+k)*w*w/((1+k*wd)*(w+q*m)) if w>0 else 0
    sm=u*(1+k)*m/(1+k*md)
    aw=w/(w+p['coupling']*u*m) if w>0 else 0
    return sw,aw*sw+p['mutant_activity']*sm

def main():
    data=json.loads((HERE/'dose_response_v2.json').read_text())
    err=0.
    for row in data['rows']:
        p=row['assumptions'];a=row['action'];q=p.copy()
        q.update({key:a[key] for key in ('survival','susceptibility','coupling') if key in a})
        w=a.get('wt_multiplier',1)+a.get('added_wt',0)
        m=a.get('mutant_multiplier',1)
        s0,i0=calc(1,1,p);s1,i1=calc(w,m,q)
        _,c0=calc(1,0,p);_,c1=calc(w,0,q)
        for actual,expected in ((row['delta_current'],i1-i0),
                                (row['delta_wt_surface'],s1-s0),
                                (row['wt_control_delta_current'],c1-c0)):
            err=max(err,abs(actual-expected))
            assert math.isclose(actual,expected,abs_tol=1e-12,rel_tol=1e-12)
    result=dict(verified_rows=len(data['rows']),maximum_absolute_error=err,
                scope='Independent equation reconstruction; not biological validation')
    with (HERE/'dose_response_v2_verification.json').open('x') as f:json.dump(result,f,indent=2)
    print(result)

if __name__=='__main__':main()
