from pathlib import Path
import json

ROOT=Path(__file__).resolve().parents[1]


def run():
    r=json.loads((ROOT/'results/R1.json').read_text())
    d=json.loads((ROOT/'data/target-forest-inputs.json').read_text())
    v=json.loads((ROOT/'results/R2.json').read_text())
    demo=json.loads((ROOT/'results/R4.json').read_text())
    original=r['reproduction']['labelled_death_disabling_stroke']['1_year']
    changed=r['sensitivities']['1_year_two_endpoint_substitutions']
    def display(x):return {'rr':round(x['risk_ratio'],2),'lower':round(x['ci_hk'][0],2),'upper':round(x['ci_hk'][1],2),'p':round(x['p_hk'],3)}
    loo=r['sensitivities']['1_year_two_substitutions_leave_one_out']
    result={
      'ci_level_pct':95,'core':{'horizon_years':1,'trials':6,'n_tavr':original['n_tavr'],'n_savr':original['n_savr'],'changed_trials':2,'published_changed_weight_pct':58.9,'calculated_changed_weight_pct':round(r['endpoint_audit']['calculated_weight_1_year_pct'],2),'original':display(original),'substituted':display(changed),'loo_include_null':sum(x['ci_hk'][0]<=1<=x['ci_hk'][1] for x in loo.values()),'loo_total':len(loo)},
      'source_counts':{'DEDICATE':{'target_t':37,'target_s':68,'source_t':26,'source_s':57,'n_t':701,'n_s':713},'UKTAVI':{'target_t':39,'target_s':40,'source_t':30,'source_s':35,'n_t':458,'n_s':455}},
      'six_models_match':all(x['matches_target_at_2dp'] for rows in r['reproduction'].values() for x in rows.values()),'reproduced_models':6,
      'software_validation_models':v['archived_r_models_checked'],'software_validation_max_error':v['max_absolute_python_r_difference'],
      'evolut':{'target_t':21,'target_s':31,'observed_t':17,'observed_s':27,'n_t':725,'n_s':678,'posterior_t_pct':2.9,'posterior_s_pct':4.6,'posterior_times_n_t':round(2.9*725/100),'posterior_times_n_s':round(4.6*678/100)},
      'horizons':{'minimum':1,'maximum':10,'one_year_trial_count':3,'five_plus_trial_count':3},
      'sensitivities':{k:display(x) for k,x in r['sensitivities'].items() if 'leave_one_out' not in k},
      'long_original':display(r['reproduction']['labelled_death_disabling_stroke']['longest']),
      'demo':{'units':4,'events_overlap':demo['a']['composite_events_by_horizon'],'events_disjoint':demo['b']['composite_events_by_horizon'],'same_component_curves':demo['component_curves_identical']},
    }
    (ROOT/'results/R3.json').write_text(json.dumps(result,indent=2)+'\n')
    return result


if __name__=='__main__':run()
