#!/usr/bin/env python3
"""Clean-room offline verifier for CAIN continuous governance attestations (IP Evolution 10).

Imports NOTHING from CAIN: standard library + `cryptography` only. Re-implements the canonical form, the per-dimension
fingerprint, the envelope digest and signature, the attestation hash chain and the L4 continuity rule from the spec in
platform-gateway/cain_governance_attestation.py's docstrings, so a runtime bug shows up as a disagreement here
(tests/test_governance_attestation_cleanroom.py diffs the two).

    python3 scripts/attestation_verify_offline.py bundle.json --key <base64 Ed25519 attestation public key>
        [--subject tenant/agent --now S --window S --max-gap S]

bundle.json: {"envelope": <envelope>, "attestations": [<AttestationLog.export() entries>]}.
Exit 0 only if every check passes. Without --key nothing is accepted: a self-asserted key proves nothing.
"""
from __future__ import annotations

import argparse
import base64
import hashlib
import json
import sys

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

DIMS = ["identity", "capability", "authority", "policy", "contract", "model", "runtime", "tools", "dependencies",
        "environment", "evidence"]
LIVE = ("AUTHORIZED", "ACTIVE")


def canon(v):
    def walk(x):
        if isinstance(x, float):
            raise ValueError("float in canonical data")
        if isinstance(x, dict):
            for k, y in x.items():
                if not isinstance(k, str):
                    raise ValueError("non-string key")
                walk(y)
        elif isinstance(x, list):
            for y in x:
                walk(y)
        elif not (x is None or isinstance(x, (bool, int, str))):
            raise ValueError(f"type {type(x).__name__}")
    walk(v)
    return json.dumps(v, sort_keys=True, separators=(",", ":"), ensure_ascii=True, allow_nan=False).encode()


def h(ds, v):
    return hashlib.sha256(ds + b"\x1f" + canon(v)).hexdigest()


def sig_ok(pub, ds, dg, sig):
    try:
        Ed25519PublicKey.from_public_bytes(base64.b64decode(pub)).verify(base64.b64decode(sig),
                                                                        ds + b"\x1f" + dg.encode())
        return True
    except Exception:  # noqa: BLE001
        return False


def by_role(code, roles):
    return {k: v["sha256"] for k, v in code.items() if v["role"] in roles}


def dimension_digests(bom):
    caps = [{k: v for k, v in c.items() if k != "body"} for c in bom["capability"]]
    mat = {"identity": bom["identity"], "authority": bom["authority"], "model": bom["model"],
           "capability": [c for c in caps if c["state"] in LIVE],
           "contract": sorted([c["contract_id"], c["fingerprint"], c["state"]] for c in caps),
           "policy": bom["policy"], "runtime": by_role(bom["code"], ("decision",)),
           "tools": by_role(bom["code"], ("execution", "evidence")),
           "dependencies": {"versions": bom["dependencies"],
                            "verifiers": by_role(bom["code"], ("verification", "compiler"))},
           "environment": bom["environment"], "evidence": bom["evidence"]}
    return {d: h(b"CAIN/e10/v1/dimension" + d.encode(), mat[d]) for d in DIMS}


def verify(bundle, key, subject=None, now=None, window=None, max_gap=None):
    errs, out = [], {}
    env = bundle["envelope"]
    if env.get("signer_public_key_b64") != key:
        errs.append("envelope signer is not the pinned key")
    body = {k: v for k, v in env.items() if k not in ("bodies", "envelope_digest", "signature_b64")}
    if h(b"CAIN/e10/v1/envelope", body) != env.get("envelope_digest"):
        errs.append("envelope digest mismatch")
    if not sig_ok(key, b"CAIN/e10/v1/envelope", env.get("envelope_digest", ""), env.get("signature_b64", "")):
        errs.append("envelope signature invalid")
    if env.get("grants_authority") is not False:
        errs.append("envelope claims authority")
    dims = dimension_digests(env["bom"])
    if dims != env["fingerprint"]["dimensions"]:
        errs.append("fingerprint dimensions do not match the envelope BOM: "
                    + ",".join(d for d in DIMS if dims[d] != env["fingerprint"]["dimensions"].get(d)))
    if h(b"CAIN/e10/v1/fingerprint", dims) != env["fingerprint"]["composite"]:
        errs.append("composite fingerprint mismatch")
    if env["assurance_level"] >= 3 and env["proofs"]["status"] != "VALID":
        errs.append("envelope claims L3 without VALID proofs")
    prev = "0" * 64
    for i, e in enumerate(bundle.get("attestations", [])):
        st = e["statement"]
        if h(b"CAIN/e10/v1/attestation", st) != e["statement_digest"]:
            errs.append(f"attestation[{i}] digest mismatch")
        if st["prev_digest"] != prev:
            errs.append(f"attestation[{i}] chain break")
        if not sig_ok(key, b"CAIN/e10/v1/attestation", e["statement_digest"], e["signature_b64"]):
            errs.append(f"attestation[{i}] signature invalid")
        if st.get("grants_authority") is not False:
            errs.append(f"attestation[{i}] claims authority")
        # a tenant log holds every agent's attestations; only those made against THIS envelope are bounded by it
        if st.get("envelope_digest") == env.get("envelope_digest") and st["verdict"] == "CONTINUE" \
                and st["assurance_level"] > env["assurance_level"]:
            errs.append(f"attestation[{i}] level above its envelope")
        prev = e["statement_digest"]
    out["level"] = None
    if subject and now is not None and window and max_gap:
        mine = [e["statement"] for e in bundle.get("attestations", []) if e["statement"]["subject"] == subject]
        lvl = 0
        if mine and not errs:
            last = mine[-1]
            if now < last["valid_until_s"] and last["verdict"] == "CONTINUE":
                lvl = last["assurance_level"]
                win = [s for s in mine if s["valid_from_s"] >= now - window]
                gaps_ok = bool(win) and win[0]["valid_from_s"] - (now - window) <= max_gap and all(
                    b["valid_from_s"] - a["valid_from_s"] <= max_gap for a, b in zip(win, win[1:]))
                if lvl >= 3 and gaps_ok and all(s["verdict"] == "CONTINUE" and s["assurance_level"] >= 3 for s in win):
                    lvl = 4
            elif last["verdict"] == "CONTINUE":
                lvl = 1
        out["level"] = lvl
    out["errors"] = errs
    out["ok"] = not errs
    out["checked"] = {"envelope": 1, "attestations": len(bundle.get("attestations", [])), "dimensions": len(DIMS)}
    return out


def main(argv=None):
    ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    ap.add_argument("bundle")
    ap.add_argument("--key", required=True, help="pinned base64 Ed25519 attestation public key")
    ap.add_argument("--subject")
    ap.add_argument("--now", type=int)
    ap.add_argument("--window", type=int)
    ap.add_argument("--max-gap", type=int)
    a = ap.parse_args(argv)
    with open(a.bundle, encoding="utf-8") as f:
        bundle = json.load(f)
    r = verify(bundle, a.key, a.subject, a.now, a.window, a.max_gap)
    print(json.dumps(r, indent=2))
    return 0 if r["ok"] else 1


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