"""Reproduce all conditional calculations from source-indexed aggregate inputs."""
import itertools,json,csv
from pathlib import Path
import numpy as np
from bounds import (sharp_bounds,box_bounds,selection_only_witness,
                    selected_cohort_bounds,fixed_stratum_bounds,
                    minimum_omitted_surgery_mortality_for_null)

ROOT=Path(__file__).resolve().parents[1]
OUT=ROOT/'results';OUT.mkdir(exist_ok=True)


def save(name,value):
    (OUT/name).write_text(json.dumps(value,indent=2,allow_nan=False)+'\n')


def main():
    data=json.loads((ROOT/'data/mortality_inputs.json').read_text())
    results={'units':'risk proportions; *_pp fields are percentage points',
             'interval_interpretation':'Identification bounds or deterministic input-uncertainty envelopes; never confidence intervals.',
             'partner':{},'evolut':{}}
    for row in data['partner']:
        raw=[row[k] for k in ['e_TAVR_pct','e_SAVR_pct','d_TAVR_pct','d_SAVR_pct']]
        values=np.array(raw)/100
        point=sharp_bounds(*values)
        box=[[(v-row['rounding_halfwidth_pct'])/100,(v+row['rounding_halfwidth_pct'])/100] for v in raw]
        uncertain=box_bounds(box)
        null=selection_only_witness(*values)
        box_null=box_bounds(box,selection_only=True)
        results['partner'][row['id']]={'landmark_years':row['landmark_years'],
            'horizon_years':row['horizon_years'],'input_risks_e1_e0_d1_d0':values.tolist(),
            'sharp_bounds':point,'lower_pp':round(100*point['lower']['value'],2),
            'upper_pp':round(100*point['upper']['value'],2),
            'rounding_envelope':uncertain,'rounding_lower_pp':round(100*uncertain['lower']['value'],2),
            'rounding_upper_pp':round(100*uncertain['upper']['value'],2),
            'selection_only':null,'selection_only_with_rounding':box_null}
        if null['feasible']:
            results['partner'][row['id']]['minimum_discordance_pct']=round(100*null['minimum_early_survival_discordance'],2)
        strong=selection_only_witness(*values,all_always_survive_horizon=True)
        results['partner'][row['id']]['all_always_survive_horizon']=strong
        if strong['feasible']:
            results['partner'][row['id']]['all_always_survive_horizon_min_discordance_pct']=round(100*strong['minimum_early_survival_discordance'],2)
            strong_box=box_bounds(box,selection_only=True,all_always_survive_horizon=True)
            results['partner'][row['id']]['all_always_survive_horizon_rounding']=strong_box
            results['partner'][row['id']]['all_always_survive_horizon_rounding_min_discordance_pct']=round(100*strong_box['minimum_early_survival_discordance'],2)
    for row in data['evolut_ranges']:
        box=[[v/100 for v in row[k]] for k in
             ['e_TAVR_pct_range','e_SAVR_pct_range','d_TAVR_pct_range','d_SAVR_pct_range']]
        bounds=box_bounds(box)
        results['evolut'][row['id']]={'landmark_years':row['landmark_years'],
            'horizon_years':row['horizon_years'],'vital_status_sweep':row['vital_status_sweep'],
            'risk_box':box,'bounds':bounds,
            'lower_pp':round(100*bounds['lower']['value'],2),
            'upper_pp':round(100*bounds['upper']['value'],2),
            'selection_only':box_bounds(box,selection_only=True)}
    base=results['partner']['partner_L1_T7']['input_risks_e1_e0_d1_d0']
    results['monotone_early_benefit_sensitivity']=sharp_bounds(*base,monotone=True)
    source=data['primary_source'];w1=source['n_TAVR']/source['randomized_TAVR'];w0=source['n_SAVR']/source['randomized_SAVR']
    results['omission_sensitivity']={'description':'Diagram-based sensitivity model, not an actual intention-to-treat reanalysis; omitted outcomes are left unrestricted by design.',
        'w_TAVR':w1,'w_SAVR':w0,'n_omitted_TAVR':source['randomized_TAVR']-source['n_TAVR'],
        'n_omitted_SAVR':source['randomized_SAVR']-source['n_SAVR'],
        'bounds':selected_cohort_bounds(*base,w1,w0),
        'zero_effect_witness':selected_cohort_bounds(*base,w1,w0,zero_effect=True)}
    omission=results['omission_sensitivity'];omission['lower_pp']=round(100*omission['bounds']['lower']['value'],2);omission['upper_pp']=round(100*omission['bounds']['upper']['value'],2)
    calibration=minimum_omitted_surgery_mortality_for_null(*base,w1,w0)
    omission['null_calibration']=calibration
    omission['minimum_omitted_SAVR_mortality_for_null_pct']=round(100*calibration['minimum_omitted_SAVR_mortality'],2)
    omission['overall_mortality_lower_pp']=round(100*(w1*base[2]-(w0*base[3]+1-w0)),2)
    omission['overall_mortality_upper_pp']=round(100*(w1*base[2]+1-w1-w0*base[3]),2)
    omission['minimum_omitted_SAVR_mortality_for_overall_null_pct']=round(100*(w1*base[2]-w0*base[3])/(1-w0),2)
    # This is a calibrated risk-shift scenario, not an estimate of censoring bias.
    shifts=[]
    for shift in np.linspace(0,.05,51):
        v=list(base);v[3]+=float(shift)
        r=sharp_bounds(*v)
        shifts.append({'SAVR_late_risk_increase_pp':100*float(shift),
                       'lower_pp':100*r['lower']['value'],'upper_pp':100*r['upper']['value']})
    results['risk_shift_sensitivity']={'description':'Only the SAVR late marginal risk is increased; all other marginals fixed; this does not estimate missing deaths.',
        'shift_to_zero_lower_bound_pp':round(100*(base[2]-base[3]-base[0]),2),'grid':shifts}
    # Vary only the omitted SAVR fraction, retaining the documented TAVR weight.
    omission_grid=[]
    for fraction in np.linspace(0,.10,51):
        r=selected_cohort_bounds(*base,w1,1-float(fraction))
        omission_grid.append({'omitted_SAVR_pct':100*float(fraction),
            'lower_pp':100*r['lower']['value'],'upper_pp':100*r['upper']['value'],
            'overall_lower_pp':100*(w1*base[2]-((1-float(fraction))*base[3]+float(fraction))),
            'overall_upper_pp':100*(w1*base[2]+1-w1-(1-float(fraction))*base[3])})
    results['omission_sensitivity']['grid']=omission_grid
    late=results['partner']['partner_L5_T7'];e1,e0,d1,d0=late['input_risks_e1_e0_d1_d0']
    shared=[]
    for D in np.linspace(0,min(e1,e0),101):
        lo,hi=fixed_stratum_bounds(e1,e0,d1,d0,float(D))
        shared.append({'common_early_death_pct':100*float(D),'lower_pp':100*lo,'upper_pp':100*hi})
    binary_ceiling=late['selection_only']['maximum_common_early_death_mass']
    strong_ceiling=late['all_always_survive_horizon']['maximum_common_early_death_mass']
    results['shared_early_death_sensitivity']={
        'description':'Conditional year-5 to year-7 identification frontier as the unobserved probability of death by year 5 under both strategies varies; not an estimated association.',
        'binary_null_common_death_ceiling_pct':round(100*binary_ceiling,2),
        'binary_null_fraction_of_SAVR_early_deaths_shared_pct':round(100*binary_ceiling/e0,2),
        'strong_null_common_death_ceiling_pct':round(100*strong_ceiling,2),
        'strong_null_fraction_of_SAVR_early_deaths_shared_pct':round(100*strong_ceiling/e0,2),
        'product_of_early_marginal_risks_pct':round(100*e1*e0,3),
        'binary_null_with_nonnegative_early_death_association':selection_only_witness(e1,e0,d1,d0,common_early_death_min=e1*e0),
        'strong_null_with_nonnegative_early_death_association':selection_only_witness(e1,e0,d1,d0,all_always_survive_horizon=True,common_early_death_min=e1*e0),
        'grid':shared}
    save('R1.json',results)
    first=results['partner']['partner_L1_T7'];late=results['partner']['partner_L5_T7']
    save('R3.json',{'earlier_window':f"years {first['landmark_years']}–{first['horizon_years']}",
        'later_window':f"years {late['landmark_years']}–{late['horizon_years']}",
        'earlier_lower_pp':first['lower_pp'],'earlier_upper_pp':first['upper_pp'],
        'later_lower_pp':late['lower_pp'],'later_upper_pp':late['upper_pp'],
        'minimum_discordance_pct':late['minimum_discordance_pct'],
        'strong_min_discordance_pct':late['all_always_survive_horizon_min_discordance_pct'],
        'omission_lower_pp':omission['lower_pp'],'omission_upper_pp':omission['upper_pp'],
        'omission_overall_lower_pp':omission['overall_mortality_lower_pp'],
        'omission_overall_upper_pp':omission['overall_mortality_upper_pp'],
        'omission_null_mortality_pct':omission['minimum_omitted_SAVR_mortality_for_null_pct']})
    # Flat files for inspection without reading a solver witness.
    table=[]
    for key,row in results['partner'].items():
        table.append({'trial':'PARTNER 3','landmark_years':row['landmark_years'],
            'horizon_years':row['horizon_years'],'input_type':'matched displayed KM risks with sweep',
            'lower_pp':row['lower_pp'],'upper_pp':row['upper_pp'],
            'input_envelope_lower_pp':row['rounding_lower_pp'],'input_envelope_upper_pp':row['rounding_upper_pp'],
            'selection_only_feasible':row['selection_only']['feasible']})
    for key,row in results['evolut'].items():
        table.append({'trial':'Evolut Low Risk','landmark_years':row['landmark_years'],
            'horizon_years':row['horizon_years'],'input_type':'graph-read risk region'+(' with sweep' if row['vital_status_sweep'] else ' without sweep'),
            'lower_pp':'','upper_pp':'','input_envelope_lower_pp':row['lower_pp'],
            'input_envelope_upper_pp':row['upper_pp'],'selection_only_feasible':row['selection_only']['feasible']})
    with (OUT/'bounds-table.csv').open('w',newline='') as f:
        w=csv.DictWriter(f,fieldnames=list(table[0]));w.writeheader();w.writerows(table)
    print('Computed conditional bounds for',len(table),'trial/landmark/horizon/ascertainment inputs.')
    print('PARTNER 1–7:',results['partner']['partner_L1_T7']['lower_pp'],results['partner']['partner_L1_T7']['upper_pp'])
    print('PARTNER 5–7:',results['partner']['partner_L5_T7']['lower_pp'],results['partner']['partner_L5_T7']['upper_pp'])
    print('Minimum five-year survival discordance for a binary null:',results['partner']['partner_L5_T7']['minimum_discordance_pct'])
    print('Omitted-outcome scenario:',omission['lower_pp'],omission['upper_pp'])


if __name__=='__main__':main()
