#!/usr/bin/env python3
"""E460-M standalone auditor (imports no CAIN code).

Checks the conformance certificate's signature, its SHA-256, the eight rows, the summary
arithmetic, the scope commitment and the signed manifest. It does not re-run the eight auditors;
it verifies the recorded clean-copy results (the eight bundles are public and re-runnable).
"""
import hashlib
import json
import sys
from pathlib import Path

from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey

SEED = "e460m"


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


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


def pub():
    k = Ed25519PrivateKey.from_private_bytes(hashlib.sha256(f"{SEED}|coordinator".encode()).digest())
    return k.public_key().public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw).hex()


def main():
    d = Path(sys.argv[1] if len(sys.argv) > 1 else ".")
    rep = json.loads((d / "E460M_RUN_REPORT.json").read_text())
    cert = rep["certificate"]
    scope = json.loads((d / "SCOPE.json").read_text())
    frz = json.loads((d / "E460M_PREREGISTRATION_FREEZE.json").read_text())
    checks = []

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

    ck("prereg hash", sha((d / "E460M_PREREGISTRATION.json").read_bytes()) == frz["preregistration_sha256"])
    ck("scope hash", sha((d / "SCOPE.json").read_bytes()) == frz["scope_sha256"])
    ck("status", rep["status"] == "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL")
    ck("certificate binder", cert["pubkey_ed25519"] == pub())
    body = {k: v for k, v in cert.items() if k != "signature"}
    try:
        Ed25519PublicKey.from_public_bytes(bytes.fromhex(cert["pubkey_ed25519"])).verify(
            bytes.fromhex(cert["signature"]), canon(body))
        ck("certificate signature", True)
    except Exception:
        ck("certificate signature", False)
    # the digest is over the certificate without signature and without the digest itself
    digest_body = {k: v for k, v in cert.items() if k not in ("signature", "certificate_sha256")}
    ck("certificate sha256", sha(canon(digest_body)) == cert["certificate_sha256"])

    rows = cert["rows"]
    s = cert["summary"]
    ck("row count", len(rows) == 8 and len(scope["bundles"]) == 8)
    ck("all verified", all(r["rc"] == 0 for r in rows) and s["verified"] == 8)
    ck("all seals", all(r["merkle_match"] for r in rows) and s["seals_ok"] == 8)
    ck("checks arithmetic", s["checks_passed"] == sum(r["checks_passed"] or 0 for r in rows)
       and s["checks_total"] == sum(r["checks_total"] or 0 for r in rows))
    ck("no source", s["source_files_total"] == 0 and all(not r["source_files_present"] for r in rows))
    ck("no authority", s["authority_true_fields"] == 0 and all(r["authority_true_fields"] == 0 for r in rows))
    ck("no model calls", s["model_calls_max"] == 0 and all(r["model_calls_max"] == 0 for r in rows))
    ck("scope matches rows", all(a["name"] == b["bundle"] and a["merkle_root"] == b["merkle"]
                                 for a, b in zip(scope["bundles"], rows)))

    def H(k):
        return rep["hypotheses"][k]["verdict"] == "SUPPORTED"

    for k in ("H1_clean_copy_verification", "H2_seal_and_merkle", "H3_engine_withheld",
              "H4_no_authority", "H5_no_model_calls", "H6_certificate"):
        ck(k, H(k))
    ck("H7 blocked", rep["hypotheses"]["H7_external_review"]["verdict"] == "BLOCKED")
    ck("verdict", rep["verdict"] == "MEMORY_EVIDENCE_CONFORMANCE_SUPPORTED")

    manp = d / "E460M_MANIFEST.json"
    if manp.exists():
        man = json.loads(manp.read_text())
        mb = {k: v for k, v in man.items() if k != "signature"}
        try:
            Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"])).verify(
                bytes.fromhex(man["signature"]), canon(mb))
            ck("manifest signature", True)
        except Exception:
            ck("manifest signature", False)
        ck("manifest hashes", {k: sha((d / k).read_bytes()) for k in man["files"]} == man["files"])
        leaves = sorted(man["files"].values())
        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)]
        ck("merkle", leaves[0] == man["merkle_root"])
        extra = {"PUBLICATION.json", "E460M_OMEGA_SEAL.json", "MANIFEST.json", "MERKLE_ROOT.txt",
                 "E460M_PUBKEY.pem", "E460M_SIGNED_BODY.json", "E460M_VERIFICATION_RESULTS.json",
                 "E460M_TAMPER_RESULTS.json", "E460M_MANIFEST.json"}
        actual = {str(p.relative_to(d)) for p in d.rglob("*") if p.is_file() and "__pycache__" not in p.parts}
        ck("no unexpected files", actual <= (set(man["files"]) | extra))

    fails = [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(fails)}/{len(checks)} checks passed")
    return 0 if not fails else 1


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