"""Write forecasts/{id}/protocol.md from the saved ClinicalTrials.gov record plus the resolution target
pinned in data/pilot_targets.json (written before any forecast was made).
usage: python3 scripts/make_protocol.py"""
import json, os, textwrap
T = json.load(open("data/pilot_targets.json"))
for sid, t in T.items():
    d = json.load(open(f"data/harvest/pilot_records/{sid}.json"))
    p = d["protocolSection"]
    idm, st, de, arms, om = p["identificationModule"], p["statusModule"], p["designModule"], p["armsInterventionsModule"], p["outcomesModule"]
    el = p.get("eligibilityModule", {})
    dsc = p.get("descriptionModule", {})
    di = de.get("designInfo", {})
    L = [f"# {sid}: {idm.get('officialTitle') or idm.get('briefTitle')}", "",
         f"Registry record: https://clinicaltrials.gov/study/{sid} (retrieved {t['retrieved']}). Sponsor: {p['sponsorCollaboratorsModule']['leadSponsor']['name']}.", "",
         "## What you are forecasting", "",
         f"**Primary hypothesis ({t['hypothesis_source']}):** {t['hypothesis']}", "",
         f"**Resolution rule:** {t['resolution']}", "",
         f"**Alpha:** {t['alpha']}", "",
         f"**Effect metric for your 90% interval:** {t['metric']}", "",
         f"**Moderator to consider:** {t['moderator']}", "",
         "## Design", "",
         f"- Allocation: {di.get('allocation','n/a')}; model: {di.get('interventionModel','n/a')}; purpose: {di.get('primaryPurpose','n/a')}",
         f"- Masking: {di.get('maskingInfo',{}).get('masking','n/a')} {di.get('maskingInfo',{}).get('whoMasked','')}",
         f"- Enrollment: {de.get('enrollmentInfo',{}).get('count')} ({de.get('enrollmentInfo',{}).get('type','').lower()})",
         f"- Phase: {', '.join(de.get('phases',[]) or ['n/a'])}",
         f"- Status on registry: {st.get('overallStatus')}; start {st.get('startDateStruct',{}).get('date')}; primary completion {st.get('primaryCompletionDateStruct',{}).get('date')} ({st.get('primaryCompletionDateStruct',{}).get('type','').lower()})"]
    if di.get("interventionModelDescription"): L.append(f"- Model description: {di['interventionModelDescription']}")
    L += ["", "## Arms", ""]
    for a in arms.get("armGroups", []):
        L.append(f"- **{a['label']}** ({a.get('type','').lower().replace('_',' ')}): {a.get('description','') or '(no description on registry)'}")
    L += ["", "## Primary outcome(s) as registered", ""]
    for o in om.get("primaryOutcomes", []):
        L.append(f"- **{o['measure']}** ({o.get('timeFrame','')}): {o.get('description','')}")
    sec = om.get("secondaryOutcomes", [])
    if sec:
        L += ["", "## Secondary outcomes (names only)", ""] + [f"- {o['measure']} ({o.get('timeFrame','')})" for o in sec[:25]]
        if len(sec) > 25: L.append(f"- ... and {len(sec)-25} more")
    L += ["", "## Population", "", f"Ages {el.get('minimumAge','n/a')} to {el.get('maximumAge','n/a')}; sex: {el.get('sex','n/a')}; healthy volunteers: {el.get('healthyVolunteers','n/a')}.", "",
          el.get("eligibilityCriteria", "").strip(), "", "## Registry summary", "", dsc.get("briefSummary", "").strip()]
    if dsc.get("detailedDescription"):
        L += ["", "## Registry detailed description", "", dsc["detailedDescription"].strip()]
    os.makedirs(f"forecasts/{sid}", exist_ok=True)
    open(f"forecasts/{sid}/protocol.md", "w").write("\n".join(L) + "\n")
    print(sid, len("\n".join(L)))
