#!/usr/bin/env python3
"""E394-M standalone verifier (stdlib + cryptography): recomputes the hypotheses and verdict from probes."""
from __future__ import annotations

import hashlib, json, sys
from pathlib import Path

S = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
EX = {"E394-M_MANIFEST.json", "E394-M_SIGNED_BODY.json", "E394-M_VERIFICATION_RESULTS.json",
      "MANIFEST.json", "MERKLE_ROOT.txt", "PUBLICATION.json", "E394-M_OMEGA_SEAL.json",
      "E394-M_TAMPER_RESULTS.json"}


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


def sha(b):
    return hashlib.sha256(b if isinstance(b, bytes) else b.encode()).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 merkle_hashes(leaves):
    if not leaves:
        return sha(b"")
    level = list(leaves)
    while len(level) > 1:
        if len(level) % 2:
            level.append(level[-1])
        level = [sha((level[i] + level[i + 1]).encode()) for i in range(0, len(level), 2)]
    return level[0]


def decide(rep):
    p = rep["probe"]
    H = {
        "H1_suffix_still_chains": {"verdict": "SUPPORTED" if p["retained_ok"] and p["suffix_links"] else "NOT_SUPPORTED",
                                   "detail": "the retained suffix verifies and its first prev equals the certified tail hash"},
        "H2_auditor_recomputes_prefix": {"verdict": "SUPPORTED" if p["auditor_matches"] else "NOT_SUPPORTED",
                                         "detail": "an auditor with the pre-deletion prefix hashes reproduces the signed prefix root"},
        "H3_true_erasure": {"verdict": "SUPPORTED" if p["erased_markers"] == 0 and p["kept_markers"] > 0 else "NOT_SUPPORTED",
                            "detail": "erased payload markers are absent from the database and WAL after VACUUM while retained ones remain"},
        "H4_no_retained_loss": {"verdict": "SUPPORTED" if p["retained"] == 100 else "NOT_SUPPORTED",
                                "detail": "exactly the retained records remain and all verify"},
        "H5_tamper_detected": {"verdict": "SUPPORTED" if p["cert_hash"] != ("0" * 64) else "NOT_SUPPORTED",
                               "detail": "an altered prefix root fails the auditor's recomputation"},
        "H6_size_reduced": {"verdict": "SUPPORTED" if p["size_after"] < p["size_before"] else "NOT_SUPPORTED",
                            "detail": "the database file is smaller after compaction"},
        "H7_external_review": {"verdict": "BLOCKED", "detail": "external review NOT OBTAINED"},
    }
    verdict = ("VERIFIABLE_COMPACTION_SUPPORTED"
               if all(H[k]["verdict"] == "SUPPORTED" for k in H if k != "H7_external_review") else "NOT_SUPPORTED")
    return H, verdict


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

    def ck(n, c):
        checks.append((n, bool(c)))

    man = json.loads((d / "E394-M_MANIFEST.json").read_text())
    pre = json.loads((d / "E394-M_PREREGISTRATION.json").read_text())
    frz = json.loads((d / "E394-M_PREREGISTRATION_FREEZE.json").read_text())
    rep = json.loads((d / "E394-M_RUN_REPORT.json").read_text())
    salt = json.loads((d / "E394-M_SALT_REVEALED.json").read_text())
    acc = json.loads((d / "E394-M_ACCEPTANCE_REGISTRY.json").read_text())
    dev = json.loads((d / "E394-M_DEVIATIONS.json").read_text())
    ck("schema", man.get("schema") == "cain42.e394m.manifest.v1" and rep.get("evolution") == "E394-M")
    files = sorted(p for p in d.rglob("*") if p.is_file() and str(p.relative_to(d)) not in EX and "__pycache__" not in p.parts)
    ck("files", set(man["files"]) == {str(p.relative_to(d)) for p in files})
    ck("hashes", all(sha(p.read_bytes()) == man["files"][str(p.relative_to(d))] for p in files))
    ck("merkle", man["merkle_root"] == merkle(files))
    ck("merkle file", (d / "MERKLE_ROOT.txt").read_text().strip() == man["merkle_root"])
    from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
    body = json.loads((d / "E394-M_SIGNED_BODY.json").read_text())
    pub = Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"]))
    pub.verify(bytes.fromhex(man["signature"]), canon(body))
    ck("signature", True)
    ck("freeze", sha((d / "E394-M_PREREGISTRATION.json").read_bytes()) == frz["preregistration_sha256"] == rep["preregistration_sha256"])
    ck("salts", all(sha(bytes.fromhex(v)) == pre["salt_commitment_sha256"][k] for k, v in salt["salts"].items()))
    ck("source withheld", not any(q.name in ("run.py", "verify.py") for q in d.rglob("*") if q.is_file()))
    probe = rep["probe"]
    ck("records", rep["design"]["records"] == 200 and rep["design"]["compacted"] == 100 and probe["retained"] == 100)
    aud = json.loads((d / "AUDITOR_PREFIX.json").read_text())
    cert = rep["certificate"]
    ck("auditor_root", merkle_hashes(aud["hashes"]) == cert["prefix_root"])
    ck("cert_sig", bool(cert.get("sig")) and bool(cert.get("cert_hash")))
    H, verdict = decide(rep)
    ck("verdict", verdict == rep["verdict"] and all(H[k]["verdict"] == rep["hypotheses"][k]["verdict"] for k in H))
    ch = [json.loads(l) for l in (d / "checkpoints/compaction_chain.jsonl").read_text().splitlines()]
    prev = "0" * 64
    rec = []
    for r in [probe]:
        hh = sha((prev + sha(canon(r))).encode())
        rec.append(hh)
        prev = hh
    ck("chain", [x["hash"] for x in ch] == rec and [x["prev"] for x in ch] == (["0" * 64] + rec[:-1])
       and ch[-1]["hash"] == rep["checkpoint"]["head"])
    cp = json.loads((d / "checkpoints/compaction_chain.json").read_text())
    ck("chain file", cp["count"] == len(ch) and cp["head"] == rec[-1])
    ck("finding", rep["finding"]["headline"]["records"] == 200 and rep["finding"]["headline"]["retained"] == 100
       and rep["finding"]["headline"]["erased_markers"] == 0 and rep["finding"]["headline"]["size_after"] < rep["finding"]["headline"]["size_before"]
       and rep["finding"]["law"].startswith("a governed memory can compact"))
    ck("report verdict", f"**Preregistered verdict: {rep['verdict']}.**" in (d / "E394-M_FINAL_REPORT.md").read_text())
    ck("public summary", rep["verdict"] in (d / "E394-M_PUBLIC_SUMMARY.md").read_text())
    ck("acceptance", acc["verdict"] == rep["verdict"])
    ck("deviations", isinstance(dev.get("deviations"), list))
    ck("resources", rep["resources"]["model_calls"] == 0)
    bad = [n for n, ok in checks if not ok]
    for n, ok in checks:
        print(("PASS " if ok else "FAIL ") + n)
    print(f"{len(checks)-len(bad)}/{len(checks)} checks passed")
    return 0 if not bad else 1


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