"""Synthetic identifiability example, not clinical data or a new theorem."""
from pathlib import Path
import json

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


def km(events, censoring, grid):
    stop=[min(t if t is not None else c,c) for t,c in zip(events,censoring)]
    observed=[t is not None and t<=c for t,c in zip(events,censoring)]
    survival=1.;values=[]
    for point in grid:
        risk=sum(t>=point for t in stop)
        deaths=sum(t==point and e for t,e in zip(stop,observed))
        if risk:survival*=1-deaths/risk
        values.append(survival)
    return values


def run():
    grid=[.25,.5,1.,2.]
    death=[1.,2.,None,None]
    stroke_a=[.25,.5,None,None]
    stroke_b=[None,None,.25,.5]
    administrative=[3.]*4
    def get(stroke):
        stroke_censor=[min(3.,t) if t is not None else 3. for t in death]
        combined=[min([t for t in (a,b) if t is not None],default=None) for a,b in zip(death,stroke)]
        return {
          'death_km_survival':km(death,administrative,grid),
          'stroke_km_survival_with_death_censoring':km(stroke,stroke_censor,grid),
          'composite_km_survival':km(combined,administrative,grid),
          'death_times':death,'stroke_times':stroke,
          'composite_events_by_horizon':sum(t is not None and t<=2 for t in combined),
        }
    a,b=get(stroke_a),get(stroke_b)
    assert a['death_km_survival']==b['death_km_survival']
    assert a['stroke_km_survival_with_death_censoring']==b['stroke_km_survival_with_death_censoring']
    assert a['composite_km_survival']!=b['composite_km_survival']
    result={'description':'Hypothetical four-unit cohorts with identical published component KM curves but different joint composite curves. All stroke events occur before all deaths. No reconstructed or real patient records.','time_units':'arbitrary synthetic units','grid':grid,'a':a,'b':b,'component_curves_identical':True,'composite_curves_identical':False}
    (ROOT/'results/R4.json').write_text(json.dumps(result,indent=2)+'\n')
    return result


if __name__=='__main__':run()
