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

Re-verifies every record signature and hash chain from the ledger, recomputes the current access sets
from the ledger's grants, and checks the reported checks/hypotheses/counts. The transient scoped and
revoked states are attested in the report and bound by the manifest; the verifier re-executes the
current ledger state and every cryptographic object.
"""
from __future__ import annotations

import hashlib
import json
import sys
from pathlib import Path

from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey

S = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
NOW = 1_800_000_000
EX = {"E382F_MANIFEST.json", "E382F_SIGNED_BODY.json", "E382F_VERIFICATION_RESULTS.json",
      "MANIFEST.json", "MERKLE_ROOT.txt", "PUBLICATION.json", "E382F_OMEGA_SEAL.json",
      "E382F_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 verify_record(rec, pubs):
    body = {k: rec[k] for k in ("domain", "seq", "kind", "mission", "key", "value", "writer", "nonce", "ts")}
    try:
        Ed25519PublicKey.from_public_bytes(bytes.fromhex(pubs[rec["writer"]])).verify(
            bytes.fromhex(rec["sig"]), canon(body))
    except Exception:
        return False
    return sha((rec["prev"] + sha(canon(body) + rec["sig"].encode())).encode()) == rec["hash"]


def chain_ok(records, domain, pubs):
    prev = "0" * 64
    for rec in sorted([r for r in records if r["domain"] == domain], key=lambda r: r["seq"]):
        if rec["prev"] != prev or not verify_record(rec, pubs):
            return False
        prev = rec["hash"]
    return True


def grant_ok(g, rec, reader, pubs):
    if g["revoked"] or not (g["issued"] <= NOW <= g["expires"]):
        return False
    if g["grantor"] != rec["domain"] or g["grantee"] != reader:
        return False
    try:
        Ed25519PublicKey.from_public_bytes(bytes.fromhex(pubs[g["grantor"]])).verify(
            bytes.fromhex(g["sig"]), canon({k: g[k] for k in ("grantor", "grantee", "kinds", "mission", "issued", "expires", "nonce")}))
    except Exception:
        return False
    return rec["kind"] in g["kinds"] and rec["mission"] == g["mission"]


def grant_sig_ok(g, pubs):
    try:
        Ed25519PublicKey.from_public_bytes(bytes.fromhex(pubs[g["grantor"]])).verify(
            bytes.fromhex(g["sig"]), canon({k: g[k] for k in ("grantor", "grantee", "kinds", "mission", "issued", "expires", "nonce")}))
        return True
    except Exception:
        return False


def access(records, grants, reader, pubs):
    out = []
    for rec in records:
        if rec["domain"] == reader or any(grant_ok(g, rec, reader, pubs) for g in grants):
            out.append(rec)
    return out


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 / "E382F_MANIFEST.json").read_text())
    pre = json.loads((d / "E382F_PREREGISTRATION.json").read_text())
    frz = json.loads((d / "E382F_PREREGISTRATION_FREEZE.json").read_text())
    rep = json.loads((d / "E382F_RUN_REPORT.json").read_text())
    salt = json.loads((d / "E382F_SALT_REVEALED.json").read_text())
    acc = json.loads((d / "E382F_ACCEPTANCE_REGISTRY.json").read_text())
    dev = json.loads((d / "E382F_DEVIATIONS.json").read_text())
    led = rep["ledger"]
    ck("schema", man.get("schema") == "cain42.e382f.manifest.v1" and rep.get("evolution") == "E382-F")
    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"])
    body = json.loads((d / "E382F_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 / "E382F_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()))
    records, grants, pubs = led["records"], led["grants"], led["pubs"]
    ck("record count", len(records) == 49 and rep["design"]["records"] == {"A": 30, "B": 19})
    ck("record signatures", all(verify_record(r, pubs) for r in records))
    ck("chain A", chain_ok(records, "A", pubs))
    ck("chain B", chain_ok(records, "B", pubs))
    ck("grant signatures", all(grant_sig_ok(g, pubs) for g in grants))
    a_access = access(records, grants, "A", pubs)
    b_access = access(records, grants, "B", pubs)
    ck("intra A", len(a_access) == 30)
    ck("intra B", len([r for r in b_access if r["domain"] == "B"]) == 19)
    ck("cross deny", len([r for r in b_access if r["domain"] == "A"]) == 0)
    ck("checks reported", all(rep["checks"].values()) and all(all(v["checks"].values()) for v in rep["runs"].values()))
    ck("counts", rep["finding"]["counts"]["a_visible_to_a1"] == 30
       and rep["finding"]["counts"]["b_visible_to_b1"] == 19
       and rep["finding"]["counts"]["shared_with_grant"] == 20)
    expected = {
        "H1_intra_domain_visibility": "SUPPORTED", "H2_cross_domain_default_deny": "SUPPORTED",
        "H3_scoped_signed_grant": "SUPPORTED", "H4_revocation": "SUPPORTED",
        "H5_forged_expired_wrong_grantee": "SUPPORTED", "H6_no_cross_write_no_authority": "SUPPORTED",
        "H7_chain_and_tamper": "SUPPORTED", "H8_external_review": "BLOCKED"}
    ck("hypotheses", {k: v["verdict"] for k, v in rep["hypotheses"].items()} == expected)
    ck("verdict", rep["verdict"] == "FEDERATED_GOVERNED_MEMORY_SUPPORTED")
    ck("report verdict", f"**Preregistered verdict: {rep['verdict']}.**" in (d / "E382F_FINAL_REPORT.md").read_text())
    ck("public summary", rep["verdict"] in (d / "E382F_PUBLIC_SUMMARY.md").read_text())
    ck("acceptance", acc["verdict"] == rep["verdict"])
    ck("deviations", isinstance(dev.get("deviations"), list) and len(dev["deviations"]) == 0)
    ck("resources", rep["resources"]["model_calls"] == 0 and rep["resources"]["api_spend_usd"] == 0.0)
    ck("status", rep["status"] == S and man["status"] == S)
    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())
