"""Step 13. Build black_hole_research_lab.html: one offline file with Three.js r160 inlined, the scene source
(scene/lab_app.js, scene/lab.css, scene/lab_template.html) and the session's data, logs, code and TeX excerpts embedded."""
import os, io, json, base64, glob, re
import numpy as np
from common import ROOT, RES, LOG, SRC, Tee, event, load_json, read_csv

SC = os.path.join(ROOT, "scene")


def f(x):
    return float(x)


def downscale_png(path, width=1000):
    from PIL import Image
    im = Image.open(path).convert("RGB")
    if im.width > width:
        im = im.resize((width, round(im.height * width / im.width)), Image.LANCZOS)
    im = im.quantize(colors=128, method=Image.Quantize.MEDIANCUT)
    buf = io.BytesIO(); im.save(buf, format="PNG", optimize=True)
    return "data:image/png;base64," + base64.b64encode(buf.getvalue()).decode()


def tex_excerpt(lines, a, b):
    return "\n".join(f"{i:5d}  {lines[i-1]}" for i in range(a, min(b, len(lines)) + 1))


def main():
    S = load_json("slope_constants.json"); T2 = load_json("table2_reanalysis.json"); FA = load_json("functional_analysis.json"); H = load_json("hp_hagedorn.json")
    Q = load_json("hp_quartic.json"); V = load_json("validation_summary.json"); X = load_json("extraction_summary.json"); CAP = load_json("figure_captions.json")["captions"]
    led = json.load(open(os.path.join(ROOT, "claim_ledger.json")))["claims"]; tl = json.load(open(os.path.join(ROOT, "research_timeline.json")))["events"]
    q = Q["quartic"]

    def cls(v):
        v = v.lower()
        if v.startswith("not verified") or v.startswith("quoted"):
            return "no"
        if "arithmetic" in v or v.startswith("sums reproduced") or v.startswith("internal") or v.startswith("ratios reproduced"):
            return "ar"
        if v.startswith("independently reproduced") or v.startswith("reproduced within"):
            return "ok"
        return "co"
    for x in led:
        x["cls"] = cls(x["verdict"])
    checks = read_csv("all_checks.csv"); by = {}
    for r in checks:
        by.setdefault(r["script"], [0, 0]); by[r["script"]][1] += 1; by[r["script"]][0] += r["pass"] == "True"
    fb = read_csv("functional_bounds.csv")
    fresh = [dict(c=int(r["c"]), P=int(r["P"]), ratio=f(r["c_over_Delta1"])) for r in fb]
    best = {}
    for r in fresh:
        if r["c"] >= 24 and (r["c"] not in best or r["P"] > best[r["c"]]["P"]):
            best[r["c"]] = r
    d = np.load(os.path.join(RES, "fd_field_xstar.npz")); x, y, U = d["x"], d["y"], d["U"]
    ix = np.unique(np.round(np.linspace(0, len(x) - 1, 61)).astype(int)); iy = np.unique(np.round(np.linspace(0, len(y) - 1, 17)).astype(int))
    xq, yq, Uq = x[ix], y[iy], U[np.ix_(ix, iy)]
    xf = np.concatenate([-xq[::-1], xq[1:]]); Uh = np.concatenate([Uq[::-1, :], Uq[1:, :]], axis=0)
    yf = np.concatenate([-yq[::-1], yq[1:]]); Uf = np.concatenate([Uh[:, ::-1], Uh[:, 1:]], axis=1)
    btex = open(os.path.join(SRC, "bootstrap.tex")).read().split("\n")
    tex = {
        "[B] Theorem 1 and the class (sec. 2.6), lines 889-978": tex_excerpt(btex, 889, 978),
        "[B] Half-mass condition (sec. 2.4), lines 764-822": tex_excerpt(btex, 764, 822),
        "[B] The gap and Conjecture 1 (sec. 4.5-4.6), lines 1374-1473": tex_excerpt(btex, 1374, 1473),
        "[B] Numerical evidence and Table 2 (sec. 5), lines 1475-1618": tex_excerpt(btex, 1475, 1618),
        "[B] Optimality statements (sec. 6.1-6.2), lines 1625-1722": tex_excerpt(btex, 1625, 1722),
        "[B] Majorant, closed form, deficit (sec. 6.5-6.8), lines 1893-2210": tex_excerpt(btex, 1893, 2210),
    }
    for fn in ("02_free.tex", "03_landau.tex", "05_anatomy.tex", "06_computation.tex", "07_result.tex", "08_checks.tex", "B_series.tex", "C_howdone.tex"):
        L = open(os.path.join(SRC, "hawking_page", "sec", fn)).read().split("\n")
        tex[f"[HP] sec/{fn} (complete)"] = tex_excerpt(L, 1, len(L))
    code = {os.path.basename(p): open(p).read() for p in sorted(glob.glob(os.path.join(ROOT, "code", "*.py")))}
    code["scene/lab_app.js"] = open(os.path.join(SC, "lab_app.js")).read()
    logs = {}
    for p in sorted(glob.glob(os.path.join(LOG, "*.log"))):
        t = open(p).read()
        logs[os.path.basename(p)] = t if len(t) < 40000 else t[:20000] + "\n… [middle omitted in the embedded copy; full file in logs/] …\n" + t[-18000:]
    term = [l for l in open(os.path.join(LOG, "s02_slope_endpoint.log")).read().split("\n") if "PASS" in l or "root" in l or "arcsinh" in l][:8]
    term += [l.strip() for l in open(os.path.join(LOG, "s09_functional_analysis.log")).read().split("\n") if l.startswith(("fresh", "certificates", "half-mass", "  c=4", "  c=12"))][:6]
    term += [l.strip() for l in open(os.path.join(LOG, "s07_hp_series_quartic.log")).read().split("\n") if "b/g^4 =" in l or "partial sum" in l][:4]
    term += [l.strip() for l in open(os.path.join(LOG, "validate_all.log")).read().split("\n") if "SUMMARY" in l]
    term = ["$ python code/s02_slope_endpoint.py ; s09 ; s07 ; validate_all"] + [re.sub(r"\s+", " ", l).strip() for l in term]
    figs = {os.path.basename(p)[:-4]: downscale_png(p) for p in sorted(glob.glob(os.path.join(ROOT, "figures", "fig*.png")))}
    tr = read_csv("hp_temperatures.csv"); dr = read_csv("table2_window_drift.csv")
    D = dict(
        meta=dict(built_utc=__import__("common").now(), n_functionals=FA["n_points"]),
        constants=dict(xs=f(S["x_star"]), LV=f(S["Lambda_V"]), Aopt=f(S["A_opt"]), tangency_diff=S["s_tangency_minus_xstar"], beta0=q["beta0"], I=q["I"], q4=q["q4"], q4crit=q["q4_crit"], b=q["b_over_g4"],
                       q4here=q["q4_resummed_here"], absb_lambda1=abs(q["b_over_lambda2"]), Lfit=T2["fit_central"]["Lambda"], r0=T2["remainder"]["fit_r0"], r1=T2["remainder"]["fit_r1"],
                       ex4=FA["anchor_c4"]["excess"], ex12=FA["anchor_c12"]["excess"]),
        checks=dict(n=len(checks), **{"pass": sum(r["pass"] == "True" for r in checks)}, by=[[k, v[0], v[1]] for k, v in by.items()]),
        validation=dict(n=V["n"], **{"pass": V["n_pass"]}),
        sources=dict(manifest_ok=all(X["manifest_match"].values()), sha=dict(bootstrap=X["sha256"]["bootstrap.tex"], hp=X["sha256"]["hawking_page.tex"])),
        table2=[dict(c=int(r["c"]), pc=r["Pmax_over_c"], D=f(r["Delta_inf"]), sig=f(r["sigma"]), ratio=r["ratio_printed"], rr=f(r["ratio_recomputed"]), impl=r["impl"]) for r in read_csv("table2_extracted.csv")],
        drift=[dict(lo=int(f(r["c_lo"])), hi=int(f(r["c_hi"])), Llog=f(r["Lambda_logform"]), Lcube=f(r["Lambda_cuberoot_form"])) for r in dr],
        ladder=[dict(entry=r["entry"], Lambda=f(r["Lambda"]), status=r["status"], source=r["source"]) for r in read_csv("slope_ladder.csv")],
        fresh=fresh, freshBest=list(best.values()),
        gamma=[dict(s=f(r["s"]), g=f(r["gamma_tip"]), u0=f(r["U_s_at_0"])) for r in read_csv("gamma_tip.csv")],
        fdgen=[dict(s=f(r["s"]), g=f(r["gamma_tip_fd"])) for r in read_csv("fd_general_s.csv")],
        field=dict(x=[round(float(v), 4) for v in xf], y=[round(float(v), 4) for v in yf], U=[round(float(v), 4) for v in Uf.flatten()]),
        series=[dict(s=r["series"], n=int(r["n"]), coeff=r["coeff"], exact=r["exact_rational"] == "True", term=f(r["term_at_yH"]), partial=f(r["partial_sum"])) for r in read_csv("hp_series_resum.csv")],
        temps=[dict({"lambda": f(r["lambda"])}, Tmin=f(r["T_min_exact"]), Tc=f(r["T_c_exact"]), TH=f(r["T_H_exact"]), wc=f(r["window_c_exact"]), wl=f(r["window_c_leading"]), uc=f(r["u_c_exact"])) for r in tr],
        ledger=led, timeline=tl, captions=CAP, figs=figs, tex=tex, code=code, logs=logs, terminal=term)
    out = write_html(D)
    event("build", "black_hole_research_lab.html built", f"{os.path.getsize(out)/1e6:.2f} MB single file; three.js r160 inlined; {len(figs)} figures, {len(code)} code files, {len(logs)} logs, {len(tex)} TeX excerpts embedded",
          outputs=["black_hole_research_lab.html", "scene/lab_app.js", "scene/lab_data.json"])


def orbit_assets():
    from PIL import Image
    def webp(name):
        buf = io.BytesIO()
        with Image.open(os.path.join(SC, "orbit", name + ".png")) as im:
            im.save(buf, "WEBP", quality=92, method=6)
        return "data:image/webp;base64," + base64.b64encode(buf.getvalue()).decode("ascii")
    def field(name):
        with open(os.path.join(SC, "orbit", name + ".png"), "rb") as source:
            return "data:image/png;base64," + base64.b64encode(source.read()).decode("ascii")
    return json.dumps(dict(accretion=webp("accretion"), diskOrbits=field("accretion-orbits"),
                           plasma=field("plasma-filaments"), sky=webp("sky"),
                           worlds=webp("worlds"), surfaces=[webp(f"surface-{i}") for i in range(1, 7)]),
                      separators=(",", ":"))


def write_html(D):
    for name in ("lab_app.js", "orbit/build_assets.py"):
        with open(os.path.join(SC, name)) as f:
            D["code"]["scene/" + name] = f.read()
    for name in ("s11_ledger_reports.py", "s13_build_lab.py"):
        with open(os.path.join(ROOT, "code", name)) as source:
            D["code"][name] = source.read()
    data = json.dumps(D, ensure_ascii=False, separators=(",", ":")).replace("</", "<\\/").replace("<!--", "<\\u0021--")   # keep the JSON valid and inert inside <script>
    three = open(os.path.join(SC, "vendor", "three.module.min.js")).read()
    i = three.rindex("export{"); j = three.rindex("}")
    pairs = [p.split(" as ") for p in three[i + 7:j].split(",")]
    assert all(len(p) == 2 for p in pairs) and len(pairs) > 400
    three_inline = three[:i] + "window.THREE={" + ",".join(f"{b.strip()}:{a.strip()}" for a, b in pairs) + "};\n"
    assert "</script" not in three_inline.lower()
    app = open(os.path.join(SC, "lab_app.js")).read()
    assert "</script" not in app.lower()
    html = open(os.path.join(SC, "lab_template.html")).read()
    parts = {"ORBIT": orbit_assets(), "CSS": open(os.path.join(SC, "lab.css")).read(), "DATA": data, "THREE": three_inline, "APP": app}
    assert all(html.count("/*__" + k + "__*/") == 1 for k in parts)
    html = re.sub(r"/\*__(CSS|DATA|THREE|APP|ORBIT)__\*/", lambda m: parts[m.group(1)], html)      # single pass: embedded text may itself contain the markers
    from paper_reader import attach_reader
    html = attach_reader(html, ROOT)
    out = os.path.join(ROOT, "black_hole_research_lab.html")
    open(out, "w", encoding="utf-8").write(html)
    json.dump(D, open(os.path.join(SC, "lab_data.json"), "w"), ensure_ascii=False)
    ext = re.findall(r"""(?:src|href)=["'](https?:[^"']+)""", html.replace(three_inline, "").replace(data, ""))
    print(f"wrote black_hole_research_lab.html: {os.path.getsize(out)/1e6:.2f} MB (three.js {len(three_inline)/1e6:.2f} MB, data {len(data)/1e6:.2f} MB, app {len(app)/1e3:.0f} kB)")
    print(f"embedded: {len(D['figs'])} figures, {len(D['code'])} source files, {len(D['logs'])} logs, {len(D['tex'])} TeX excerpts, {len(D['ledger'])} claims, {len(D['timeline'])} timeline events; external URLs referenced by markup: {ext}")
    return out


if __name__ == "__main__":
    import sys
    if "--visual-only" in sys.argv:
        with open(os.path.join(SC, "lab_data.json")) as f:
            write_html(json.load(f))
    else:
        with Tee("s13_build_lab"):
            main()
