"""Write the report documents from recorded files so that every number is traceable.

Reads: structure_metadata.json, verification_results.json, results/*, provenance/*.
Writes: source_verification.md, verification_report.md, provenance/reviewer_findings.md,
        provenance/research_timeline.json, research_timeline.md, results/summary.json
"""
import json
from pathlib import Path
from datetime import datetime, timezone
import pandas as pd

ROOT = Path(__file__).resolve().parents[1]
RES = ROOT / "results"


def iso(ms):
    return datetime.fromtimestamp(ms / 1000, tz=timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")


def main():
    meta = json.loads((ROOT / "structure_metadata.json").read_text())
    ver = json.loads((ROOT / "verification_results.json").read_text())
    pj = json.loads((RES / "pocket_analysis.json").read_text())
    fu = json.loads((RES / "review_followup.json").read_text())
    comp = pd.read_csv(RES / "structural_comparison.csv")
    rd = pd.read_csv(RES / "region_distances.csv")
    cc = pd.read_csv(RES / "crystal_contacts.csv")
    T = {t["id"]: t for t in ver["tests"]}

    # ------------------------------------------------------------------ source_verification.md
    L = ["# Source verification", "",
         "Generated by `analysis/write_reports.py` from `structure_metadata.json`, `provenance/retrieval.json` and `verification_results.json`.", "",
         "## Coordinate files", "", "| File | Bytes | SHA-256 | Source URL | Retrieved (UTC) | Matches record |", "|---|---:|---|---|---|---|"]
    for pid, m in meta.items():
        for fn, f in m["files"].items():
            L.append(f"| `data/raw/{fn}` | {f['bytes']} | `{f['sha256']}` | <{f['source_url']}> | {f['retrieved_utc'][:19]}Z | {'yes' if f['matches_retrieval_record'] else 'NO'} |")
    L += ["", "## Entry records", "",
          "| Entry | Method | Resolution (Å) | R-work / R-free | Space group | Data collection T (K) | Chain | Modelled residues | Residues without coordinates | Ligands (non-water) | Alternate conformers |",
          "|---|---|---:|---|---|---|---|---|---|---|---|"]
    for pid, m in meta.items():
        un = [u["auth_seq_id"] for u in m["unobserved_residues"]]
        rngs, start = [], None
        for r in sorted(un):
            if start is None:
                start = prev = r
            elif r == prev + 1:
                prev = r
            else:
                rngs.append((start, prev)); start = prev = r
        if start is not None:
            rngs.append((start, prev))
        unt = ", ".join(f"{a}–{b}" if a != b else f"{a}" for a, b in rngs)
        lig = "; ".join(f"{l['comp_id']} {l['auth_seq_id']}" for l in m["ligands"])
        L.append(f"| {pid} | {m['method'].title()} | {m['resolution_A']:.2f} | {m['r_work']:.3f} / {m['r_free']:.3f} | {m['space_group']} | {m['data_collection_temperature_K']} | "
                 f"{m['chain_analysed']} (only chain) | {m['modelled_residue_range'][0]}–{m['modelled_residue_range'][1]} ({m['n_modelled_residues']}) | {unt} | {lig} | "
                 f"{', '.join(m['altloc_residues']) or 'none'} |")
    L += ["", "Crystallisation conditions as deposited:", ""]
    for pid, m in meta.items():
        c = m["crystallization"]
        L.append(f"- **{pid}**: {c['details']}; pH {c['pH']}; {c['temperature_K']} K. Deposited {m['deposition_date']}. Citation DOI {m['primary_citation']['doi']}.")
    L += ["", "## Numbering and mapping", "",
          "- `auth_seq_id` equals native PTP1B (UniProt P18031) numbering in all three entries; no insertion codes. `label_seq_id` is offset by +5 in 5K9W/5K9V (expression tag GHMAS) and by 0 in 1T49.",
          f"- Residues 2–280 are modelled and identical in all three entries (279 residues); the core fit set has 267 Cα atoms and the loop window 12 (`structure_mapping.csv`).",
          f"- Independent check V2: {T['V2_mapping']['description']} — **{T['V2_mapping']['status']}**.",
          f"- Independent check V1: {T['V1_checksums']['description']} — **{T['V1_checksums']['status']}**.",
          "", "## Supplementary file not staged by this session", "",
          "- `sources/case/1SUG.cif` was placed by the independent technician (hash and URL in `sources/case/retrieval.json`). It is used only as a supplementary apo control and is flagged as such in every table.",
          "", "## Literature sources", "",
          "- PubMed records (title, authors, abstract) for six papers: `provenance/pubmed_records.json`.",
          "- Keedy 2018 full text (CC BY 4.0): `sources/Keedy2018.xml`, `sources/Keedy2018_reading_copy.md` (placed by the independent technician).",
          "- Tetra-1 page: fetched once in this session; only the title was returned."]
    (ROOT / "source_verification.md").write_text("\n".join(L) + "\n")

    # ------------------------------------------------------------------ verification_report.md
    core = comp[comp.fit_definition == "core_2-280_excl_176-187"].set_index(["mobile", "reference"])
    def c(m, r, k):
        return float(core.loc[(m, r), k])
    def dist(s, name):
        v = rd[(rd.structure == s) & (rd.distance == name)].value_A
        return float(v.iloc[0])
    sasa = T["V4_pocket"]["evidence"]["protein_SASA_buried_A2"]
    occ = fu["e_local_alpha3_alpha6_fit_overlap"]
    loopc = cc[cc.group == "loop window 176-187"].set_index("structure")
    rows = [
        ("Coordinate files are the recorded wwPDB entries", "Independently verified", f"V1: six SHA-256 hashes, sizes and identifiers match `provenance/retrieval.json`."),
        ("Residue mapping (2–280 identical, native numbering, Cys215/WPD positions)", "Independently verified", f"V2: SEQRES vs ATOM mapping 100 % in all entries; motif HCSAGIGRSG at 214–223; consecutive Cα distances 3.6–4.0 Å."),
        (f"Loop-window Cα RMSD after core fit: {c('5K9V','5K9W','loop_176_187_rmsd_fitted_frame_A'):.3f} Å (5K9V→5K9W), {c('1T49','5K9W','loop_176_187_rmsd_fitted_frame_A'):.3f} Å (1T49→5K9W), {c('1T49','5K9V','loop_176_187_rmsd_fitted_frame_A'):.3f} Å (1T49→5K9V)",
         "Independently reproduced", "V3: legacy-PDB parser + quaternion fit + Bio.PDB.Superimposer; largest difference from the primary table "
         f"{max(e['max_abs_difference_A'] for e in T['V3_rmsd']['evidence'].values()):.1e} Å. Also reproduced by the technician's audit in `independent/primary_agreement.json` (written outside this session)."),
        (f"Asp181 Cα displacement {c('5K9V','5K9W','asp181_CA_displacement_A'):.3f} / {c('1T49','5K9W','asp181_CA_displacement_A'):.3f} / {c('1T49','5K9V','asp181_CA_displacement_A'):.3f} Å; fit RMSD {c('5K9V','5K9W','fit_rmsd_A'):.3f} / {c('1T49','5K9W','fit_rmsd_A'):.3f} / {c('1T49','5K9V','fit_rmsd_A'):.3f} Å",
         "Independently reproduced", "V3 (same evidence)."),
        ("Result is insensitive to including the loop in the fit or pruning the core", "Independently reproduced", "V3 recomputes the loop-included fit; the pruned-core rows are in `results/structural_comparison.csv` (re-executed in V8)."),
        ("α7 (285–296) has coordinates only in 5K9W", "Independently verified", "`results/alpha7_coverage.csv`; unobserved-residue records in `structure_metadata.json`; legacy-PDB residue counts in V2."),
        (f"Ligand-892 neighbourhood: {pj['n_neighbourhood_residues']['4.0A']} residues within 4.0 Å, {pj['n_neighbourhood_residues']['5.0A']} within 5.0 Å", "Independently verified",
         "V4: brute-force recomputation from the legacy PDB file gives identical residue sets at 3.5/4.0/4.5/5.0 Å."),
        (f"Ligand to Cys215 Sγ: {min(T['V4_pocket']['evidence']['ligand_to_Cys215_SG_min_A']['primary']):.1f} / {max(T['V4_pocket']['evidence']['ligand_to_Cys215_SG_min_A']['primary']):.1f} Å (two Sγ conformers)", "Independently verified; consistent with published evidence",
         "V4 recomputation; Wiesmann 2004 abstract: site 'approximately 20 Å from the catalytic site'."),
        (f"Protein surface occluded by the ligand: {sasa['primary_own_implementation']:.0f} Å²", "Independently verified",
         f"V4: Biopython Shrake–Rupley gives {sasa['biopython_shrake_rupley']:.0f} Å² ({100 * sasa['relative_difference']:.1f} % difference)."),
        (f"Ligand position coincides with Trp291/α7 residues of 5K9W (Trp291 {T['V4_pocket']['evidence']['Trp291_min_distance_to_superposed_ligand_A']:.2f} Å in the core frame; {occ['5K9W']['closest_residues'][0]['min_A']:.2f} Å in a local α3/α6 frame)",
         "Consistent with published evidence", "`results/ligand892_site_occupancy.csv`, `results/review_followup.json`; Keedy 2018: BB compounds bind 'the space normally occupied by the regulatory C-terminal α7 helix'. Not recomputed by a separate implementation."),
        (f"Asp181 Cα–Cys215 Cα: 5K9W {dist('5K9W','Asp181 CA - Cys215 CA'):.2f}, 5K9V {dist('5K9V','Asp181 CA - Cys215 CA'):.2f}, 1T49 {dist('1T49','Asp181 CA - Cys215 CA'):.2f} Å", "Consistent with published evidence",
         "Deposited titles 'closed state'/'open state'; V5. The technician's `independent/case_distances.csv` reports the same 1T49 value."),
        ("Loop-window contact differences (Asp181–Arg221, Lys120–Asp181, Phe182–Gln266 in 5K9W only)", "Independently verified (re-executed); not recomputed by a second implementation",
         "`results/contact_differences.csv`; cutoff sensitivity in `results/review_followup.json`."),
        (f"Lattice contacts: loop atoms within 4 Å of a symmetry mate — 5K9W {int(loopc.loc['5K9W','n_group_atoms_within_4A_of_mate'])}, 5K9V {int(loopc.loc['5K9V','n_group_atoms_within_4A_of_mate'])}, 1T49 {int(loopc.loc['1T49','n_group_atoms_within_4A_of_mate'])}",
         "Hypothesis supported by limited evidence", "Single implementation (`analysis/review_followup.py`, REMARK 290 operators); consistent with Keedy 2018's remark that 1SUG is the only apo crystal with a loop free of lattice contacts. Not independently recomputed."),
        ("Inhibitor binding disorders α7 and thereby stabilises the open loop", "Hypothesis supported by limited evidence", "Published mechanism; the static overlap (H1) is consistent with it. Causation and dynamics are untested here."),
        ("Loop state tracks α7 order in these crystals (H3)", "Inconclusive", "Four structures; ligand state, crystal form and lattice contacts are confounded."),
        ("Tetra-1 predicted an inhibitor-like conformation (12.5 Å) from sequence plus mechanism prompt", "Not reproduced", "No prediction files, prompts or logs available; no prediction backend available. The claim remains developer-reported."),
    ]
    L = ["# Verification report", "",
         f"Generated by `analysis/write_reports.py` from `verification_results.json` (run {ver['generated_utc'][:19]}Z; {ver['n_pass']}/{ver['n_tests']} checks passed).", "",
         "Independent numerical verification uses a different input format (legacy PDB), a separately written parser, a different superposition algorithm "
         "(Horn quaternion; Bio.PDB.Superimposer as a third), brute-force distances and Biopython's SASA. A further audit written outside this session "
         "by the laboratory technician is in `independent/`; it is cited where it bears on a result but is not this agent's work.", "",
         "## Required checks", "", "| # | Check | Status | Method |", "|---|---|---|---|"]
    for t in ver["tests"]:
        L.append(f"| {t['requirement']} | {t['description']} | **{t['status']}** | {t['method']} |")
    L += ["", "## Classification of results", "", "| Result | Classification | Exact evidence |", "|---|---|---|"]
    for r in rows:
        L.append(f"| {r[0]} | **{r[1]}** | {r[2]} |")
    L += ["", "## Comparison with published statements (check 5)", ""]
    for x in T["V5_published"]["evidence"]:
        L.append(f"- *Published:* {x['published']}  \n  *Computed:* {x['computed']}  \n  *Verdict:* {x['verdict']}")
    L += ["", "## Discrepancies and unresolved issues (check 6)", ""]
    for d in T["V6_discrepancies"]["evidence"]:
        L.append(f"- **{d['issue']}** — {d['detail']} *Status:* {d['status']}.")
    L += ["", "## Review", "",
          "The Open-Science Reviewer could not be invoked from this session (see `provenance/reviewer_findings.md`). A tool-less LLM critique was used instead and "
          "its points were answered with additional computation (`analysis/review_followup.py`). That critique is not independent numerical verification and is not counted as such.", "",
          "## Environment", "", "```json", json.dumps(ver["environment"], indent=1), "```"]
    (ROOT / "verification_report.md").write_text("\n".join(L) + "\n")

    # ------------------------------------------------------------------ reviewer findings
    rv = json.loads((ROOT / "provenance" / "llm_review_round1.json").read_text())
    a = fu["a_ligand892_to_loop"]
    sug = pd.read_csv(RES / "sug_control.csv").set_index("reference")
    resp = [
        ("Claim 5 overstated: 'no direct contact' rests on 4.13 Å vs a 4.0 Å cutoff and the window was misquoted",
         f"Reworded. No atom of 176–187 is within 4.0 Å; Ser187 Oγ is at {a['Ser187']['min_A']:.2f} Å; the nearest atom of 176–186 is {a['residues_176_186']['min_A']:.1f} Å away and the WPD tripeptide {a['WPD_tripeptide_179_181']['min_A']:.1f} Å (`results/review_followup.json`, section a)."),
        ("Claim 7 overstated: 1SUG judged closed from one distance; active-site contents unchecked",
         f"1SUG was put through the same core fit: loop RMSD {sug.loc['5K9W','loop_176_187_rmsd_fitted_frame_A']:.2f} Å against 5K9W and {sug.loc['5K9V','loop_176_187_rmsd_fitted_frame_A']:.2f} Å against 5K9V. "
         "Non-water groups within 8 Å of Cys215 Sγ: 5K9W TCS401; 5K9V a chloride ion (4.2 Å); 1T49 none; 1SUG a glycerol (6.3 Å). 'Apo' here means no active-site inhibitor; 5K9V and 1SUG are not ligand-free in the strict sense."),
        ("Crystal packing unexamined", "Symmetry mates generated from REMARK 290 operators. Closed 5K9W loop: no lattice contact. Open loops of 5K9V (11 atoms) and 1T49 (Phe182) are at lattice contacts. This is now a stated confound (`results/crystal_contacts.csv`, Figure 9)."),
        ("Order and occupancy not analysed", "Loop-window atoms have no alternate conformers and full occupancy in all three entries; mean loop Cα B is 1.1–1.2× the 2–280 mean (`results/loop_order_metrics.csv`). Electron density was not examined; listed as a limitation."),
        ("Construct boundaries not checked", "Constructs span 1–301 (5K9W, 5K9V) and 1–298 (1T49) per SEQRES and struct_ref_seq, so residues 281/283 onward were present but not modelled (`results/alpha7_coverage.csv`, V2)."),
        ("Single hard contact cutoff", "Loop contact differences re-evaluated at 3.5 and 4.5 Å; 5K9V and 1T49 agree with each other for 15, 14 and 12 of the 15 pairs at 3.5, 4.0 and 4.5 Å (`results/review_followup.json`, section d)."),
        ("Clash depends on the global frame", f"Local α3/α6 fit (32 Cα): Trp291 {occ['5K9W']['closest_residues'][0]['min_A']:.2f} Å; {occ['5K9W']['n_protein_heavy_atoms_within_2A']} heavy atoms within 2.0 Å — the same as in the global frame."),
        ("Lys239 difference inside the fit set unexplained", "Reported, quantified with a pruned-core control, and shown to coincide with a lattice contact in all three crystals; not explained mechanistically."),
        ("Sample size; no survey of other entries", "Not addressed. Stated as a limitation."),
        ("Wording: 'adopts two positions' → 'is modelled in two positions in these depositions'; ligand clash is not specific to α7", "Adopted in `hypotheses.md` and the laboratory panels; the 5K9V overlaps with Phe196/Asn193/Glu200 are reported alongside the α7 overlaps."),
    ]
    L = ["# Reviewer findings", "",
         "## Status of the Open-Science Reviewer", "",
         "The platform Reviewer could **not** be used from this agent session: `host.delegate` is unavailable, `host.agents.list()` returned no Specialists, and "
         "`host.sessions.read({kind: 'review'})` failed with \"This Session is not linked to the current conversation\". No Reviewer assessment exists for this work.", "",
         "## Substitute: tool-less LLM critique", "",
         f"A single `host.llm` call (model `{rv['model']}`, {rv['requested_utc'][:19]}Z) was given eight claims and the numerical evidence and asked to judge support. "
         "This is the same model family as the author and had no tools, so it is a self-critique rather than an independent review, and it does not count as numerical verification. "
         "Full prompt and response: `provenance/llm_review_round1.json`.", "",
         "### Critique (verbatim)", "", rv["response"], "",
         "### Response to each point", "", "| Point raised | Action and evidence |", "|---|---|"]
    for p, r in resp:
        L.append(f"| {p} | {r} |")
    (ROOT / "provenance" / "reviewer_findings.md").write_text("\n".join(L) + "\n")

    # ------------------------------------------------------------------ timeline
    log = json.loads((ROOT / "provenance" / "run_log.json").read_text())
    ev = []
    for e in log["events"]:
        t = e.get("t_utc")
        if not t and e.get("start_ms"):
            t = iso(e["start_ms"])
        if not t and e.get("id"):
            try:
                t = iso(int(e["id"].split("-")[2]))
            except Exception:
                t = None
        ev.append(dict(time_utc=t, time_basis=("recorded timestamp" if e.get("t_utc") else "platform run start" if e.get("start_ms") else "platform activity id stamp" if t else "order only (no timestamp returned)"),
                       duration_s=(round((e["end_ms"] - e["start_ms"]) / 1000, 1) if e.get("end_ms") else None), phase=e["phase"], kind=e["kind"], run_id=e.get("id"),
                       what=e["what"], outcome=e["outcome"]))
    (ROOT / "provenance" / "research_timeline.json").write_text(json.dumps(dict(note=log["note"], events=ev), indent=1))
    L = ["# Research timeline", "", "Built from `provenance/run_log.json` (events recorded from tool results during the session). Events keep their recorded order; "
         "times are platform timestamps where one was returned.", "", "| # | Time (UTC) | Phase | Event | Outcome | Run id |", "|---:|---|---|---|---|---|"]
    for i, e in enumerate(ev, 1):
        L.append(f"| {i} | {e['time_utc'] or '—'} | {e['phase']} | {e['what']} | {e['outcome']} | {('`' + e['run_id'] + '`') if e['run_id'] else '—'} |")
    (ROOT / "research_timeline.md").write_text("\n".join(L) + "\n")

    # ------------------------------------------------------------------ summary numbers for the laboratory
    summ = dict(
        pairs={f"{m}->{r}": {k: float(core.loc[(m, r), k]) for k in ("n_fit_CA", "fit_rmsd_A", "rmsd_all_CA_2_280_A", "loop_176_187_rmsd_fitted_frame_A",
                                                                     "loop_176_187_rmsd_local_refit_A", "asp181_CA_displacement_A", "asp181_CG_displacement_A",
                                                                     "max_CA_displacement_outside_loop_A")} for m, r in core.index},
        asp181_cys215_CA={s: dist(s, "Asp181 CA - Cys215 CA") for s in sorted(set(rd.structure))},
        ligand892=dict(n_within_4A=pj["n_neighbourhood_residues"]["4.0A"], n_within_5A=pj["n_neighbourhood_residues"]["5.0A"], residues_4A=pj["neighbourhood_residues"]["4.0A"],
                       to_Cys215_SG_min_A=T["V4_pocket"]["evidence"]["ligand_to_Cys215_SG_min_A"]["primary"], sasa=pj["sasa"], occupancy=pj["ligand"]["occupancy"],
                       to_loop=a, Trp291_overlap_A=T["V4_pocket"]["evidence"]["Trp291_min_distance_to_superposed_ligand_A"]),
        lattice={s: dict(loop_atoms_within_4A=int(loopc.loc[s, "n_group_atoms_within_4A_of_mate"]), closest_A=float(loopc.loc[s, "min_distance_to_symmetry_mate_A"])) for s in loopc.index},
        verification=dict(n_pass=ver["n_pass"], n_tests=ver["n_tests"], generated_utc=ver["generated_utc"]),
        sources={"pairs": "results/structural_comparison.csv", "asp181_cys215_CA": "results/region_distances.csv", "ligand892": "results/pocket_analysis.json; results/review_followup.json",
                 "lattice": "results/crystal_contacts.csv", "verification": "verification_results.json"})
    (RES / "summary.json").write_text(json.dumps(summ, indent=1))
    print("reports written; timeline events:", len(ev))


if __name__ == "__main__":
    main()

if __name__ == "__main__":
    from append_review import main as append_native_review
    append_native_review()
