"""CAIN-A75-051 offline verifier (rules embedded verbatim). CAIN-A75-051 agent-identity rules. Standard library only, no CAIN imports: embedded verbatim in the offline verifier.

An agent identity is not a keypair. It is a composite record: an accountable human, an operator, a workload identity, a
purpose, a delegation chain, the model and tool versions it runs, and evidence that changes over time. The package claims a
trust state for the agent. The review recomputes it:

  composite   the agent names a named-human accountable party, an operator, a SPIFFE workload id inside the operator's trust
              domain, a purpose on the policy's allowlist, and a committed public key
  delegation  the chain starts at the accountable human, ends at the agent, links hop to hop, only narrows scopes, and every
              link is valid at the review time
  versions    every runtime component the policy requires (e.g. model, tool) is attested by hash, and fresh
  trust       the trust score equals the decayed sum recomputed here, T = min(1, sum w_type * 2^(-age / half_life)), over
              hashed evidence about this agent issued by someone other than the agent; registration alone never makes an
              agent TRUSTED; stale evidence decays; a revoked key or delegation link makes the state REVOKED
  claims      the stated trust score and state, and every boolean the package asserts, match what this review computed

Verdict: SOUND, else UNSOUND with every failing check named. Malformed input is UNSOUND.
It reviews the identity record; it does not look up any bureau, registry or certificate authority.
"""
from __future__ import annotations

import math
import re

_ID = re.compile(r"^[A-Za-z0-9_.:\-/@]{1,160}$")
_HEX = re.compile(r"^[0-9a-f]{64}$")
_SPIFFE = re.compile(r"^spiffe://([a-z0-9.\-]{1,120})(/[A-Za-z0-9._\-/]{1,200})$")
STATES = ("TRUSTED", "DEGRADED", "UNTRUSTED", "REVOKED")


class Bad(ValueError):
    pass


def _num(v, what, lo=0.0, hi=1e15):
    if isinstance(v, bool) or not isinstance(v, (int, float)) or not math.isfinite(v) or not (lo <= v <= hi):
        raise Bad(f"{what} must be a finite number in [{lo}, {hi}]")
    return float(v)


def _id(v, what):
    if not isinstance(v, str) or not _ID.match(v):
        raise Bad(f"{what} must be an id")
    return v


def _human(p):
    return isinstance(p, str) and p.startswith("human:") and len(p) > 6


def evaluate(record):
    checks, summary = [], {}

    def c(cid, ok, detail=""):
        checks.append({"id": cid, "ok": bool(ok), "detail": detail})

    try:
        if not isinstance(record, dict) or record.get("schema") != "cain42.a75.agentidentity.review.v1":
            raise Bad("not a cain42.a75.agentidentity.review.v1 record")
        pol, ag = record.get("policy"), record.get("agent")
        if not isinstance(pol, dict) or not isinstance(ag, dict):
            raise Bad("policy and agent must be objects")
        as_of = _num(record.get("as_of"), "as_of")
        half = _num(pol.get("half_life_s"), "policy.half_life_s", 1.0, 1e10)
        max_age = _num(pol.get("max_evidence_age_s"), "policy.max_evidence_age_s", 1.0, 1e10)
        t_hi = _num(pol.get("trusted_threshold"), "policy.trusted_threshold", 0.0, 1.0)
        t_lo = _num(pol.get("degraded_threshold"), "policy.degraded_threshold", 0.0, 1.0)
        weights = pol.get("evidence_weights")
        if not isinstance(weights, dict) or not weights:
            raise Bad("policy.evidence_weights must be a non-empty object")
        for k, w in weights.items():
            _num(w, f"weight {k}", 0.0, 1.0)
        c("policy.thresholds", t_lo <= t_hi, f"degraded {t_lo} <= trusted {t_hi}")

        # ---- composite identity
        aid = _id(ag.get("id"), "agent.id")
        operator = ag.get("operator")
        if not isinstance(operator, dict):
            raise Bad("agent.operator must be an object")
        c("composite.accountable_human", _human(ag.get("accountable_human")), f"accountable {ag.get('accountable_human')!r}")
        c("composite.operator", isinstance(operator.get("id"), str) and bool(operator.get("id")), f"operator {operator.get('id')!r}")
        m = _SPIFFE.match(ag.get("workload_id") or "") if isinstance(ag.get("workload_id"), str) else None
        c("composite.workload", bool(m) and m.group(1) == operator.get("trust_domain"),
          f"workload {ag.get('workload_id')!r} in trust domain {operator.get('trust_domain')!r}")
        c("composite.purpose", ag.get("purpose") in (pol.get("allowed_purposes") or []), f"purpose {ag.get('purpose')!r}")
        key = ag.get("key") if isinstance(ag.get("key"), dict) else {}
        c("composite.key", isinstance(key.get("public_key_sha256"), str) and bool(_HEX.match(key["public_key_sha256"])),
          "public key committed by SHA-256")

        # ---- delegation chain
        chain = record.get("delegation")
        if not isinstance(chain, list) or not chain:
            raise Bad("delegation must be a non-empty list")
        prev_to, prev_scopes = ag.get("accountable_human"), None
        for i, ln in enumerate(chain):
            if not isinstance(ln, dict):
                raise Bad("a delegation link must be an object")
            sc = ln.get("scopes")
            if not isinstance(sc, list) or not sc:
                raise Bad(f"delegation[{i}].scopes must be a non-empty list")
            c(f"delegation.{i}.links", ln.get("from") == prev_to, f"from {ln.get('from')!r} after {prev_to!r}")
            c(f"delegation.{i}.attenuates", prev_scopes is None or set(sc) <= prev_scopes,
              "scopes only narrow" if prev_scopes is None or set(sc) <= prev_scopes else f"widened by {sorted(set(sc) - prev_scopes)}")
            c(f"delegation.{i}.valid", _num(ln.get("issued_at"), f"delegation[{i}].issued_at") <= as_of
              < _num(ln.get("expires_at"), f"delegation[{i}].expires_at"), "valid at the review time")
            prev_to, prev_scopes = ln.get("to"), set(sc)
        c("delegation.ends_at_agent", prev_to == aid, f"chain ends at {prev_to!r}")
        summary["effective_scopes"] = sorted(prev_scopes or [])

        # ---- runtime versions
        atts = record.get("runtime") if isinstance(record.get("runtime"), list) else []
        for kind in pol.get("required_runtime") or []:
            good = [a for a in atts if isinstance(a, dict) and a.get("kind") == kind and isinstance(a.get("sha256"), str)
                    and _HEX.match(a["sha256"]) and isinstance(a.get("version"), str) and a.get("version")
                    and as_of - _num(a.get("observed_at"), f"runtime.{kind}.observed_at") <= max_age]
            c(f"runtime.{kind}", bool(good), f"{len(good)} fresh hashed {kind} attestation(s)")

        # ---- revocation
        revs = record.get("revocations") if isinstance(record.get("revocations"), list) else []
        revoked_ids = {r.get("target") for r in revs if isinstance(r, dict)
                       and _num(r.get("at"), "revocation.at") <= as_of}
        link_ids = {ln.get("id") for ln in chain if ln.get("id")}
        revoked = bool(revoked_ids & ({aid, key.get("public_key_sha256")} | link_ids))
        summary["revoked"] = revoked

        # ---- trust
        ev = record.get("evidence")
        if not isinstance(ev, list):
            raise Bad("evidence must be a list")
        score, fresh_non_reg, used = 0.0, 0, 0
        for j, e in enumerate(ev):
            if not isinstance(e, dict):
                raise Bad("an evidence item must be an object")
            t = e.get("type")
            age = as_of - _num(e.get("observed_at"), f"evidence[{j}].observed_at")
            ok = (t in weights and e.get("subject") == aid and e.get("issuer") not in (None, "", aid)
                  and isinstance(e.get("sha256"), str) and bool(_HEX.match(e["sha256"])) and age >= 0)
            c(f"evidence.{j}.usable", ok or t in weights, f"{t!r} from {e.get('issuer')!r}")
            if not ok:
                continue
            used += 1
            score += weights[t] * 2 ** (-age / half)
            if t != "registration" and age <= max_age:
                fresh_non_reg += 1
        score = min(1.0, score)
        runtime_ok = all(x["ok"] for x in checks if x["id"].startswith("runtime."))
        structure_ok = all(x["ok"] for x in checks if x["id"].startswith(("composite.", "delegation.")))
        if revoked:
            state = "REVOKED"
        elif score >= t_hi and fresh_non_reg >= 1 and runtime_ok and structure_ok:
            state = "TRUSTED"
        elif score >= t_lo and structure_ok:
            state = "DEGRADED"
        else:
            state = "UNTRUSTED"
        summary.update(trust_score=round(score, 6), trust_state=state, evidence_used=used, fresh_non_registration=fresh_non_reg)
        stated = record.get("trust") if isinstance(record.get("trust"), dict) else {}
        c("trust.score", isinstance(stated.get("score"), (int, float)) and not isinstance(stated.get("score"), bool)
          and abs(stated["score"] - score) <= 1e-6, f"stated {stated.get('score')!r} vs recomputed {round(score, 6)}")
        c("trust.state", stated.get("state") == state, f"stated {stated.get('state')!r} vs recomputed {state}")

        claims = record.get("claims") if isinstance(record.get("claims"), dict) else {}
        computed = {"composite_identity_complete": all(x["ok"] for x in checks if x["id"].startswith("composite.")),
                    "delegation_chain_valid": all(x["ok"] for x in checks if x["id"].startswith("delegation.")),
                    "runtime_attested": runtime_ok,
                    "trust_from_current_evidence": fresh_non_reg >= 1,
                    "not_revoked": not revoked}
        for k in sorted(claims):
            c(f"claims.{k}", k in computed and claims[k] == computed[k], f"claimed {claims[k]!r}, computed {computed.get(k)!r}")
        summary["computed"] = computed
    except Bad as e:
        checks.append({"id": "input.well_formed", "ok": False, "detail": str(e)})
        return "UNSOUND", checks, summary
    except Exception as e:  # noqa: BLE001
        checks.append({"id": "input.error", "ok": False, "detail": f"{type(e).__name__}: {e}"[:200]})
        return "UNSOUND", checks, summary
    return ("SOUND" if all(x["ok"] for x in checks) else "UNSOUND"), checks, summary


# ---------------------------------------------------------------------------- offline verifier (no CAIN imports)
# Every name below is prefixed _kit_verifier_ / _b64 / _hl / _json / _sys so it cannot shadow a name in the rules above.
import base64 as _b64, hashlib as _hl, json as _json, sys as _sys
_KIT_VERIFIER_GENESIS = _hl.sha256(b"cain42.a75.agentidentity.genesis").hexdigest()


def _kit_verifier_canon(o):
    return _json.dumps(o, sort_keys=True, separators=(",", ":"), ensure_ascii=True).encode()


def _kit_verifier_sha(o):
    return _hl.sha256(_kit_verifier_canon(o)).hexdigest()


def _kit_verifier_main(argv):
    from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
    if len(argv) < 2:
        print("usage: verify_offline.py run.json --pinned-key BASE64"); return 2
    run = _json.load(open(argv[1]))
    pin = argv[argv.index("--pinned-key") + 1] if "--pinned-key" in argv else None
    problems, prev, recs = [], _KIT_VERIFIER_GENESIS, run.get("records") or []
    for i, r in enumerate(recs):
        body = {k: v for k, v in r.items() if k not in ("record_hash", "signature_b64")}
        if _kit_verifier_sha(body) != r.get("record_hash"): problems.append(f"record {i}: record_hash does not match")
        if body.get("subject_sha256") != _kit_verifier_sha(body.get("subject")): problems.append(f"record {i}: subject_sha256 does not match")
        if pin and r.get("public_key_b64") != pin: problems.append(f"record {i}: different key than the pinned one")
        try:
            Ed25519PublicKey.from_public_bytes(_b64.b64decode(pin or r.get("public_key_b64"))).verify(
                _b64.b64decode(r.get("signature_b64", "")), str(r.get("record_hash")).encode())
        except Exception:
            problems.append(f"record {i}: signature does not verify")
        if r.get("prev_record_hash") != prev: problems.append(f"record {i}: chain link broken")
        v, checks, _ = evaluate(r.get("subject"))
        if v != r.get("verdict") or checks != r.get("checks"):
            problems.append(f"record {i}: re-running the rules gives {v}, the record says {r.get('verdict')}")
        prev = r.get("record_hash")
    if run.get("run_hash") != _kit_verifier_sha([r.get("record_hash") for r in recs]): problems.append("run_hash does not match")
    for p in problems: print("  -", p)
    if not pin: print("WARNING: no --pinned-key given; the signature was checked against the key inside the file")
    print("VERDICT:", "VERIFIED" if not problems else "TAMPERED OR INVALID", f"(CAIN-A75-051, {len(recs)} record(s), verdicts {run.get('verdicts')})")
    return 0 if not problems else 1


if __name__ == "__main__":
    _sys.exit(_kit_verifier_main(_sys.argv))
