#!/usr/bin/env python3
"""E377-R standalone offline verifier (stdlib + cryptography + the published QaaS verifier)."""
from __future__ import annotations

import hashlib
import json
import sys
from pathlib import Path

S = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
SCHEMA = "cain42.jit.batch_statement.v1"
EX = {"E377R_MANIFEST.json", "E377R_SIGNED_BODY.json", "E377R_VERIFICATION_RESULTS.json",
      "E377R_TAMPER_RESULTS.json", "MANIFEST.json", "MERKLE_ROOT.txt", "PUBLICATION.json",
      "E377R_OMEGA_SEAL.json"}


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


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


def leaf(h):
    return sha(("leaf|" + h).encode())


def node(l, r):
    return sha(("node|" + l + r).encode())


def verify_inclusion(commitment, path, root):
    h = leaf(commitment)
    for side, s in path:
        h = node(s, h) if side == "L" else node(h, s)
    return h == root


def commitment(row):
    doc = {"schema": SCHEMA, "statement_hash": row["statement_hash"],
           "principal": row["principal"], "revocation_epoch": float(row["revocation_epoch"]),
           "not_after": float(row["not_after"]), "approvers": json.loads(row["approvers"]),
           "reason": row["reason"], "ticket": row["ticket"],
           "policy_hash": row["policy_hash"] or ""}
    return sha(canon(doc))


def chain_ok(rows):
    prev = ""
    for row in rows:
        base = "|".join([prev, row["statement_hash"], row["principal"],
                         repr(float(row["revocation_epoch"])), repr(float(row["not_after"])),
                         row["approvers"], row["reason"], row["ticket"]])
        payload = ("v2|" + base + "|" + row["policy_hash"]) if row["policy_hash"] else base
        if sha(payload.encode()) != row["entry_hash"] or row["prev_hash"] != prev:
            return False
        prev = row["entry_hash"]
    return True


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 main() -> int:
    d = Path(sys.argv[1] if len(sys.argv) > 1 else ".").resolve()
    sys.path.insert(0, str(d))
    import verify_qaas_receipt as V
    rep = json.loads((d / "E377R_RUN_REPORT.json").read_text())
    pre = json.loads((d / "E377R_PREREGISTRATION.json").read_text())
    frz = json.loads((d / "E377R_PREREGISTRATION_FREEZE.json").read_text())
    ext = json.loads((d / "E377R_EXTERNAL_REVIEW_STATUS.json").read_text())
    man = json.loads((d / "E377R_MANIFEST.json").read_text())
    checks = []

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

    ck("schema", rep["schema"] == "cain42.e377r.run_report.v1")
    ck("evolution", rep["evolution"] == "E377-R")
    ck("status line", rep["status"] == S)
    ck("prereg hash", sha((d / "E377R_PREREGISTRATION.json").read_bytes())
       == frz["preregistration_sha256"])
    arms = {a["name"]: a for a in rep["arms"]}
    ck("two arms", set(arms) == {"crash_receipt", "healthy"})
    C, H = arms["crash_receipt"], arms["healthy"]
    ca, ha = rep["audit"]["crash"], rep["audit"]["healthy"]

    def arm_proofs(a):
        n = 0
        for row in a["rows"]:
            if row.get("batch_root"):
                n += 1 if verify_inclusion(commitment(row), json.loads(row["batch_proof"]),
                                           row["batch_root"]) else 0
        return n

    crash_vals, healthy_vals = [], []
    for a, out in ((C, crash_vals), (H, healthy_vals)):
        for r in a["receipts"]:
            if r["state"] != "done":
                continue
            rec = json.loads(r["receipt"])
            out.append(V.verify_receipt(rec, pin=rec["configuration_hash"],
                                        digest=r["digest"])["verdict"])
    ck("crash arm", C["accepted"] == 8 and C["roots"] == 2 and arm_proofs(C) == 8
       and chain_ok(C["rows"]))
    ck("healthy arm", H["accepted"] == 8 and H["roots"] == 2 and arm_proofs(H) == 8
       and chain_ok(H["rows"]))
    ck("crash receipts notarized", len(crash_vals) == 3
       and all(v == "NOTARIZED" for v in crash_vals))
    ck("healthy receipts notarized", len(healthy_vals) == 2
       and all(v == "NOTARIZED" for v in healthy_vals))
    ck("one duplicate digest", len(ca["duplicate_digest"]) == 1
       and ca["by_digest"][ca["duplicate_digest"][0]] == 2)
    dup = ca["duplicate_digest"][0] if ca["duplicate_digest"] else None
    ck("duplicate digest consistent", dup is not None and all(
        r["digest"] == dup for r in C["receipts"] if r["digest"] == dup))
    ck("two sequences reported", dup is not None and len(ca["sequences"].get(dup, [])) == 2)
    ck("healthy single attempts", not ha["duplicate_digest"]
       and all(n == 1 for n in ha["by_digest"].values()))
    ck("retrieval recorded", ca.get("retrieval_ok") is True and ha.get("retrieval_ok") is True)
    ck("every done receipt has a sequence", all(
        r.get("sequence") is not None for a in (C, H) for r in a["receipts"]
        if r["state"] == "done"))

    Hh = rep["hypotheses"]
    rec = {
        "H1_duplicate_submission": len(ca["duplicate_digest"]) == 1
        and ca["by_digest"][ca["duplicate_digest"][0]] == 2,
        "H2_duplicate_receipts_agree": len(crash_vals) == 3
        and all(v == "NOTARIZED" for v in crash_vals),
        "H3_store_retrieval": ca.get("retrieval_ok") is True and ha.get("retrieval_ok") is True,
        "H4_no_second_commitment": C["accepted"] == 8 and C["roots"] == 2
        and arm_proofs(C) == 8 and chain_ok(C["rows"]),
        "H5_healthy_single_attempt": not ha["duplicate_digest"]
        and all(n == 1 for n in ha["by_digest"].values()),
        "H6_receipts_offline": all(v == "NOTARIZED" for v in crash_vals + healthy_vals),
    }
    for k, v in rec.items():
        ck("hypothesis " + k, Hh[k]["verdict"] == ("SUPPORTED" if v else "NOT_SUPPORTED"))
    ck("verdict", rep["verdict"] == "RECEIPT_STORE_DUPLICATE_AUDIT_SUPPORTED"
       and all(Hh[k]["verdict"] == "SUPPORTED" for k in Hh if not k.startswith("H7")))
    ck("external blocked", Hh["H7_external_review"]["verdict"] == "BLOCKED"
       and ext["status"] == "NOT_OBTAINED")
    ck("model calls zero", rep["resources"]["model_calls"] == 0
       and rep["resources"]["api_spend_usd"] == 0.0 and rep["resources"]["hosts"] == 1)
    ck("live notarizations", rep["resources"]["live_notarizations"] == 5)
    ck("limits", len(rep["limits"]) == 6)
    ck("store documented", "jit_anchor_receipts" in pre["design"]["store"])

    ck("headline matches", man["headline"]["verdict"] == rep["verdict"])
    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
                   and not p.name.endswith(("-wal", "-shm")))
    ck("manifest files", man["files"] == {str(p.relative_to(d)): sha(p.read_bytes())
                                         for p in files})
    ck("merkle root", man["merkle_root"] == merkle(files))
    try:
        from cryptography.hazmat.primitives import serialization
        pk = serialization.load_pem_public_key((d / "E377R_PUBKEY.pem").read_bytes()) \
            if (d / "E377R_PUBKEY.pem").exists() else None
        if pk is None:
            from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
            pk = Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"]))
        pk.verify(bytes.fromhex(man["signature"]),
                  canon({k: v for k, v in man.items() if k != "signature"}))
        ck("manifest signature", True)
    except Exception as e:  # noqa: BLE001
        ck(f"manifest signature ({type(e).__name__})", False)

    ck("receipt verifiers shipped", (d / "verify_qaas_receipt.py").exists()
       and (d / "verify_pbft_qc_bundle.py").exists())
    ck("status in public summary", S in (d / "E377R_PUBLIC_SUMMARY.md").read_text())
    ck("no API key", "CAIN_API_KEY=" not in (d / "E377R_RUN_REPORT.json").read_text())

    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())
