#!/usr/bin/env python3
"""E327-Q standalone offline verifier (stdlib + cryptography; imports no CAIN code).

Recomputes every quantized optimum from the stored coverage matrix and the composition
enumeration, checks the corrected H4 direction, and recomputes the hypotheses and verdict.
"""
import hashlib
import json
import sys
from pathlib import Path

S = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
ENG = ("quantize.py", "run.py")
DEPS = 7
GRID = (2, 4, 8, 16, 32)
EX = {"E327Q_MANIFEST.json", "E327Q_SIGNED_BODY.json", "E327Q_VERIFICATION_RESULTS.json",
      "MANIFEST.json", "MERKLE_ROOT.txt", "PUBLICATION.json", "E327Q_OMEGA_SEAL.json",
      "E327Q_TAMPER_RESULTS.json", "E327Q_ACCEPTANCE_REGISTRY.json"}


def canon(o):
    return json.dumps(o, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()


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


def merkle(paths):
    leaves = sorted(sha(p.read_bytes()) for p in paths)
    if not leaves:
        return sha(b"")
    while len(leaves) > 1:
        if len(leaves) % 2:
            leaves.append(leaves[-1])
        leaves = [sha((leaves[i] + leaves[i + 1]).encode())
                  for i in range(0, len(leaves), 2)]
    return leaves[0]


def chain(rows):
    prev = "0" * 64
    out = []
    for r in rows:
        h = sha((prev + sha(canon(r))).encode())
        out.append({"i": len(out), "prev": prev, "hash": h})
        prev = h
    return out


def comps(M, k):
    if k == 1:
        yield (M,)
        return
    for i in range(M + 1):
        for rest in comps(M - i, k - 1):
            yield (i,) + rest


def worst(A, counts, M):
    k = len(counts)
    return max((sum(A[r][i] * counts[i] for i in range(k)) / M for r in range(len(A))), default=0.0)


def best(A, k, M):
    b = None
    bc = None
    for c in comps(M, k):
        t = worst(A, c, M)
        if b is None or t < b - 1e-12:
            b, bc = t, c
    return b, bc


def main():
    B = Path(sys.argv[1] if len(sys.argv) > 1 else ".")
    c = []

    def ck(n, ok, d=""):
        c.append({"check": n, "ok": bool(ok), "detail": str(d)[:300]})

    man = json.loads((B / "E327Q_MANIFEST.json").read_text())
    ck("schema", man.get("schema") == "cain42.e327q.manifest.v1")
    ck("status", man.get("status") == S)
    body = {k: v for k, v in man.items() if k != "signature"}
    try:
        from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
        Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"])).verify(
            bytes.fromhex(man["signature"]), canon(body))
        ck("signature", True)
    except Exception as ex:
        ck("signature", False, ex)
    files = man.get("files", {})
    ck("files present", all((B / k).exists() for k in files))
    ck("file hashes", not [k for k, h in files.items()
                           if (B / k).exists() and sha((B / k).read_bytes()) != h])
    ck("merkle", merkle(sorted(B / k for k in files if (B / k).exists())) == man.get("merkle_root"))
    present = {str(x.relative_to(B)) for x in B.rglob("*")
               if x.is_file() and "__pycache__" not in x.parts}
    ck("no unlisted file", not (present - set(files) - EX), sorted(present - set(files) - EX)[:5])
    ck("source withheld", not any((B / n).exists() for n in ENG))

    pre = json.loads((B / "E327Q_PREREGISTRATION.json").read_text())
    frz = json.loads((B / "E327Q_PREREGISTRATION_FREEZE.json").read_text())
    rep = json.loads((B / "E327Q_RUN_REPORT.json").read_text())
    rev = json.loads((B / "E327Q_SALT_REVEALED.json").read_text())
    corr = json.loads((B / "E327Q_ANALYSIS_CORRECTION.json").read_text())
    ck("prereg hash", sha((B / "E327Q_PREREGISTRATION.json").read_bytes()) ==
       frz["preregistration_sha256"])
    ck("freeze before run", frz["frozen_at"] <= rep["generated_at"])
    ck("salt commitments", all(sha(bytes.fromhex(rev["salts"][k])) ==
                               pre["salt_commitment_sha256"][k] for k in rev["salts"]))
    ck("external not faked",
       json.loads((B / "E327Q_EXTERNAL_REVIEW_STATUS.json").read_text()).get("status") == "NOT_OBTAINED")
    ck("pinned dependency", len(pre.get("dependency_sha256", {})) == DEPS)
    ck("engine hashes", len(pre.get("engine_sha256", {})) == len(ENG))
    ck("correction present", corr.get("schema") == "cain42.e327q.analysis_correction.v1")

    allr = []
    for salt in ("primary", "replication"):
        rows = rep["sets"][salt]["rows"]
        allr += rows
        ck(f"{salt} rows", len(rows) == 24, len(rows))
        ck(f"{salt} unique", len({(r["grammar"], r["p1"], r["world"]) for r in rows}) == 24)
    ck("total runs", len(allr) == 48, len(allr))

    bad = []
    for r in allr:
        if not r["k"]:
            continue
        A = r["k"]["A"]
        for M in GRID:
            t, cnt = best(A, 4, M)
            st = r["k"]["grid"][str(M)]["t"]
            if abs(t - st) > 1e-9:
                bad.append(("t", M, r["grammar"], r["p1"], r["world"], t, st))
            if r["k"]["grid"][str(M)]["counts"] != list(cnt):
                bad.append(("counts", M))
        first = next((M for M in GRID if best(A, 4, M)[0] <= r["k"]["t_frac"] + 0.02 + 1e-9), None)
        if r["k"]["first_within_0_02"] != first:
            bad.append(("first", r["grammar"], r["p1"], r["world"]))
    ck("quantized recomputation", not bad, bad[:5])

    cap = [r for r in allr if r["k"] and not r["k"]["correct"]]
    cells = [r["k"] for r in cap]

    def frac(pred):
        return sum(1 for x in cells if pred(x)) / len(cells)

    h1 = frac(lambda x: x["grid"]["16"]["within_0_01"]) >= 0.90
    h2 = frac(lambda x: x["grid"]["4"]["gap"] <= 0.05 + 1e-9) >= 0.75
    h3 = frac(lambda x: x["grid"]["2"]["gap"] > 0.05 + 1e-9) >= 0.50
    mono = all(all(x["grid"][str(GRID[j])]["t"] >= x["grid"][str(GRID[j + 1])]["t"] - 1e-9
                   for j in range(4)) for x in cells)
    h4 = mono
    h5 = frac(lambda x: x["first_within_0_02"] is not None and
              x["first_within_0_02"] <= 8) >= 0.75
    rcap = [r for r in rep["sets"]["replication"]["rows"] if r["k"] and not r["k"]["correct"]]
    rc = [r["k"] for r in rcap]
    h6 = (sum(1 for x in rc if x["grid"]["16"]["within_0_01"]) / len(rc) >= 0.80 and
          sum(1 for x in rc if x["first_within_0_02"] is not None and
              x["first_within_0_02"] <= 8) / len(rc) >= 0.70)
    H = rep["hypotheses"]
    for k, ok in (("H1_M16_within_0_01", h1), ("H2_M4_within_0_05", h2),
                  ("H3_M2_coarse_costs", h3), ("H5_cheap_implementation", h5),
                  ("H6_replication", h6)):
        ck(f"{k} verdict", H[k]["verdict"] == ("SUPPORTED" if ok else "NOT_SUPPORTED"))
    ck("H4 as-shipped was inverted", H["H4_monotone_in_M"]["verdict"] == "NOT_SUPPORTED")
    ck("H4 corrected", mono == corr["all_non_increasing"] and corr["corrected_H4"] == "SUPPORTED")
    ck("H1 fraction", abs(H["H1_M16_within_0_01"]["fraction"] -
                          frac(lambda x: x["grid"]["16"]["within_0_01"])) < 0.0002)
    ck("H3 fraction", abs(H["H3_M2_coarse_costs"]["fraction_gap_gt_0_05"] -
                          frac(lambda x: x["grid"]["2"]["gap"] > 0.05 + 1e-9)) < 0.0002)
    verdict = ("QUANTIZED_AUDIT_SUPPORTED" if all((h1, h2, h3, h4, h5, h6)) else "NOT_SUPPORTED")
    ck("verdict", verdict == rep["verdict"] == man.get("label") == "NOT_SUPPORTED")
    f = rep["finding"]
    ck("finding means", abs(f["mean_gap_M16"] - sum(x["grid"]["16"]["gap"] for x in cells) / len(cells)) < 0.0002 and
       abs(f["mean_gap_M2"] - sum(x["grid"]["2"]["gap"] for x in cells) / len(cells)) < 0.0002)
    ck("manifest headline", man.get("headline", {}).get("verdict") == verdict and
       man.get("headline", {}).get("runs") == 48 and
       abs(man.get("headline", {}).get("mean_gap", {}).get("2", -1) -
           sum(x["grid"]["2"]["gap"] for x in cells) / len(cells)) < 0.0002 and
       abs(man.get("headline", {}).get("mean_gap", {}).get("16", -1) -
           sum(x["grid"]["16"]["gap"] for x in cells) / len(cells)) < 0.0002)
    ch = chain(allr)
    cp = json.loads((B / "checkpoints/claim_chain.json").read_text())
    ck("chain count", cp["count"] == 48)
    ck("chain head", cp["head"] == ch[-1]["hash"])
    ck("chain mid", cp["mid"] == ch[len(ch) // 2]["hash"])
    ck("chain recompute", sha((ch[-2]["hash"] + sha(canon(allr[-1]))).encode()) == ch[-1]["hash"])
    ck("status line", S in (B / "E327Q_FINAL_REPORT.md").read_text())
    ck("limits present", len(rep.get("limits", [])) >= 5)
    ck("zero model calls", rep["resources"]["model_calls"] == 0)

    passed = sum(1 for x in c if x["ok"])
    print(json.dumps({"schema": "cain42.e327q.verify.v1", "checks": len(c),
                      "passed": passed, "failed": [x for x in c if not x["ok"]],
                      "verdict": verdict,
                      "mean_gap_M2": round(sum(x["grid"]["2"]["gap"] for x in cells) / len(cells), 4),
                      "mean_gap_M16": round(sum(x["grid"]["16"]["gap"] for x in cells) / len(cells), 4)},
                     ensure_ascii=False))
    return 0 if passed == len(c) else 1


if __name__ == "__main__":
    sys.exit(main())
