"""Assemble research_notebook.ipynb and execute it top to bottom with nbclient.

The notebook re-runs the analysis scripts in a fresh kernel, so its stored outputs are
genuine execution results. Run from the data directory:  python analysis/build_notebook.py
"""
import sys
from pathlib import Path
import nbformat as nbf
from nbformat.v4 import new_notebook, new_markdown_cell as md, new_code_cell as code

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

cells = [
    md("# PTP1B open/closed/allosteric-inhibitor comparison — executable research notebook\n\n"
       "Question: how does the WPD catalytic loop differ across apo PTP1B (5K9V), a catalytic-site ligand complex (5K9W) and a distal inhibitor "
       "complex (1T49); what constrains the inhibitor's location relative to the catalytic site; and which claims need evidence beyond these three structures?\n\n"
       "Every number is computed here from the deposited coordinate files in `data/raw/`. Core definition (from `research_plan.md`): chain A, Cα atoms of "
       "identical native residues 2–280, excluding 176–187 from the fit. Run this notebook from the project data directory."),
    code("import sys, json, hashlib, runpy, platform, subprocess\nfrom pathlib import Path\nimport numpy as np, pandas as pd, scipy, Bio, matplotlib\n"
         "from IPython.display import Image, display\nROOT = Path.cwd()\nassert (ROOT / 'data' / 'raw' / '5K9W.cif').exists(), 'run from the project data directory'\n"
         "pd.set_option('display.width', 220, 'display.max_columns', 30)\n"
         "print('python', sys.version.split()[0], '|', platform.platform())\n"
         "print({m.__name__: m.__version__ for m in (np, scipy, pd, Bio, matplotlib)})"),
    md("## 1. Source files: identifiers and checksums"),
    code("retr = json.loads((ROOT / 'provenance' / 'retrieval.json').read_text())\nrows = []\nfor r in retr:\n    data = (ROOT / 'data' / 'raw' / r['file']).read_bytes()\n"
         "    rows.append(dict(file=r['file'], bytes=len(data), sha256_matches=hashlib.sha256(data).hexdigest() == r['sha256'], retrieved_utc=r['retrieved_utc'][:19], url=r['url']))\n"
         "pd.DataFrame(rows)"),
    md("## 2. Metadata, residue mapping and Cα superposition\n\n`analysis/structure_alignment.py` writes `structure_metadata.json`, `structure_mapping.csv`, "
       "`results/structural_comparison.csv`, `results/per_residue_displacement.csv` and `results/alpha7_coverage.csv`."),
    code("_ = runpy.run_path('analysis/structure_alignment.py', run_name='__main__')"),
    code("meta = json.loads((ROOT / 'structure_metadata.json').read_text())\n"
         "pd.DataFrame([{'entry': k, 'title': m['title'], 'resolution_A': m['resolution_A'], 'space_group': m['space_group'], 'modelled': '%d-%d' % tuple(m['modelled_residue_range']),\n"
         "               'n_unobserved_residues': len(m['unobserved_residues']), 'ligands': ', '.join(sorted({l['comp_id'] for l in m['ligands']})),\n"
         "               'altloc_residues': ', '.join(m['altloc_residues']) or '-'} for k, m in meta.items()])"),
    md("### Principal comparison (core definition) and fit-sensitivity controls"),
    code("comp = pd.read_csv('results/structural_comparison.csv')\ncols = ['mobile', 'reference', 'fit_definition', 'n_fit_CA', 'fit_rmsd_A', 'rmsd_all_CA_2_280_A', 'loop_176_187_rmsd_fitted_frame_A',\n"
         "        'loop_176_187_rmsd_local_refit_A', 'asp181_CA_displacement_A', 'asp181_CG_displacement_A', 'max_CA_displacement_outside_loop_residue', 'max_CA_displacement_outside_loop_A']\n"
         "comp[cols].round(3)"),
    md("The loop window differs by about 3 Å between 5K9W and either of the other two entries, while 1T49 and 5K9V agree to 0.33 Å. Including the loop in the "
       "fit, or pruning mobile residues from the core, changes the loop RMSD by less than 0.1 Å.\n\n**α7:** the helix is modelled only in 5K9W, so no α7 comparison is possible."),
    code("a7 = pd.read_csv('results/alpha7_coverage.csv')\na7[[c for c in a7.columns if c.endswith('status') or c == 'native_resnum']].set_index('native_resnum').T"),
    md("## 3. Inhibitor neighbourhood (ligand 892 in 1T49)\n\nA declared 4.0 Å heavy-atom neighbourhood — not a cavity boundary; no pocket volume is computed."),
    code("_ = runpy.run_path('analysis/allosteric_pockets.py', run_name='__main__')"),
    md("## 4. Contact maps and declared distances"),
    code("_ = runpy.run_path('analysis/contact_analysis.py', run_name='__main__')"),
    md("## 5. Follow-up controls prompted by review\n\nIncludes the supplementary apo entry 1SUG through the same fit and crystal-lattice contacts from the REMARK 290 symmetry operators."),
    code("_ = runpy.run_path('analysis/review_followup.py', run_name='__main__')"),
    md("## 6. Figures (drawn only from the result tables)"),
    code("_ = runpy.run_path('analysis/make_figures.py', run_name='__main__')\nman = json.loads((ROOT / 'figures' / 'figure_manifest.json').read_text())\n"
         "for name, m in man.items():\n    print('FIGURE:', name, '|', m['title'], '| sources:', ', '.join(m['source_tables']))\n    display(Image(filename=str(ROOT / m['file']), width=820))"),
    md("## 7. Independent verification and re-execution\n\n`verification_tests.py` uses the legacy PDB files, its own parser, a quaternion superposition and Biopython's SASA, "
       "then re-runs the analysis scripts in fresh processes and compares table hashes."),
    code("pr = subprocess.run([sys.executable, 'verification_tests.py', '--rerun'], capture_output=True, text=True)\nprint(pr.stdout)\nprint(pr.stderr[-500:])\n"
         "ver = json.loads((ROOT / 'verification_results.json').read_text())\npd.DataFrame([{'id': t['id'], 'status': t['status'], 'classification': t['classification']} for t in ver['tests']])"),
    md("## 8. Reading the result\n\n- **Measured:** two loop positions among these depositions; the inhibitor sits about 21 Å from Cys215 Sγ on the α3/α6 face and overlaps the "
       "position that Trp291 and neighbouring α7 residues occupy in 5K9W.\n- **Not measurable:** α7 displacement (no coordinates outside 5K9W).\n"
       "- **Confound:** both open loops are at crystal-lattice contacts; the closed loop is not.\n- **Published mechanism vs hypothesis:** see `hypotheses.md`. "
       "A static comparison is not a causal or dynamic mechanism.\n- **Not reproduced:** the Tetra-1 prediction claim (no files, no backend)."),
]
nb = new_notebook(cells=cells, metadata={"kernelspec": {"name": "python3", "display_name": "Python 3", "language": "python"}, "language_info": {"name": "python"}})
out = ROOT / "research_notebook.ipynb"
nbf.write(nb, out)
if "--no-exec" not in sys.argv:
    from nbclient import NotebookClient
    import os
    kw = {}
    try:
        from jupyter_client.kernelspec import KernelSpecManager
        specs = KernelSpecManager().find_kernel_specs()
        if "python3" not in specs:
            raise RuntimeError("no python3 kernelspec")
    except Exception as e:
        print("kernelspec lookup:", e, "-> launching ipykernel with the current interpreter")
        from jupyter_client.manager import KernelManager
        class KM(KernelManager):
            def format_kernel_cmd(self, extra_arguments=None):
                return [sys.executable, "-m", "ipykernel_launcher", "-f", self.connection_file]
        kw["kernel_manager_class"] = KM
    client = NotebookClient(nb, timeout=600, resources={"metadata": {"path": str(ROOT)}}, **kw)
    client.execute()
    nbf.write(nb, out)
    n_out = sum(len(c.get("outputs", [])) for c in nb.cells if c.cell_type == "code")
    n_err = sum(o.get("output_type") == "error" for c in nb.cells if c.cell_type == "code" for o in c.get("outputs", []))
    print(f"executed {sum(c.cell_type == 'code' for c in nb.cells)} code cells; {n_out} outputs; {n_err} errors -> {out.name} ({out.stat().st_size} bytes)")
