#!/usr/bin/env python3
"""E380-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 = {"E380-M_MANIFEST.json", "E380-M_SIGNED_BODY.json", "E380-M_VERIFICATION_RESULTS.json",
      "MANIFEST.json", "MERKLE_ROOT.txt", "PUBLICATION.json", "E380-M_OMEGA_SEAL.json",
      "E380-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 decide(probes):
    by = {p["probe"]: p for p in probes}
    h1 = by["H1_visibility"]
    h2 = by["H2_isolation"]
    h3 = by["H3_no_authority_from_memory"]
    h4 = by["H4_verified_writes"]
    h5 = by["H5_uncertainty_and_provenance"]
    h6 = by["H6_tamper_evidence"]
    h7 = by["H7_scale"]
    H = {
        "H1_visibility": {"verdict": "SUPPORTED" if h1["ok"] else "NOT_SUPPORTED",
                          "detail": "every agent in the domain sees every peer action, record and result"},
        "H2_isolation": {"verdict": "SUPPORTED" if h2["ok"] and h2["leaks"] == 0 else "NOT_SUPPORTED",
                         "detail": "a foreign tenant's reader is refused and no cross-tenant record is returned"},
        "H3_no_authority_from_memory": {"verdict": "SUPPORTED" if h3["ok"] and h3["grants"] == 0 else "NOT_SUPPORTED",
                                        "detail": "no hit grants authority; an action justified only by memory is refused"},
        "H4_verified_writes": {"verdict": "SUPPORTED" if h4["ok"] and h4["refused"] == h4["attempts"] else "NOT_SUPPORTED",
                               "detail": "unsigned, wrong-key, out-of-range, unknown-kind and revoked writes are refused"},
        "H5_uncertainty_and_provenance": {"verdict": "SUPPORTED" if h5["ok"] and h5["exposed"] == h5["total"] else "NOT_SUPPORTED",
                                          "detail": "every visible record exposes uncertainty, verification status, writer fingerprint and chain position"},
        "H6_tamper_evidence": {"verdict": "SUPPORTED" if h6["ok"] else "NOT_SUPPORTED",
                               "detail": "a direct storage flip breaks the per-tenant chain"},
        "H7_scale": {"verdict": "SUPPORTED" if h7["ok"] and h7["rows"] == 20000 and h7["p95_ms"] <= 100.0 else "NOT_SUPPORTED",
                     "detail": "20,000 records ingested; read(limit=200) p95 <= 100 ms; chain valid at scale"},
        "H8_external_review": {"verdict": "BLOCKED", "detail": "external review NOT OBTAINED"},
    }
    verdict = ("GOVERNED_SHARED_MEMORY_VERIFIED"
               if all(H[k]["verdict"] == "SUPPORTED" for k in H if k != "H8_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 / "E380-M_MANIFEST.json").read_text())
    pre = json.loads((d / "E380-M_PREREGISTRATION.json").read_text())
    frz = json.loads((d / "E380-M_PREREGISTRATION_FREEZE.json").read_text())
    rep = json.loads((d / "E380-M_RUN_REPORT.json").read_text())
    salt = json.loads((d / "E380-M_SALT_REVEALED.json").read_text())
    acc = json.loads((d / "E380-M_ACCEPTANCE_REGISTRY.json").read_text())
    dev = json.loads((d / "E380-M_DEVIATIONS.json").read_text())
    ck("schema", man.get("schema") == "cain42.e380m.manifest.v1" and rep.get("evolution") == "E380-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 / "E380-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 / "E380-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()))
    probes = rep["probes"]
    ck("probes", len(probes) >= 7 and {p["probe"] for p in probes} >= {"H1_visibility", "H2_isolation", "H3_no_authority_from_memory",
                                                                      "H4_verified_writes", "H5_uncertainty_and_provenance",
                                                                      "H6_tamper_evidence", "H7_scale"})
    H, verdict = decide(probes)
    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/probe_chain.jsonl").read_text().splitlines()]
    prev = "0" * 64
    rec = []
    for r in probes:
        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/probe_chain.json").read_text())
    ck("chain file", cp["count"] == len(ch) and cp["head"] == rec[-1])
    ck("finding", rep["finding"]["headline"]["records"] == 240 and rep["finding"]["headline"]["visible_records"] == 240
       and rep["finding"]["law"].startswith("one governed shared memory"))
    ck("report verdict", f"**Preregistered verdict: {rep['verdict']}.**" in (d / "E380-M_FINAL_REPORT.md").read_text())
    ck("public summary", rep["verdict"] in (d / "E380-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())
