"""Step 12. Build and EXECUTE research_notebook.ipynb.  The notebook is portable: it uses only relative paths, re-runs
the fast calculations live, loads the slow ones from results/, and embeds the figures.

Execution: a Jupyter kernel needs local sockets, which the sandbox of this session forbids (nbclient fails with
PermissionError on bind).  The cells are therefore executed in order, in one shared namespace, by the in-process executor
below; stdout and displayed images are stored as ordinary nbformat outputs with execution counts.  With sockets available,
`python code/s12_build_notebook.py --kernel` (or `jupyter nbconvert --execute`) re-executes it through a real kernel."""
import os, sys
import nbformat as nbf
from nbclient import NotebookClient
from common import ROOT, Tee, event

M, C = nbf.v4.new_markdown_cell, nbf.v4.new_code_cell
cells = [
M("# Research notebook — independent reproduction of two AI-assisted black-hole physics papers\n\n"
  "[B] *The Spinless Modular Bootstrap at Large Central Charge* (Hexagon 2611.00174v1) and [HP] *The Hawking–Page Transition at Weak Coupling* (Hexagon 2611.00175v1).\n\n"
  "Run from the package root (the folder containing `code/`, `results/`, `figures/`, `sources/`). Fast steps are recomputed live in the cells below; slow steps "
  "(multiprecision functional solver, finite differences) are loaded from `results/` and can be regenerated with the scripts in `code/` (see `research_report.md` §6)."),
C("import os, sys, json, csv, math\nif not os.path.isdir('code') and os.path.isdir('../code'): os.chdir('..')\nsys.path.insert(0, 'code')\nimport numpy as np, mpmath as mp\nfrom IPython.display import Image, display\n"
  "def table(name, n=None, cols=None):\n    rows = list(csv.DictReader(open(os.path.join('results', name))))\n    cols = cols or list(rows[0].keys())\n    print(' | '.join(cols))\n"
  "    for r in rows[:n]:\n        print(' | '.join(str(r[c])[:22] for c in cols))\n    print(f'[{len(rows)} rows in results/{name}]')\n"
  "print('python', sys.version.split()[0], '| numpy', np.__version__, '| mpmath', mp.__version__)"),
M("## 1. Sources and extracted tables (parsed from TeX, not retyped)"),
C("X = json.load(open('results/extraction_summary.json'))\nprint('manifest hash matches:', X['manifest_match'])\nprint('Table 2 rows:', X['table2']['n_rows'], '| ratio rounding exceptions:', X['table2']['ratio_exceptions'])\n"
  "table('table2_extracted.csv', cols=['c','Pmax_over_c','Delta_inf','sigma','ratio_printed','ratio_recomputed','impl','provenance'])"),
M("## 2. Primary study — the endpoint of the optimal-slope argument, solved live three ways\n\n(i) root of $\\sinh\\pi x=1$; (ii) tangency condition for a slit at general position $s$ (Poisson integral derived for this reproduction); (iii) finite differences (loaded)."),
C("import s02_slope_endpoint as s02\nmp.mp.dps = 30\nxs = mp.asinh(1)/mp.pi\nroot, n = s02.bisect(lambda x: mp.sinh(mp.pi*x) - 1, mp.mpf('0.1'), mp.mpf('0.5'), mp.mpf(10)**-25)\n"
  "print('(i)  bisection root of sinh(pi x)=1 :', mp.nstr(root, 22))\nprint('     arcsinh(1)/pi                  :', mp.nstr(xs, 22))\nprint('     Lambda_V                       :', mp.nstr(1/(mp.mpf(1)/12 + xs**2/3), 15))\n"
  "for s in (0.24, 0.275, 0.285, 0.32):\n    print(f'(ii) gamma_tip({s}) = {float(s02.gamma_tip(mp.mpf(str(s)))[0]):+.4f}')\n"
  "st, n = s02.bisect(lambda s: s02.gamma_tip(s)[0], mp.mpf('0.2'), mp.mpf('0.36'), mp.mpf(10)**-18)\nprint('     tangency root s =', mp.nstr(st, 20), ' | s - x* =', mp.nstr(st - xs, 3))\n"
  "print('     Poisson U_{x*}(0) =', mp.nstr(s02.U_s_real(mp.mpf(0), xs), 12), '(closed form U_0 = -0.388747872)')\nF = json.load(open('results/fd_summary.json'))\n"
  "print('(iii) finite differences: U(0) Richardson =', round(F['U0_richardson'], 7), '| orders', [round(o, 2) for o in F['orders']], '| tip-coefficient root s =', round(F['s_root_fd'], 4))"),
C("display(Image('figures/fig04_tangency.png', width=900)); display(Image('figures/fig03_extremal_potential.png', width=900))"),
M("## 3. Fresh finite-order functionals (optimizer output of this session)\n\nA small case is solved live (c = 12, orders 2–10, with full certificates); the complete set is loaded."),
C("import s04_functional_newton as s04\nres = s04.run(12, 10, with_mass=True, save=False)\nprint('half-mass fraction at P=8:', [r['neg_mass_below_t1_over_M'] for r in res if 'neg_mass_below_t1_over_M' in r])"),
C("A = json.load(open('results/functional_analysis.json'))\nprint('points:', A['n_points'], '| route cross-check:', A['route_cross_check'])\nprint('anchor c=4 :', A['anchor_c4'])\nprint('anchor c=12:', A['anchor_c12'])\n"
  "print('half mass  :', {k: A['half_mass'][k] for k in ('n', 'max_dev', 'max_identity_violation')})\nprint('zeros      :', A['zeros_between_vacuum_and_t1'])\ntable('functional_extrapolation.csv')\n"
  "display(Image('figures/fig05_functional_convergence.png', width=900))"),
M("## 4. Table 2 reanalysis (published points are inputs) — live refit"),
C("rows = list(csv.DictReader(open('results/table2_extracted.csv')))\nc = np.array([float(r['c']) for r in rows]); D = np.array([float(r['Delta_inf']) for r in rows])\ny = (D - (c - 1)/12)/c\n"
  "A4 = np.vstack([c**0, c**(-2/3), c**-1.0, c**(-4/3)]).T\nco = np.linalg.lstsq(A4, y, rcond=None)[0]\nprint(f'refit, basis of [B] eq. (5-meas): xi = {co[0]:.6f}, Lambda = {1/(1/12+co[0]):.4f}, c^(-2/3) coefficient = {co[1]:.4f}')\n"
  "print('paper: xi = 0.026240 +- 0.000025, Lambda = 9.1263 +- 0.002; theory xi* = 0.0262361, Lambda_V = 9.12663, A_opt = 0.27666')\nLV = 9.126634025564685; AO = 0.2766597045\n"
  "r2 = D - c/LV - AO*c**(1/3)\nprint('remainder Delta - c/Lambda_V - A_opt c^(1/3): c=24 %+.4f ... c=2048 %+.4f' % (r2[0], r2[-1]))\n"
  "for lo, hi in ((24, 300), (300, 700), (500, 2048)):\n    m = (c >= lo) & (c <= hi)\n    a = np.linalg.lstsq(np.vstack([c[m], np.log(c[m]), c[m]**0]).T, D[m], rcond=None)[0]\n"
  "    b = np.linalg.lstsq(np.vstack([c[m], c[m]**(1/3), c[m]**0]).T, D[m], rcond=None)[0]\n    print(f'window [{lo},{hi}]: log form Lambda = {1/a[0]:.3f} | c^(1/3) form Lambda = {1/b[0]:.3f}')\n"
  "display(Image('figures/fig01_slope_drift.png', width=900)); display(Image('figures/fig02_fit_sensitivity.png', width=900))"),
M("## 5. Secondary study — Hagedorn equation, series, quartic coefficient (live)"),
C("import s06_hp_hagedorn as s06\nmp.mp.dps = 40\nfor nmax in (1, 4, 12, 48):\n    xr = s06.bisect(lambda x: sum(s06.z_modes(x, nmax)) - 1, mp.mpf('0.01'), mp.mpf('0.5'), mp.mpf(10)**-35)\n"
  "    print(f'mode cut-off {nmax:3d}: x_root = {mp.nstr(xr, 20)}  error {float(xr - (7 - 4*mp.sqrt(3))):+.2e}')\nxH = xr; yH = mp.sqrt(xH); b0 = -mp.log(xH)\n"
  "print('beta_0 =', mp.nstr(b0, 10), '| T_H0 =', mp.nstr(1/b0, 8), '| x z\\'(x) =', mp.nstr(xH*mp.diff(s06.z_cf, xH), 12), '| d1(x_H) =', mp.nstr(s06.d1(xH), 12))\n"
  "from fractions import Fraction\nS = list(csv.DictReader(open('results/hp_series_extracted.csv')))\nsums = {}\nfor w in 'ab':\n"
  "    sums[w] = sum((mp.mpf(Fraction(r['coeff_tex']).numerator)/Fraction(r['coeff_tex']).denominator)*yH**int(r['n']) for r in S if r['series'] == w)\n"
  "print('partial sums at y_H: a ->', mp.nstr(sums['a'], 8), ' b ->', mp.nstr(sums['b'], 8))\nQ = json.load(open('results/hp_quartic.json'))\n"
  "print('with tails: q4a =', round(Q['series']['a']['centre_power_law'], 5), ' q4b =', round(Q['series']['b']['centre_power_law'], 4), ' range', round(Q['series']['b']['min'], 4), round(Q['series']['b']['max'], 4))\n"
  "A2 = 1 - s06.zB_cf(xH**2) + s06.zF_cf(xH**2); I = mp.mpf('2.1222')/2 + 2*mp.mpf('0.16821')**2/A2; q4 = mp.mpf('-0.7340') + mp.mpf('-1.500')\n"
  "print('A2 =', mp.nstr(A2, 9), '| I =', mp.nstr(I, 7), '| b/g^4 =', mp.nstr(-4*b0**2*I + b0*q4, 7), '| q4 needed for b=0:', mp.nstr(4*b0*I, 6), '| margin', mp.nstr(4*b0*I - q4, 5))\n"
  "display(Image('figures/fig08_series.png', width=900)); display(Image('figures/fig09_quartic_budget.png', width=900))"),
M("## 6. Transition on the restricted holonomy domain (live)"),
C("import s08_hp_landau as s08\nth = s08.thresholds(-0.1)\nprint({k: round(v, 5) for k, v in th.items()})\nfor m2 in (0.08, 0.045, 0.02, -0.02):\n    print(f'm^2 = {m2:+.3f}: saddles', [(round(u, 4), kind) for u, S_, kind in s08.saddles(m2, -0.1)])\n"
  "table('hp_temperatures.csv', cols=['lambda', 'T_min_exact', 'T_c_exact', 'T_H_exact', 'window_c_exact', 'window_c_leading', 'u_c_exact', 'ordering_Tmin<Tc<TH'])\n"
  "display(Image('figures/fig10_landau_transition.png', width=950))"),
M("## 7. Verification summary and claim ledger"),
C("V = json.load(open('results/validation_summary.json')); L = json.load(open('claim_ledger.json'))\nchecks = list(csv.DictReader(open('results/all_checks.csv')))\n"
  "print('paper-referenced checks:', sum(r['pass'] == 'True' for r in checks), '/', len(checks), '| cross-algorithm comparisons:', V['n_pass'], '/', V['n'])\nprint('ledger verdicts:')\n"
  "for k, v in L['verdict_counts'].items(): print(f'  {v:2d}  {k}')\nprint()\nfor x in L['claims']:\n    print(f\"{x['id']}  {x['location'][:44]:44s} -> {x['verdict']}\")"),
M("## 8. Remaining figures"),
C("for f in ('fig06_functional_anatomy', 'fig07_hagedorn', 'fig11_gravity_comparison'):\n    display(Image(f'figures/{f}.png', width=900))\ncaps = json.load(open('results/figure_captions.json'))['captions']\nfor k in sorted(caps): print(caps[k][:160], '...')"),
]

def execute_inprocess(nb):
    import io, base64, contextlib, traceback, IPython.display as ipd
    captured = []
    def display(*objs, **kw):
        for o in objs:
            data = getattr(o, "data", None)
            if isinstance(o, ipd.Image) and isinstance(data, (bytes, bytearray)):
                captured.append(nbf.v4.new_output("display_data", data={"image/png": base64.b64encode(data).decode(), "text/plain": "<IPython.core.display.Image object>"},
                                                  metadata={"image/png": {"width": o.width}} if o.width else {}))
            else:
                captured.append(nbf.v4.new_output("display_data", data={"text/plain": repr(o)}))
    ipd.display = display
    ns = {"__name__": "__main__"}
    n = 0
    for cell in nb.cells:
        if cell.cell_type != "code":
            continue
        n += 1
        buf = io.StringIO(); captured.clear(); outs = []
        try:
            with contextlib.redirect_stdout(buf):
                exec(compile(cell.source, f"<cell {n}>", "exec"), ns)
        except Exception as e:
            outs.append(nbf.v4.new_output("error", ename=type(e).__name__, evalue=str(e), traceback=traceback.format_exc().split("\n")))
        if buf.getvalue():
            outs.insert(0, nbf.v4.new_output("stream", name="stdout", text=buf.getvalue()))
        cell.outputs = outs[:1] + list(captured) + outs[1:] if outs and outs[0].output_type == "stream" else list(captured) + outs
        cell.execution_count = n


if __name__ == "__main__":
    with Tee("s12_build_notebook"):
        nb = nbf.v4.new_notebook(cells=cells, metadata={"kernelspec": {"name": "python3", "display_name": "Python 3", "language": "python"}, "language_info": {"name": "python"},
                                                        "execution_note": "executed in-process by code/s12_build_notebook.py (no socket access for a Jupyter kernel in the session sandbox)"})
        os.chdir(ROOT)
        if "--kernel" in sys.argv:
            NotebookClient(nb, timeout=1200, kernel_name="python3", resources={"metadata": {"path": ROOT}}).execute()
            how = "Jupyter kernel (nbclient)"
        else:
            execute_inprocess(nb)
            how = "in-process executor"
        nbf.validate(nb)
        nbf.write(nb, os.path.join(ROOT, "research_notebook.ipynb"))
        nout = sum(len(c.get("outputs", [])) for c in nb.cells if c.cell_type == "code")
        nerr = sum(1 for c in nb.cells if c.cell_type == "code" for o in c.outputs if o.output_type == "error")
        nimg = sum(1 for c in nb.cells if c.cell_type == "code" for o in c.outputs if "image/png" in o.get("data", {}))
        print(f"executed research_notebook.ipynb via {how}: {len(nb.cells)} cells, {nout} outputs, {nimg} embedded images, {nerr} errors, size {os.path.getsize(os.path.join(ROOT,'research_notebook.ipynb'))/1e6:.2f} MB")
        for c in nb.cells:
            if c.cell_type == "code":
                for o in c.outputs:
                    if o.output_type == "error":
                        print("ERROR in cell", c.execution_count, o.ename, o.evalue)
        event("notebook", "research_notebook.ipynb built and executed", f"{how}; {len(nb.cells)} cells, {nimg} embedded figures, {nerr} errors (nbclient kernel launch was blocked by the sandbox: PermissionError on socket bind)")
