"""Scientific validation against an independent stratum-capacity calculation."""
import json
from pathlib import Path
import numpy as np
from bounds import (sharp_bounds,one_dimensional_bounds,closed_form,
                    selected_cohort_bounds,selection_only_witness,box_bounds,
                    minimum_omitted_surgery_mortality_for_null)


def validate():
    rng=np.random.default_rng(281106)
    examples=[(0,0,.2,.1),(.1,.1,.1,.1),(.02,.04,.2,.2),
              (.4,.4,.4,.9),(.49,.49,.5,.6),(.01,.024,.195,.168)]
    for _ in range(1000):
        e1,e0=rng.uniform(0,.49,2)
        d1=rng.uniform(e1,1);d0=rng.uniform(e0,1)
        examples.append((e1,e0,d1,d0))
    max_error=0.;closed_cases=0;max_closed_error=0.
    for index,example in enumerate(examples):
        a=sharp_bounds(*example);b=one_dimensional_bounds(*example)
        error=max(abs(a['lower']['value']-b[0]),abs(a['upper']['value']-b[1]))
        max_error=max(max_error,error)
        if error>2e-8:raise AssertionError((example,a,b))
        c=closed_form(*example)
        if c is not None:
            closed_cases+=1
            cerr=max(abs(c[0]-b[0]),abs(c[1]-b[1]));max_closed_error=max(max_closed_error,cerr)
            if cerr>2e-8:raise AssertionError(('Closed form failed',example,c,b))
        # Selected-cohort formulation must reduce to the fixed-margin case.
        if index<12:
            z=selected_cohort_bounds(*example,1,1)
            assert abs(z['lower']['value']-b[0])<2e-8
            assert abs(z['upper']['value']-b[1])<2e-8
        if index<50:
            null=selection_only_witness(*example)
            expected=(b[0] <= 1e-10 and b[1] >= -1e-10)
            assert null['feasible']==expected,(example,b,null)
        if index<100:
            e1,e0,d1,d0=example;L1=d1-e1;L0=d0-e0
            strong=selection_only_witness(*example,all_always_survive_horizon=True)
            feasible=(L1<=e0+1e-10 and L0<=e1+1e-10)
            assert strong['feasible']==feasible
            if feasible:
                maximum_common_early_death=min(e0-L1,e1-L0)
                minimum_discordance=e1+e0-2*maximum_common_early_death
                assert abs(strong['minimum_early_survival_discordance']-minimum_discordance)<2e-8
                matrix=np.array(strong['witness'])
                assert matrix[1:,1:].sum()-matrix[2,2]<2e-8
    # No late deaths implies exactly zero contrast, despite positive early deaths.
    assert one_dimensional_bounds(.1,.2,.1,.2)==(0.,0.)
    # With nobody dying before the landmark, the target is the marginal difference.
    z=one_dimensional_bounds(0,0,.3,.2)
    assert max(abs(v-.1) for v in z)<1e-12
    # A singleton risk region must reduce to fixed marginal risks.
    v=(.01,.024,.195,.168)
    z=box_bounds([[x,x] for x in v]);b=one_dimensional_bounds(*v)
    assert abs(z['lower']['value']-b[0])<2e-8
    assert abs(z['upper']['value']-b[1])<2e-8
    # In the clinical closed-form region, linear-fractional extrema over a
    # rectangular risk region occur at vertices; compare this with the box LP.
    import itertools
    intervals=[(.0095,.0105),(.0235,.0245),(.1945,.1955),(.1675,.1685)]
    vertices=[closed_form(*p) for p in itertools.product(*intervals)]
    z=box_bounds(intervals)
    assert abs(z['lower']['value']-min(x[0] for x in vertices))<2e-8
    assert abs(z['upper']['value']-max(x[1] for x in vertices))<2e-8
    # An independent finite-vertex check of the actual omission model is
    # exact here: all mixture vertices lie in the closed-form region, and
    # its endpoint expressions are linear-fractional over the omitted-state
    # simplex product. Such extrema occur at simplex-product vertices.
    source=json.loads(Path('data/mortality_inputs.json').read_text())
    row=next(r for r in source['partner'] if r['id']=='partner_L1_T7');e1=row['e_TAVR_pct']/100;e0=row['e_SAVR_pct']/100
    d1=row['d_TAVR_pct']/100;d0=row['d_SAVR_pct']/100
    s=source['primary_source'];w1=s['n_TAVR']/s['randomized_TAVR'];w0=s['n_SAVR']/s['randomized_SAVR']
    r=np.array([e1,d1-e1,1-d1]);c=np.array([e0,d0-e0,1-d0]);extrema=[];overall=[]
    for i,j in itertools.product(range(3),repeat=2):
        R=w1*r;C=w0*c;R[i]+=1-w1;C[j]+=1-w0
        values=(R[0],C[0],R[0]+R[1],C[0]+C[1])
        assert closed_form(*values) is not None
        extrema.append(one_dimensional_bounds(*values))
        overall.append((R[0]+R[1])-(C[0]+C[1]))
    result=selected_cohort_bounds(e1,e0,d1,d0,w1,w0)
    assert abs(result['lower']['value']-min(z[0] for z in extrema))<2e-8
    assert abs(result['upper']['value']-max(z[1] for z in extrema))<2e-8
    assert abs(min(overall)-(w1*d1-w0*d0-(1-w0)))<2e-8
    assert abs(max(overall)-(w1*d1+(1-w1)-w0*d0))<2e-8
    calibrated=minimum_omitted_surgery_mortality_for_null(e1,e0,d1,d0,w1,w0)
    independently_derived=(w1*(d1-e1)-w0*d0)/(1-w0)
    assert abs(calibrated['minimum_omitted_SAVR_mortality']-independently_derived)<2e-8
    return {'marginal_configurations':len(examples),'max_LP_independent_difference':max_error,
            'closed_form_configurations':closed_cases,'max_closed_form_difference':max_closed_error,
            'omission_vertices_checked':9,'omission_calibration_analytic_check':True,
            'seed':281106,'validation_passed':True}


if __name__=='__main__':
    out=validate();Path('results').mkdir(exist_ok=True)
    Path('results/R2.json').write_text(json.dumps(out,indent=2)+'\n')
    print(json.dumps(out))
