"""Step 1. Extract published numbers directly from the TeX sources (no retyping) and write sources.md.

Outputs
  results/table2_extracted.csv      [B] Table 2 (finite-c gaps, sigma, provenance I/II) + recomputed ratios
  results/hp_series_extracted.csv   [HP] App. B Tables (a_n, b_n, printed term sizes, printed partial sums)
  results/hp_nearbps_extracted.csv  [HP] section 7 near-BPS table
  results/hp_ym_extracted.csv       [HP] section 8 pure Yang-Mills table
  results/extraction_summary.json   hashes, line numbers, bibliography entries used for historical comparison
  sources.md
"""
import os, re, json, hashlib
from fractions import Fraction
from decimal import Decimal, getcontext
from common import ROOT, SRC, Tee, event, save_csv, save_json, now

getcontext().prec = 40


def sha256(p):
    h = hashlib.sha256()
    with open(p, "rb") as f:
        for blk in iter(lambda: f.read(1 << 20), b""):
            h.update(blk)
    return h.hexdigest()


def parse_sigma(s):
    s = s.strip().strip("$")
    m = re.match(r"([\d.]+)\\cdot10\^\{(-?\d+)\}", s)
    return float(m.group(1)) * 10 ** int(m.group(2)), s


def main():
    out = {"generated_utc": now()}
    # ---------------- hashes vs manifests
    files = {}
    for rel in ["bootstrap.tex", "bootstrap.pdf", "hawking_page.tex", "hawking_page.pdf"]:
        files[rel] = sha256(os.path.join(SRC, rel))
    man_b = json.load(open(os.path.join(SRC, "bootstrap_manifest.json")))
    man_h = json.load(open(os.path.join(SRC, "hawking_page_manifest.json")))
    manifest_ok = {}
    for man in (man_b, man_h):
        for lc in man["local_copies"]:
            manifest_ok[lc["name"]] = (files[lc["name"]] == lc["sha256"])
            print(f"sha256 {lc['name']}: {'matches manifest' if manifest_ok[lc['name']] else 'MISMATCH'}")
    secdir = os.path.join(SRC, "hawking_page", "sec")
    sec_hash = {f: sha256(os.path.join(secdir, f)) for f in sorted(os.listdir(secdir))}
    out["sha256"] = files; out["manifest_match"] = manifest_ok; out["hp_section_sha256"] = sec_hash
    out["manifests"] = {"bootstrap": man_b, "hawking_page": man_h}

    # ---------------- [B] Table 2
    tex = open(os.path.join(SRC, "bootstrap.tex")).read().split("\n")
    lab = [i for i, l in enumerate(tex) if "\\label{tab:2}" in l][0]
    start = max(i for i in range(lab) if "\\begin{table}" in tex[i])
    row_re = re.compile(r"^\s*(\d+)\s*&\s*([\d.]+)\s*&\s*([\d.]+)\s*&\s*(\$[^$]+\$)\s*&\s*([\d.]+)\s*&\s*(I+)\s*\\\\")
    rows = []
    for i in range(start, lab):
        m = row_re.match(tex[i])
        if not m:
            continue
        c = int(m.group(1)); pm = m.group(2); dstr = m.group(3); sig, sigstr = parse_sigma(m.group(4))
        rstr = m.group(5); impl = m.group(6)
        D = Decimal(dstr); ratio = Decimal(c) / D
        dec = len(rstr.split(".")[1])
        diff = abs(ratio - Decimal(rstr))
        half_ulp = Decimal(5) * Decimal(10) ** (-(dec + 1))
        # uncertainty of the ratio induced by sigma
        dr = float(ratio) * sig / float(D)
        cp = c - 1
        t1 = float(D) - cp / 12.0
        rows.append(dict(c=c, Pmax_over_c=float(pm), Delta_inf=dstr, sigma=sig, sigma_tex=sigstr, ratio_printed=rstr,
                         impl=impl, tex_line=i + 1, ratio_recomputed=float(ratio), ratio_absdiff=float(diff),
                         printed_decimals=dec, ratio_rounding_ok=bool(diff <= half_ulp),
                         ratio_sigma=dr, converged_Pmax_ge_4c=bool(float(pm) >= 4.0),
                         t1=t1, t1_over_c=t1 / c, x1=(3 * t1 / cp) ** 0.5, provenance="published_input"))
    assert len(rows) == 24, len(rows)
    hdr = list(rows[0].keys())
    save_csv("table2_extracted.csv", hdr, [[r[h] for h in hdr] for r in rows])
    nbad = [r["c"] for r in rows if not r["ratio_rounding_ok"]]
    print(f"[B] Table 2: {len(rows)} rows parsed from TeX lines {rows[0]['tex_line']}-{rows[-1]['tex_line']}; "
          f"impl I: {sum(r['impl']=='I' for r in rows)}, impl II: {sum(r['impl']=='II' for r in rows)}; "
          f"converged rows (Pmax/c>=4): {sum(r['converged_Pmax_ge_4c'] for r in rows)}")
    print(f"    printed ratio c/Delta reproduced to printed rounding in {len(rows)-len(nbad)}/{len(rows)} rows; exceptions: {nbad}")
    for r in rows:
        if not r["ratio_rounding_ok"]:
            print(f"    c={r['c']}: printed {r['ratio_printed']} recomputed {r['ratio_recomputed']:.7f} "
                  f"(diff {r['ratio_absdiff']:.2e}; ratio uncertainty from sigma {r['ratio_sigma']:.1e})")
    out["table2"] = {"n_rows": len(rows), "ratio_exceptions": nbad, "tex_lines": [rows[0]["tex_line"], rows[-1]["tex_line"]]}

    # quoted scalars of [B] found by regex (line numbers recorded)
    def find(pattern, text_lines):
        for i, l in enumerate(text_lines):
            m = re.search(pattern, l)
            if m:
                return {"line": i + 1, "match": m.group(0), "groups": m.groups()}
        return None
    quoted = {
        "xi_meas": find(r"\\xi\^\*_\{1,\\rm meas\}=([\d.]+)\\pm([\d.]+)", tex),
        "Lambda_meas": find(r"\\Lmeas=([\d.]+)\\pm([\d.]+)", tex),
        "Aopt": find(r"\\Aopt=\\frac\{\\abs\{a_1\}\\,\\arcsinh1\}\{\(3\\sqrt2\\,\\pi\^4\)\^\{1/3\}\}=([\d.]+)", tex),
        "U0": find(r"\\dd s=(-[\d.]+) ,", tex),
        "LV": find(r"\\LV:=1/\(\\frac1\{12\}\+\\xis\)=12\\pi\^2/\(\\pi\^2\+4\\arcsinh\^21\)=([\d.]+)", tex),
        "aht_fit": find(r"c/9\.08\+0\.439\\log c-0\.896", tex),
        "rate": find(r"0\.44\\,c'\^\{1/3\}\\log\^\{2/3\}c'", tex),
    }
    out["bootstrap_quoted"] = quoted
    for k, v in quoted.items():
        print(f"    [B] quoted {k}: {v['groups'] if v else 'NOT FOUND'} (line {v['line'] if v else '-'})")

    # ---------------- [HP] App. B series
    bl = open(os.path.join(secdir, "B_series.tex")).read().split("\n")
    ser = []
    which = None
    for i, l in enumerate(bl):
        if "$a_n$" in l and "&" in l:
            which = "a"
        if "$b_n$" in l and "&" in l:
            which = "b"
        m = re.match(r"^\s*(\d+)\s*&\s*\$(-?[\d./]+)\$\s*&\s*\$(-?[\d.]+)\$\s*&\s*\$(-?[\d.]+)\$", l)
        if m and which:
            n = int(m.group(1)); cs = m.group(2)
            exact = "/" in cs or "." not in cs
            ser.append(dict(series=which, n=n, coeff_tex=cs, coeff_float=float(Fraction(cs)),
                            exact_rational=bool(exact), term_printed=m.group(3), partial_printed=m.group(4), tex_line=i + 1))
    hdr = list(ser[0].keys())
    save_csv("hp_series_extracted.csv", hdr, [[r[h] for h in hdr] for r in ser])
    print(f"[HP] App. B: {sum(r['series']=='a' for r in ser)} coefficients a_n (n=6..16), "
          f"{sum(r['series']=='b' for r in ser)} coefficients b_n (n=4..10)")

    # ---------------- [HP] near-BPS table and YM table
    rl = open(os.path.join(secdir, "07_result.tex")).read().split("\n")
    nb = []
    for i, l in enumerate(rl):
        m = re.match(r"^\$(su[^$]+)\$\s*(bosonic|fermionic)?\s*&\s*\$([^$]+)\$\s*&\s*\$([^$]+)\$\s*&\s*\$([^$]+)\$\s*&\s*\$([^$]+)\$\s*&\s*\$([^$]+)\$", l)
        if m:
            nb.append(dict(sector=(m.group(1) + (" " + m.group(2) if m.group(2) else "")).replace(",", ";"), xH=m.group(3), A2=m.group(4),
                           c3=m.group(5), Q4=m.group(6), b_over_G2=m.group(7), tex_line=i + 1))
    hdr = list(nb[0].keys())
    save_csv("hp_nearbps_extracted.csv", hdr, [[r[h] for h in hdr] for r in nb])
    print(f"[HP] near-BPS table: {len(nb)} sectors")
    cl = open(os.path.join(secdir, "08_checks.tex")).read().split("\n")
    ym = []
    for i, l in enumerate(cl):
        m = re.match(r"^([A-Za-z ,]+?)\s*&\s*(3[a-n, 3]+)\s*&\s*\$(-?[\d.]+)\$\s*&\s*\$(-?[\d.]+)(\(\d+\))?\$", l)
        if m:
            ym.append(dict(vertex_class=m.group(1).replace(",", ";"), diagrams=m.group(2).replace(",", ";"), this_work=m.group(3), AMMPV=m.group(4),
                           AMMPV_err=(m.group(5) or ""), tex_line=i + 1))
    hdr = list(ym[0].keys())
    save_csv("hp_ym_extracted.csv", hdr, [[r[h] for h in hdr] for r in ym])
    print(f"[HP] pure-YM table: {len(ym)} vertex classes")

    # ---------------- bibliography entries used for the historical comparison
    def bib(text, keys):
        res = {}
        for k in keys:
            m = re.search(r"\\bibitem\{" + re.escape(k) + r"\}(.*?)(?=\\bibitem|\\end\{thebibliography\})", text, re.S)
            if m:
                s = re.sub(r"\\href\{[^}]*\}", "", m.group(1))
                s = re.sub(r"\\(emph|bfseries|ttfamily)", "", s)
                s = re.sub(r"[{}]", "", s); s = s.replace("~", " ").replace("\\'a", "á").replace("\\v c", "č").replace("\\vc", "č")
                s = s.replace("``", '"').replace("''", '"').replace("--", "–")
                res[k] = " ".join(s.split())
        return res
    btxt = "\n".join(tex)
    htxt = open(os.path.join(secdir, "refs.tex")).read()
    bib_b = bib(btxt, ["Hellerman", "FK", "FKS", "CLY", "AHT", "HMR", "ACHLT", "CohnElkies", "OpenAI", "BTZ", "Cardy86", "BCK", "CohnGoncalves"])
    bib_h = bib(htxt, ["HawkingPage", "WittenThermal", "Sundborg", "AMMPV1", "AMMPV2", "AMV", "SpradlinVolovich", "HW1", "HW2", "HW3",
                       "GrossWitten", "Wadia", "Hagedorn", "AtickWitten", "BeisertComplete", "BKS", "MusselYacoby", "HO1", "HKO"])
    out["bibliography"] = {"bootstrap": bib_b, "hawking_page": bib_h}
    lean_hits = [(f, i + 1) for f, L in [("bootstrap.tex", tex)] + [(f, open(os.path.join(secdir, f)).read().split("\n")) for f in sec_hash]
                 for i, l in enumerate(L) if re.search(r"\bLean\b|lean4|Isabelle|\bCoq\b|formaliz", l)]
    out["formal_proof_mentions"] = lean_hits
    print(f"formal-proof (Lean/Coq/Isabelle/formaliz*) mentions in TeX sources: {len(lean_hits)} {lean_hits[:5]}")
    save_json("extraction_summary.json", out)

    # ---------------- sources.md
    L = []
    L.append("# Sources\n")
    L.append(f"Generated by `code/s01_extract_sources.py` at {out['generated_utc']} (UTC). All hashes are SHA-256 of the local files.\n")
    L.append("## Primary sources (local, offline)\n")
    L.append("| ID | Title | Record | Version | Authors (manifest) | License | Local file | SHA-256 | Matches manifest |")
    L.append("|---|---|---|---|---|---|---|---|---|")
    for ID, title, man, names in (("B", "The Spinless Modular Bootstrap at Large Central Charge", man_b, ["bootstrap.tex", "bootstrap.pdf"]),
                                  ("HP", "The Hawking–Page Transition at Weak Coupling", man_h, ["hawking_page.tex", "hawking_page.pdf"])):
        for n in names:
            L.append(f"| {ID} | {title} | {man['record']} | v{man['version']} | {man['authors']} | {man['license']} | `sources/{n}` | `{files[n]}` | {'yes' if manifest_ok[n] else 'NO'} |")
    L.append("\n[HP] section files actually read (`sources/hawking_page/sec/`):\n")
    for f, h in sec_hash.items():
        L.append(f"* `{f}` — `{h[:16]}…`")
    L.append("\nSource-archive hashes recorded in the manifests (archives themselves are not in the package): "
             f"[B] `{man_b['source_archive_sha256']}`, [HP] `{man_h['source_archive_sha256']}`.\n")
    L.append("## Vendored software\n")
    L.append(f"* `scene/vendor/three.module.min.js` — Three.js r160 ES module, SHA-256 `{sha256(os.path.join(ROOT,'scene','vendor','three.module.min.js'))}`; "
             "MIT license in `scene/vendor/THREE-LICENSE.txt`. Used only by `black_hole_research_lab.html`.\n")
    L.append("## Where each published number used here sits in the TeX\n")
    L.append(f"* [B] Table 2 (24 rows): `sources/bootstrap.tex` lines {rows[0]['tex_line']}–{rows[-1]['tex_line']} → `results/table2_extracted.csv`.")
    for k, v in quoted.items():
        if v:
            L.append(f"* [B] `{k}`: line {v['line']}, text `{v['match']}`.")
    L.append("* [HP] App. B Tables (series coefficients): `sources/hawking_page/sec/B_series.tex` → `results/hp_series_extracted.csv`.")
    L.append("* [HP] §7 near-BPS table: `sec/07_result.tex` → `results/hp_nearbps_extracted.csv`; §8 pure-YM table: `sec/08_checks.tex` → `results/hp_ym_extracted.csv`.")
    L.append("* Scalar inputs of [HP] (c_3, Q_4, A_2, q_4 pieces, C_41, Harmark–Wilhelm coefficient) are quoted with section/equation in `code/s07_hp_quartic.py`.\n")
    L.append("## Historical literature used for comparison\n")
    L.append("These entries are copied from the bibliographies of the two TeX sources (they were **not** re-downloaded in this session; "
             "numbers attributed to them below are the values *as quoted in [B] or [HP]*, with the quoting section given in the report).\n")
    L.append("From [B]:\n")
    for k, v in bib_b.items():
        L.append(f"* **{k}** — {v}")
    L.append("\nFrom [HP]:\n")
    for k, v in bib_h.items():
        L.append(f"* **{k}** — {v}")
    L.append("\n## Formal proofs\n")
    L.append(f"Text search of all TeX sources for Lean/Coq/Isabelle/formaliz*: {len(lean_hits)} hits. "
             "Neither source ships a formal (Lean) development, and no Lean toolchain is installed in this runtime, so no Lean rerun was possible or attempted.\n")
    open(os.path.join(ROOT, "sources.md"), "w").write("\n".join(L) + "\n")
    print("wrote sources.md")
    event("extract", "Parsed published tables from TeX", f"Table 2: 24 rows; ratio rounding exceptions {nbad}; App. B series {len(ser)} coefficients",
          outputs=["results/table2_extracted.csv", "results/hp_series_extracted.csv", "sources.md"])


if __name__ == "__main__":
    with Tee("s01_extract_sources"):
        main()
