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

Checks the manifest signature, every file digest, the Merkle root, the preregistration hash, the
freeze ordering, the salt commitments, the external-review status, the frozen surface pin, the row
chain, every row's structure, and recomputes the aggregates, every hypothesis and the verdict from
the raw rows. The engine source is withheld by the IP rule; the verifier validates the recorded
rows and the decision rule, not the engine implementation.
"""
from __future__ import annotations

import hashlib
import json
import sys
from pathlib import Path

S = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
ENG = ("surface.py", "inject.py", "run.py")
EX = {"E331R_MANIFEST.json", "E331R_SIGNED_BODY.json", "E331R_VERIFICATION_RESULTS.json", "MANIFEST.json",
      "MERKLE_ROOT.txt", "PUBLICATION.json", "E331R_OMEGA_SEAL.json", "E331R_TAMPER_RESULTS.json"}
INJECTED_REPAIRABLE = {"block_status_removed", "block_seal_changed", "block_duplicate", "block_order_swap",
                       "block_above_mark", "snapshot_status_changed", "snapshot_seal_changed",
                       "snapshot_missing", "claim_missing", "claim_status_changed",
                       "combined_order_and_status"}
INJECTED_REFUSAL = {"page_missing_all_sites", "unknown_evidence_block", "evidence_tampered",
                    "injection_all_sites", "schema_unknown"}


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 agg(rows):
    n = len(rows)
    defect = [r for r in rows if r["kind"] != "benign"]
    benign = [r for r in rows if r["kind"] == "benign"]
    rep = [r for r in rows if r["kind"] == "repairable"]
    ref = [r for r in rows if r["kind"] == "refusal"]
    return {
        "rows": n, "defect_rows": len(defect), "benign_rows": len(benign),
        "repairable_rows": len(rep), "refusal_rows": len(ref),
        "detected_ok": sum(1 for r in rows if r["detected_ok"]),
        "detection_rate": round(sum(1 for r in rows if r["detected_ok"]) / n, 6) if n else 0.0,
        "repaired": sum(1 for r in rep if r["repaired"]),
        "repair_rate": round(sum(1 for r in rep if r["repaired"]) / len(rep), 6) if rep else 0.0,
        "false_repairs": sum(1 for r in rows if r["false_repair"]),
        "refused_correct": sum(1 for r in ref if r["refusal_correct"]),
        "regressions": sum(len(r["regressions"]) for r in rows),
        "violations": sum(len(r["violations"]) for r in rows),
        "evidence_changed": sum(1 for r in rows if r["evidence_changed"]),
        "idempotent": sum(1 for r in rows if r["idempotent"]),
        "deterministic": sum(1 for r in rows if r["deterministic"]),
        "benign_ops": sum(r["ops"] for r in benign),
        "classes": len({r["class"] for r in defect}),
        "naive_regressions": sum(len(r["naive"]["regressions"]) for r in rows),
        "naive_evidence_changes": sum(1 for r in rows if r["naive"]["evidence_changed"]),
        "naive_unsafe": sum(1 for r in rows if r["naive"]["unsafe"]),
        "naive_bad": sum(1 for r in rows if r["naive"]["regressions"] or r["naive"]["evidence_changed"]
                         or r["naive"]["unsafe"]),
    }


def hyp(p, q):
    H = {}
    H["H1_detection"] = "SUPPORTED" if p["detected_ok"] == p["rows"] and q["detected_ok"] == q["rows"] \
        and p["benign_ops"] == 0 and q["benign_ops"] == 0 else "NOT_SUPPORTED"
    H["H2_repair"] = "SUPPORTED" if p["repair_rate"] == 1.0 and q["repair_rate"] == 1.0 \
        and p["false_repairs"] == 0 and q["false_repairs"] == 0 else "NOT_SUPPORTED"
    H["H3_no_regression"] = "SUPPORTED" if p["regressions"] == 0 and q["regressions"] == 0 \
        and p["violations"] == 0 and q["violations"] == 0 else "NOT_SUPPORTED"
    H["H4_evidence_untouched_and_refusals"] = "SUPPORTED" if p["evidence_changed"] == 0 \
        and q["evidence_changed"] == 0 and p["refused_correct"] == p["refusal_rows"] \
        and q["refused_correct"] == q["refusal_rows"] else "NOT_SUPPORTED"
    H["H5_idempotent_deterministic"] = "SUPPORTED" if p["idempotent"] == p["rows"] and q["idempotent"] == q["rows"] \
        and p["deterministic"] == p["rows"] and q["deterministic"] == q["rows"] else "NOT_SUPPORTED"
    H["H6_naive_is_unsafe"] = "SUPPORTED" if p["naive_bad"] > 0 and q["naive_bad"] > 0 else "NOT_SUPPORTED"
    H["H7_replication"] = "SUPPORTED" if p["rows"] == q["rows"] and p["classes"] == q["classes"] \
        and p["repairable_rows"] == q["repairable_rows"] and p["refusal_rows"] == q["refusal_rows"] \
        else "NOT_SUPPORTED"
    H["H8_external_review"] = "BLOCKED"
    return H


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 / "E331R_MANIFEST.json").read_text())
    ck("schema", man.get("schema") == "cain42.e331r.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 / "E331R_PREREGISTRATION.json").read_text())
    frz = json.loads((B / "E331R_PREREGISTRATION_FREEZE.json").read_text())
    rep = json.loads((B / "E331R_RUN_REPORT.json").read_text())
    ck("prereg hash", sha((B / "E331R_PREREGISTRATION.json").read_bytes()) == frz.get("preregistration_sha256"))
    ck("freeze before run", str(frz.get("frozen_at")) <= str(rep.get("generated_at")))
    ck("prereg before freeze", str(pre.get("written_at")) <= str(frz.get("frozen_at")))
    ck("surface pin hash", sha((B / "surface/SURFACE_PIN.json").read_bytes()) == frz.get("surface_pin_sha256"))
    pin = json.loads((B / "surface/SURFACE_PIN.json").read_text())
    ck("surface pin files", not [k for k, h in (pin.get("files") or {}).items()
                                 if not (B / "surface" / k).exists() or sha((B / "surface" / k).read_bytes()) != h])
    ck("surface tree hash", sha(canon(sorted((pin.get("files") or {}).items()))) == pin.get("tree_hash"))
    salts = json.loads((B / "E331R_SALT_REVEALED.json").read_text())["salts"]
    ck("salt commitments", {k: sha(bytes.fromhex(v)) for k, v in salts.items()} == pre.get("salt_commitment_sha256"))
    ext = json.loads((B / "E331R_EXTERNAL_REVIEW_STATUS.json").read_text())
    ck("external review blocked", ext.get("status") == "NOT_OBTAINED" and rep["finding"].get("external_review") == "NOT_OBTAINED")
    dev = json.loads((B / "E331R_DEVIATIONS.json").read_text()).get("deviations") or []
    ck("deviation recorded", len(dev) == 1 and dev[0].get("deviation") == "D1"
       and pre.get("engine_sha256", {}).get("cain/cain2027/e331r/run.py") == dev[0].get("to"))

    rows = rep["sets"]["primary"]["rows"] + rep["sets"]["replication"]["rows"]
    ck("row count", len(rows) == 160, len(rows))
    ck("class set", sorted({r["class"] for r in rows if r["kind"] != "benign"}) ==
       sorted(INJECTED_REPAIRABLE | INJECTED_REFUSAL), sorted({r["class"] for r in rows if r["kind"] != "benign"}))
    ck("salt split", all(len(rep["sets"][s]["rows"]) == 80 for s in ("primary", "replication")))
    prev = "0" * 64
    for r in rows:
        prev = sha((prev + sha(canon(r))).encode())
    ck("row chain", prev == (rep.get("row_chain") or {}).get("head") and (rep.get("row_chain") or {}).get("n") == len(rows))
    ck("row structure", all(
        (r["repaired"] is True and not r["remaining"] and not r["regressions"]) if r["kind"] == "repairable"
        else (r["repaired"] is False and r["refusal_correct"] is True) if r["kind"] == "refusal"
        else (r["ops"] == 0 and not r["changed"]) for r in rows))
    a = agg(rows)
    a2 = agg(rep["sets"]["primary"]["rows"])
    a3 = agg(rep["sets"]["replication"]["rows"])
    ck("aggregate recompute", a == rep["summary"]["all"] and a2 == rep["summary"]["primary"]
       and a3 == rep["summary"]["replication"])
    H = hyp(a2, a3)
    ck("hypotheses recompute", H == {k: v["verdict"] for k, v in rep["hypotheses"].items()}, H)
    verdict = "SURFACE_SELF_REPAIR_SUPPORTED" if all(v == "SUPPORTED" for k, v in H.items() if k != "H8_external_review") else "NOT_SUPPORTED"
    ck("verdict recompute", verdict == rep["verdict"], verdict)
    f = rep["finding"]
    ck("finding recompute", f["defects_injected"] == a["defect_rows"] and f["detected"] == a["detected_ok"]
       and f["repaired"] == a["repaired"] and f["repairable"] == a["repairable_rows"]
       and f["false_repairs"] == a["false_repairs"] and f["refused_correct"] == a["refused_correct"]
       and f["refusals"] == a["refusal_rows"] and f["regressions"] == a["regressions"]
       and f["evidence_changes"] == a["evidence_changed"] and f["idempotent"] == a["idempotent"]
       and f["deterministic"] == a["deterministic"] and f["naive_bad"] == a["naive_bad"])
    ck("no evidence change", a["evidence_changed"] == 0)
    ck("no false repair", a["false_repairs"] == 0)
    ck("acceptance registry", json.loads((B / "E331R_ACCEPTANCE_REGISTRY.json").read_text())["all_pass"] == (verdict == "SURFACE_SELF_REPAIR_SUPPORTED"))
    ck("limits present", len(rep.get("limits") or []) >= 8)
    fr = (B / "E331R_FINAL_REPORT.md").read_text()
    ps = (B / "E331R_PUBLIC_SUMMARY.md").read_text()
    ck("report verdict consistent", f"Preregistered verdict: {rep['verdict']}." in fr)
    ck("summary verdict consistent", f"Verdict: {rep['verdict']}" in ps)
    ck("report row count consistent", str(rep["summary"]["all"]["rows"]) in fr)

    passed = sum(1 for x in c if x["ok"])
    for x in c:
        if not x["ok"]:
            print("FAIL", x["check"], x["detail"])
    print(f"{passed}/{len(c)} checks passed")
    return 0 if passed == len(c) else 1


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