#!/usr/bin/env python3
"""audit_formal.py -- local log audit of the five Lean theorem declarations.

What this does (and does not do)
  * It parses sources/Main.lean and sources/Statements.lean, the pinned Mathlib
    definition, and the MIT verification logs, and cross-matches the five theorem
    declarations against (a) the logged `#print axioms` output, (b) the logged
    con-leche --compare statement comparison, (c) the MIT SHA256SUMS file.
  * It re-hashes every local snapshot against sources/index.json.
  * It reads results/summary.json and re-derives the one field that is cheap to
    re-derive (the prime count below the recorded limit).
  * It does NOT run a Lean kernel. Every "kernel accepted" statement in the output
    is a statement about what a log file records, not something recomputed here.

Usage:  python3 verification/audit_formal.py [project_root]
Writes: verification/audit_results.json
"""
import hashlib, html, json, os, re, sys

STD_AXIOMS = {"propext", "Classical.choice", "Quot.sound"}
MIT_LOGS = ["audit.log", "nanoda.log", "con-leche-compare.log", "sandbox-timeline.txt"]
T_EXT, T_LOG, T_NUM = "external-kernel (recorded)", "local-log-check", "finite-numerical"


def sha(b):
    return hashlib.sha256(b).hexdigest()


def squash(s):
    return re.sub(r"\s+", " ", s).strip()


def canon_rh(s):
    """Token-level canonical form of the RH statement: erases binder syntax,
    the displayed N->C coercion, parentheses and whitespace. A textual
    heuristic only; definitional equality is a kernel fact, not checked here."""
    s = squash(s)
    s = s.replace("(n : ℂ)", "n").replace("↑n", "n").replace("∃ n : ℕ,", "∃ n,")
    if "(_ : " in s:
        s = s.replace("∀ (s : ℂ) (_ : ", "∀ s : ℂ, ")
        s = s.replace(") (_ : ", " → ").replace("), s.re", " → s.re")
    s = s.replace("∀ (s : ℂ),", "∀ s : ℂ,")
    return re.sub(r"[()\s]", "", s)


def parse_defs(text):
    out = {}
    for m in re.finditer(r"^def (\S+) : Prop :=\n((?:[ \t]+.*\n?)+)", text, re.M):
        out[m.group(1)] = squash(m.group(2))
    return out


def prime_count(n):
    sieve = bytearray([1]) * (n + 1)
    sieve[0:2] = b"\x00\x00"
    for i in range(2, int(n ** 0.5) + 1):
        if sieve[i]:
            sieve[i * i::i] = bytearray(len(range(i * i, n + 1, i)))
    return sum(sieve)


def audit(files, index, excerpts=(), summary=None):
    """files: name -> bytes; index: list of {file, sha256, bytes};
    excerpts: names whose bytes are partial/untrusted copies (never hashed)."""
    T = {k: v.decode("utf-8") for k, v in files.items()}
    idx = {e["file"]: e for e in index}
    checks = []

    def add(cid, tier, claim, ok, detail):
        checks.append({"id": cid, "tier": tier, "claim": claim,
                       "status": "pass" if ok is True else ("FAIL" if ok is False else str(ok)),
                       "detail": detail})

    # ---- A. snapshot integrity -------------------------------------------------
    integrity = {}
    for name, e in idx.items():
        if name not in files:
            integrity[name] = "not loaded in this run (recorded hash only)"
        elif name in excerpts:
            integrity[name] = "excerpt only, not hashed"
        else:
            ok = sha(files[name]) == e["sha256"] and len(files[name]) == e["bytes"]
            integrity[name] = "sha256+size match index.json" if ok else "MISMATCH"
    hashed = [n for n, v in integrity.items() if v.startswith("sha256")]
    add("A1", T_LOG, "local snapshots are byte-identical to the index.json records",
        not any(v == "MISMATCH" for v in integrity.values()),
        "%d files re-hashed: %s" % (len(hashed), ", ".join(sorted(hashed))))

    # ---- B. MIT checksum file --------------------------------------------------
    sums = {}
    for line in T.get("SHA256SUMS", "").splitlines():
        h, n = line.split(None, 1)
        sums[n.strip()] = h
    for n in MIT_LOGS:
        rec = idx[n]["sha256"] == sums.get(n)
        loc = (sha(files[n]) == sums.get(n)) if (n in files and n not in excerpts) else None
        add("B:" + n, T_LOG, "%s matches its MIT SHA256SUMS entry" % n,
            rec and loc is not False,
            "index.json record == SHA256SUMS: %s; recomputed local sha256 == SHA256SUMS: %s"
            % (rec, {True: "yes", False: "NO", None: "not recomputed"}[loc]))

    # ---- C. the five declarations ---------------------------------------------
    decls = re.findall(r"^theorem (\S+) : (\S+) := (.+)$", T["Main.lean"], re.M)
    names = [d[0] for d in decls]
    add("C1", T_LOG, "Main.lean declares exactly five theorems", len(decls) == 5, ", ".join(names))
    defs = parse_defs(T["Statements.lean"])
    mathlib = parse_defs(T["zeta_definition.lean"])
    add("C2", T_LOG, "every theorem type is a Prop defined in Statements.lean or pinned Mathlib",
        all(t in defs or t in mathlib for _, t, _ in decls),
        "Statements.lean: %s; Mathlib: %s" % (sorted(defs), sorted(mathlib)))

    # ---- D. statement comparison ----------------------------------------------
    A = T["audit.log"]
    m = re.search(r"^def RiemannHypothesis : Prop :=\n(.*)$", A, re.M)
    forms = {"Mathlib v4.33.1 source": mathlib["RiemannHypothesis"],
             "audit.log #print": m.group(1),
             "Statements.lean RiemannZetaZerosOnLine": defs["RiemannZetaZerosOnLine"]}
    canon = {k: canon_rh(v) for k, v in forms.items()}
    add("D1", T_LOG, "Mathlib's RiemannHypothesis, its logged printout and the written-out "
        "RiemannZetaZerosOnLine agree token-for-token (modulo binder syntax and coercion display)",
        len(set(canon.values())) == 1, sorted(set(canon.values()))[0])
    terms = {n: t for n, _, t in decls}
    add("D2", T_LOG, "riemannHypothesis and riemannZeta_eq_zero_re are given the same proof term",
        terms.get("riemannHypothesis") == terms.get("riemannZeta_eq_zero_re"),
        "both := %s (source-level evidence that the two Props are definitionally equal; "
        "the kernel verdict is external)" % terms.get("riemannHypothesis"))
    mit = {}
    for block in re.findall(r"<pre>(.*?)</pre>", T.get("mit.html", ""), re.S):
        for piece in html.unescape(block).split("theorem ")[1:]:
            mm = re.match(r"(\S+) :(.*)", piece, re.S)
            if mm:
                mit[mm.group(1)] = squash(mm.group(2))
    mit_ok = {}
    for n, t, _ in decls:
        want = t if t in mathlib else defs.get(t)
        mit_ok[n] = (mit.get(n) == want)
    add("D3", T_LOG, "the five statements printed on the MIT page equal the local statements",
        all(mit_ok.values()) if mit else "skipped", json.dumps(mit_ok))
    C = T["con-leche-compare.log"]
    justified = re.findall(r"^con-leche: theorem (\S+) justified by the solution$", C, re.M)
    add("D4", T_EXT, "con-leche --compare log: each of the five theorems 'justified by the solution'",
        sorted(justified) == sorted(names), ", ".join(justified))
    acc = re.search(r"accepted (\d+) declarations, (\d+) axioms justified by the solution "
                    r"\S+ \((\d+) declarations accepted\) \(--verified\)", C)
    add("D5", T_EXT, "con-leche log: challenge and solution accepted, exit status 0",
        bool(acc) and acc.group(2) == "5" and "Exit status: 0" in C,
        "challenge declarations %s; challenge placeholders justified %s; solution declarations %s"
        % (acc.groups() if acc else ("?",) * 3))

    # ---- E. axioms -------------------------------------------------------------
    dep = {n: {a.strip() for a in a_.split(",")}
           for n, a_ in re.findall(r"^'(\S+)' depends on axioms: \[(.*)\]$", A, re.M)}
    add("E1", T_EXT, "#print axioms log: all five theorems depend only on propext, Classical.choice, Quot.sound",
        sorted(dep) == sorted(names) and all(v == STD_AXIOMS for v in dep.values()),
        "; ".join("%s: %s" % (n, sorted(dep.get(n, []))) for n in names))
    env = re.findall(r"\((\S+), (\S+)\)", A[A.index("ALL AXIOMS"):A.index("def RiemannHypothesis")])
    n_env = int(re.search(r"ALL AXIOMS IN ENVIRONMENT \((\d+)\)", A).group(1))
    add("E2", T_EXT, "axiom log: every axiom in the environment is declared in Lean core (Init.*)",
        len(env) == n_env and all(mod.startswith("Init") for _, mod in env),
        "%d axioms, modules %s" % (len(env), sorted({mod for _, mod in env})))
    unused = sorted({a for a, _ in env} - STD_AXIOMS)
    add("E3", T_EXT, "sorryAx and the compiler-trust axioms exist in core but are not used by any of the five",
        all("sorryAx" not in v and "Lean.ofReduceBool" not in v and "Lean.trustCompiler" not in v
            for v in dep.values()) and "sorryAx" in unused,
        "present in environment, absent from all five dependency lists: " + ", ".join(unused))
    where = dict(re.findall(r"^(\S+) : declared in module (\S+)$", A, re.M))
    add("E4", T_EXT, "axiom log: theorems live in Main, written-out Props in Statements, analytic notions in Mathlib",
        all(where.get(n) == "Main" for n in names)
        and all(where.get(d) == "Statements" for d in defs)
        and all(where.get(k, "").startswith("Mathlib.") for k in
                ["RiemannHypothesis", "riemannZeta", "DirichletCharacter",
                 "DirichletCharacter.LFunction", "DirichletCharacter.IsPrimitive"]),
        json.dumps(where, ensure_ascii=False))

    # ---- F. second kernel + rebuild -------------------------------------------
    N = T["nanoda.log"]
    wall = re.search(r"Elapsed \(wall clock\) time .*: (\S+)", N)
    add("F1", T_EXT, "nanoda log: independent Rust kernel run exits 0",
        "Exit status: 0" in N and "nanoda_bin" in N,
        "wall %s; the log holds timing and exit status only, no per-declaration record"
        % (wall.group(1) if wall else "?"))
    S = T["sandbox-timeline.txt"]
    exp = re.search(r"^([0-9a-f]{64})  \S*solution\.ndjson$", S, re.M)
    add("F2", T_LOG, "sandboxed rebuild: export sha256 equals the SHA256SUMS entry for solution.ndjson",
        bool(exp) and exp.group(1) == sums.get("solution.ndjson") and "EXPORT SHA256 MATCHES" in S,
        exp.group(1) if exp else "?")
    man = re.search(r"olean manifest: (\d+) files, sha256 ([0-9a-f]{64})", S)
    same = re.search(r"identical to published manifest: (\d+) of (\d+); differing: (\d+)", S)
    add("F3", T_LOG, "sandboxed rebuild: olean manifest hash equals SHA256SUMS; one module differs",
        bool(man) and man.group(2) == sums.get("sandbox-project-oleans.sha256") and bool(same),
        "%s of %s compiled files identical, %s differing (documented non-deterministic bound-variable name)"
        % (same.groups() if same else ("?",) * 3))
    tool = T.get("lean-toolchain", "").strip()
    lv = re.search(r"Lean \(version ([\d.]+),", S)
    rev = re.search(r'"rev": "([0-9a-f]{40})",\s*"name": "mathlib"', T.get("lake-manifest.json", ""))
    add("F4", T_LOG, "toolchain pin, lake manifest and rebuild log name the same Lean and Mathlib",
        bool(lv) and tool.endswith("v" + lv.group(1)) and bool(rev) and rev.group(1) in S,
        "lean-toolchain %s; rebuild Lean %s; Mathlib rev %s"
        % (tool, lv.group(1) if lv else "?", rev.group(1) if rev else "?"))
    M = T.get("mit.html", "")
    page = {k: (sums.get(k, "#") in M) for k in ["solution.ndjson", "solution.ndjson.zst", "challenge.ndjson"]}
    add("F5", T_LOG, "hashes printed on the MIT page equal the SHA256SUMS entries",
        all(page.values()) if M else "skipped", json.dumps(page))
    pending = len(re.findall(r'class="wait">running', M))
    add("F6", T_LOG, "MIT page snapshot still lists checks as running (not a failure; an open item)",
        "note" if M else "skipped", "%d rows marked 'running' in the snapshot" % pending)

    # ---- G. finite numerical companion ----------------------------------------
    if summary is not None:
        pc = prime_count(summary["prime_limit"])
        add("G1", T_NUM, "results/summary.json prime_count equals pi(prime_limit) recomputed by sieve",
            pc == summary["prime_count"], "pi(%d) = %d" % (summary["prime_limit"], pc))
        add("G2", T_NUM, "results/summary.json is a finite experiment with no completeness certificate",
            "note", "%d zeros; max |zeta(rho)| residual %.3g; max difference to printed reference %.3g; "
            "%d bracketed sign changes; mesh %s; note: %s"
            % (summary["roots"], summary["max_zero_residual"], summary["max_reference_difference"],
               summary["bracketed_crossings"], "x".join(map(str, summary["mesh_shape"])),
               summary["enumeration"]))

    matrix = []
    for n, t, term in decls:
        matrix.append({"theorem": n, "type": t, "proof_term": term,
                       "statement_source": "Mathlib (pinned)" if t in mathlib else "Statements.lean",
                       "statement": mathlib.get(t) or defs.get(t),
                       "axioms": sorted(dep.get(n, [])),
                       "declared_in": where.get(n),
                       "compare_justified": n in justified,
                       "mit_statement_equal": mit_ok.get(n)})
    return {"integrity": integrity, "checks": checks, "theorems": matrix}


def main(root):
    src = os.path.join(root, "sources")
    files = {n: open(os.path.join(src, n), "rb").read() for n in sorted(os.listdir(src))
             if os.path.isfile(os.path.join(src, n)) and not n.endswith((".pdf",))}
    for n in os.listdir(src):
        if n.endswith(".pdf"):
            files[n] = open(os.path.join(src, n), "rb").read()
    index = json.loads(files["index.json"])
    text_only = {k: v for k, v in files.items() if not k.endswith(".pdf")}
    summary = json.load(open(os.path.join(root, "results", "summary.json")))
    rep = audit_all(files, text_only, index, summary)
    rep["run"] = {"mode": "on-disk", "kernel_run": False}
    out = os.path.join(root, "verification", "audit_results.json")
    json.dump(rep, open(out, "w"), indent=1, ensure_ascii=False)
    for c in rep["checks"]:
        print("%-28s %-6s %s" % (c["id"], c["status"], c["claim"]))
    print("wrote", out)


def audit_all(files, text_files, index, summary):
    """Hash every file (including binaries) but only decode the text ones."""
    rep = audit(text_files, index, summary=summary)
    for e in index:
        n = e["file"]
        if n in files and n not in text_files:
            ok = sha(files[n]) == e["sha256"] and len(files[n]) == e["bytes"]
            rep["integrity"][n] = "sha256+size match index.json" if ok else "MISMATCH"
    return rep


if __name__ == "__main__":
    main(sys.argv[1] if len(sys.argv) > 1 else os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
