"""Independently reconstruct the study-level event tables, preserving missing reports."""
import json,sys,csv,copy
from pathlib import Path
b=Path(sys.argv[1]);out=Path(sys.argv[2])
trials=json.loads((b/'data/trials.json').read_text());ext={e['trial']:e for e in json.loads((b/'data/extraction.json').read_text())};P=json.loads((b/'data/parameters.json').read_text())
expanded=[]
for t in trials:
 d=t['design'];ket=[a for a in d.get('arms',[]) if a.get('role')=='ketamine'];ctl=[a for a in d.get('arms',[]) if a.get('role')=='control']
 def unconscious(a):return d.get('anesthesia') in ('general','general_and_regional') and a.get('start') in ('at_induction','after_induction') and a.get('end') in ('before_end_of_surgery','end_of_surgery') and a.get('pump') is not True
 classes=[unconscious(a) for a in ket]
 if d.get('eligible') and d.get('timing_comparison') and ctl and any(classes) and not all(classes):
  for state,suffix,group in [(True,'m','none'),(False,'a','some')]:
   u=copy.deepcopy(t);u['trial']+=suffix;u['parent']=t['trial'];u['control_share']=0.5;u['design']['arms']=[a for a in ket if unconscious(a)==state]+ctl;u['design']['conscious_dosing']=group;expanded.append(u)
 else:expanded.append(t)
rows=[]
for t in expanded:
 if not t['design'].get('eligible'):continue
 e=ext.get(t.get('parent',t['trial']))
 if not e or not e.get('adverse_events'):continue
 sides={role:[a['name'] for a in t['design']['arms'] if a.get('role')==role] for role in ['ketamine','control']}
 def n(a):return float(e['arms'][a].get('analysed') or e['arms'][a]['randomized'])
 counts={}
 for role,arms in sides.items():
  for ty in P['psychotomimetic_types']:
   vals=[]
   for a in arms:
    reports=[w.get('values',{}).get(a,{}).get(ty) for w in e['adverse_events']]
    reports=[float(x) for x in reports if x is not None]
    vals.append(min(max(reports),n(a)) if reports else None)
   counts[role,ty]=vals
 total={ty:sum(v for role in sides for v in counts[role,ty] if v is not None) for ty in P['psychotomimetic_types']}
 if max(total.values())==0:continue
 ty=max(total,key=total.get);share=t.get('control_share',1)
 rows.append(dict(trial=t['trial'],group={'none':'masked','some':'awake'}.get(t['design'].get('conscious_dosing'),'unclear'),event=ty,
 ai=sum(v for v in counts['ketamine',ty] if v is not None),ci=sum(v for v in counts['control',ty] if v is not None)*share,
 n1i=sum(n(a) for a in sides['ketamine']),n2i=sum(n(a) for a in sides['control'])*share,
 incomplete=any(v is None for role in sides for v in counts[role,ty])))
with (out/'event-audit.csv').open('w') as f:
 w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)
print(json.dumps({'rows':len(rows),'incomplete':[r for r in rows if r['incomplete']]},indent=2))
