"""Scene build script: assemble the self-contained offline laboratory HTML.

Embeds, in one file: three.js + GLTFLoader and 3Dmol.js (scene/vendor), the Blender GLB,
the experimental coordinates in the common 5K9W frame, every result table, the analysis
scripts, the executed notebook, the figures, the research documents and the provenance
timeline. Nothing is fetched at run time.

Run from the project data directory:  python scene/build_html.py
Outputs: scene/ptp1b_research_lab.html and scene/html_build_record.json
"""
import csv
import base64, hashlib, json, math
from datetime import datetime, timezone
from pathlib import Path
import pandas as pd

ROOT = Path(__file__).resolve().parents[1]
SC = ROOT / "scene"


def text(p):
    return (ROOT / p).read_text(encoding="utf-8")


def table(p):
    df = pd.read_csv(ROOT / p)
    rows = []
    for rec in df.itertuples(index=False):
        row = []
        for v in rec:
            if isinstance(v, float) and math.isnan(v):
                v = None
            elif hasattr(v, "item"):
                v = v.item()
            if isinstance(v, float):
                v = round(v, 5)
            row.append(v)
        rows.append(row)
    with (ROOT / p).open(encoding="utf-8-sig", newline="") as handle:
        reader = csv.reader(handle)
        columns = next(reader)
        raw_rows = list(reader)
    if columns != list(df.columns) or len(raw_rows) != len(rows):
        raise ValueError(f"CSV header or record count mismatch: {p}")
    return dict(columns=columns, rows=rows, rawRows=raw_rows)


def main():
    B = {}
    B["meta"] = json.loads(text("structure_metadata.json"))
    B["summary"] = json.loads(text("results/summary.json"))
    B["layout"] = json.loads(text("scene/lab_layout.json"))
    B["refs"] = json.loads(text("provenance/references.json"))
    B["timeline"] = json.loads(text("provenance/research_timeline.json"))
    # coordinates: superposed experimental coordinates + the deposited HELIX/SHEET records
    B["pdb"] = {}
    for pid in ("5K9W", "5K9V", "1T49"):
        ss = [l for l in text(f"data/raw/{pid}.pdb").splitlines() if l.startswith(("HELIX ", "SHEET "))]
        B["pdb"][pid] = "\n".join(ss) + "\n" + text(f"processed/{pid}_chainA_in_5K9W_frame.pdb")
    tables = ["results/structural_comparison.csv", "results/per_residue_displacement.csv", "results/alpha7_coverage.csv", "results/altloc_sensitivity.csv",
              "results/ligand892_neighbourhood.csv", "results/ligand892_distances.csv", "results/ligand892_site_occupancy.csv",
              "results/ligand892_site_environment_change.csv", "results/region_distances.csv", "results/contact_differences.csv",
              "results/loop_contact_summary.csv", "results/contact_maps.csv", "results/crystal_contacts.csv", "results/loop_order_metrics.csv",
              "results/sug_control.csv", "structure_mapping.csv"]
    B["tables"] = {p: table(p) for p in tables}
    B["json"] = {p: json.loads(text(p)) for p in ("results/pocket_analysis.json", "results/review_followup.json", "verification_results.json", "environment.json",
                                                  "results/superposition_transforms.json", "figures/figure_manifest.json", "scene/blender_export_record.json")}
    if (ROOT / "independent/primary_agreement.json").exists():
        B["json"]["independent/primary_agreement.json"] = json.loads(text("independent/primary_agreement.json"))
    docs = ["research_question.md", "research_plan.md", "literature_review.md", "references.md", "feasibility_report.md", "source_verification.md", "hypotheses.md",
            "verification_report.md", "limitations.md", "research_timeline.md", "provenance/reviewer_findings.md", "provenance/source_selection.md"]
    B["docs"] = {p: text(p) for p in docs}
    if (ROOT / "independent/README.md").exists():
        B["docs"]["independent/README.md"] = text("independent/README.md")
    scripts = ["analysis/ptp1b_common.py", "analysis/structure_alignment.py", "analysis/allosteric_pockets.py", "analysis/contact_analysis.py", "analysis/review_followup.py",
               "analysis/make_figures.py", "verification_tests.py", "analysis/write_reports.py", "analysis/build_notebook.py", "analysis/retrieve.py",
               "scene/blender/build_lab.py", "scene/blender/export_lab.py", "scene/build_html.py", "scene/src/lab_ui.js", "scene/src/lab_scene.js"]
    B["scripts"] = {p: text(p) for p in scripts}
    man = B["json"]["figures/figure_manifest.json"]
    B["figures"] = {n: dict(title=m["title"], caption=m["caption"], sources=list(m["source_tables"]),
                            uri="data:image/png;base64," + base64.b64encode((ROOT / m["file"]).read_bytes()).decode()) for n, m in man.items()}
    # Offline readers preserve the source data behind plots, including the external numerical audit.
    B["docs"]["sources/Keedy2018_reading_copy.md"] = text("sources/Keedy2018_reading_copy.md")
    B["audit_figures"] = []
    for stem, caption, source in [
        ("S1_shell_sensitivity", "Residues included at each heavy-atom cutoff", "shell_sensitivity.csv"),
        ("S2_surface_occlusion", "Residue surface screened by the deposited inhibitor", "fixed_coordinate_sasa.csv"),
        ("S3_case_geometry", "Catalytic-loop distance across four experimental deposits", "case_distances.csv"),
        ("S4_surface_convergence", "Sensitivity of solvent-accessible area to numerical resolution", "sasa_convergence.csv"),
    ]:
        name = "independent/" + source
        B["tables"][name] = table(name)
        encoded = base64.b64encode((ROOT / "independent/figures" / (stem + ".png")).read_bytes()).decode()
        B["audit_figures"].append(dict(title=caption, source=name, uri="data:image/png;base64," + encoded))
    B["json"]["provenance/research_timeline.json"] = B["timeline"]
    B["json"]["results/summary.json"] = B["summary"]
    nb = json.loads(text("research_notebook.ipynb"))
    cells, n = [], 0
    fig_names = list(man)
    for c in nb["cells"]:
        src = "".join(c["source"])
        if c["cell_type"] == "markdown":
            cells.append(dict(type="markdown", source=src))
            continue
        n += 1
        outs, k = [], 0
        for o in c.get("outputs", []):
            if o["output_type"] == "stream":
                outs.append(dict(kind="stderr" if o.get("name") == "stderr" else "text", text="".join(o["text"])))
            elif "image/png" in o.get("data", {}):
                outs.append(dict(kind="figure", name=fig_names[k])); k += 1
            elif isinstance(o.get("data", {}).get("application/json"), dict) and "columns" in o["data"]["application/json"]:
                matrix = o["data"]["application/json"]
                outs.append(dict(kind="table", columns=matrix["columns"], rows=matrix["data"]))
            elif "text/plain" in o.get("data", {}):
                outs.append(dict(kind="text", text="".join(o["data"]["text/plain"])))
            elif o["output_type"] == "error":
                outs.append(dict(kind="stderr", text=f"{o.get('ename')}: {o.get('evalue')}"))
        cells.append(dict(type="code", n=n, source=src, outputs=outs))
    B["notebook"] = dict(cells=cells, executed_with=nb["metadata"].get("execution_record", {}).get("executed_with", "unknown"))
    glb = (SC / "ptp1b_laboratory.glb").read_bytes()
    B["glb"] = base64.b64encode(glb).decode()
    built = datetime.now(timezone.utc).isoformat()
    B["build"] = dict(built_utc=built, glb_sha256=hashlib.sha256(glb).hexdigest())

    bundle = json.dumps(B, allow_nan=False, ensure_ascii=False, separators=(",", ":")).replace("</", "<\\/")
    app = text("scene/src/lab_ui.js") + "\n" + text("scene/src/lab_scene.js") + \
        f"\ndocument.getElementById('buildinfo').textContent = 'Built {built[:19]}Z from the research package · fully offline · three.js r160 + GLTFLoader and 3Dmol.js embedded (licences in scene/vendor).';\n"
    three, mol = text("scene/vendor/three-gltf.min.js"), text("scene/vendor/3Dmol-min.js")
    for name, lib in (("three", three), ("3Dmol", mol), ("app", app)):
        assert "</script" not in lib.lower(), f"{name} contains a closing script tag"
    # Fill the template in one pass over the ORIGINAL template text: the embedded sources (including
    # this script) contain the marker strings themselves, so sequential replacement would be wrong.
    tpl = text("scene/src/template.html")
    fills = {"CSS": text("scene/src/lab.css"), "THREE": three, "MOL": mol, "BUNDLE": bundle, "APP": app}
    marks = sorted((tpl.index("/*" + k + "*/"), k) for k in fills)
    assert all(tpl.count("/*" + k + "*/") == 1 for k in fills)
    parts, at = [], 0
    for i, k in marks:
        parts += [tpl[at:i], fills[k]]
        at = i + len(k) + 4
    html = "".join(parts) + tpl[at:]
    out = SC / "ptp1b_research_lab.html"
    out.write_text(html, encoding="utf-8")
    external = [m for m in ("src=\"http", "href=\"http", "@import", "url(http") if m in text("scene/src/template.html") + text("scene/src/lab.css")]
    rec = dict(built_utc=built, file="scene/ptp1b_research_lab.html", bytes=out.stat().st_size, sha256=hashlib.sha256(out.read_bytes()).hexdigest(),
               embedded=dict(three_gltf_bytes=len(three), threeDmol_bytes=len(mol), glb_bytes=len(glb), bundle_bytes=len(bundle), app_bytes=len(app),
                             tables=len(B["tables"]), scripts=len(B["scripts"]), figures=len(B["figures"]), docs=len(B["docs"]), notebook_cells=len(cells),
                             timeline_events=len(B["timeline"]["events"]), structures=list(B["pdb"])),
               external_resource_references_in_template_or_css=external,
               note="Hyperlinks to DOIs in the literature panel are ordinary links; no script, style, font, model or data is loaded from the network.")
    (SC / "html_build_record.json").write_text(json.dumps(rec, indent=1))
    print(json.dumps(rec, indent=1))


if __name__ == "__main__":
    main()
