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

A bank scores each online interaction for agent and fraud signals and then allows, holds or denies the transaction. The
package claims detection never stood in for authority. The review recomputes it:

  signals     every signal is on the policy's allowlist, has a value in [0, 1] and a SHA-256 of its raw source, and the
              record stores no raw behaviour (no `raw` field anywhere in a signal)
  scoring     the stated risk score equals the weighted sum of the signals recomputed here (clipped to [0, 1]); the stated
              agent-detected flag equals the recomputed agent score against the policy threshold
  authority   an interaction detected as an agent is allowed only with a mandate from a named human for this account and
              payee, within its amount and validity, and not revoked before the interaction
  decision    ALLOW requires all of: risk at or under the threshold, no fraud hold, and (if an agent) a valid mandate. A high
              trust score never substitutes for a missing mandate; a valid mandate never bypasses a fraud hold. HOLD or DENY
              is always acceptable (fail closed).
  claims      every boolean the package asserts matches what this review computed

Verdict: SOUND, else UNSOUND with every failing check named. Malformed input is UNSOUND.
It reviews the decision record; it does not judge whether the signal model detects agents or fraud well.
"""
from __future__ import annotations

import math
import re

_ID = re.compile(r"^[A-Za-z0-9_.:\-/]{1,120}$")
_HEX = re.compile(r"^[0-9a-f]{64}$")
DECISIONS = {"ALLOW", "HOLD", "DENY"}


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 evaluate(record):
    checks, summary = [], {"interactions": {}}

    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.agentrisk.session.v1":
            raise Bad("not a cain42.a75.agentrisk.session.v1 record")
        pol = record.get("policy")
        if not isinstance(pol, dict):
            raise Bad("policy must be an object")
        weights = pol.get("risk_weights")
        agent_w = pol.get("agent_weights")
        if not isinstance(weights, dict) or not weights or not isinstance(agent_w, dict) or not agent_w:
            raise Bad("policy.risk_weights and policy.agent_weights must be non-empty objects")
        for k, w in list(weights.items()) + list(agent_w.items()):
            _num(w, f"weight {k}", 0.0, 1.0)
        allowed = set(weights) | set(agent_w)
        threshold = _num(pol.get("risk_threshold"), "policy.risk_threshold", 0.0, 1.0)
        agent_threshold = _num(pol.get("agent_threshold"), "policy.agent_threshold", 0.0, 1.0)

        mandates = record.get("mandates") if isinstance(record.get("mandates"), list) else []
        M = {}
        for m in mandates:
            if not isinstance(m, dict):
                raise Bad("a mandate must be an object")
            M[_id(m.get("id"), "mandate.id")] = m

        inters = record.get("interactions")
        if not isinstance(inters, list) or not inters:
            raise Bad("interactions must be a non-empty list")
        seen = set()
        for it in inters:
            if not isinstance(it, dict):
                raise Bad("an interaction must be an object")
            iid = _id(it.get("id"), "interaction.id")
            if iid in seen:
                raise Bad(f"duplicate interaction {iid}")
            seen.add(iid)
            at = _num(it.get("at"), f"{iid}.at")
            sigs = it.get("signals")
            if not isinstance(sigs, list) or not sigs:
                raise Bad(f"{iid}.signals must be a non-empty list")
            vals, names = {}, []
            for s in sigs:
                if not isinstance(s, dict) or not isinstance(s.get("name"), str):
                    raise Bad(f"{iid}: a signal needs a name")
                n = s["name"]
                names.append(n)
                vals[n] = _num(s.get("value"), f"{iid}.{n}.value", 0.0, 1.0)
                c(f"{iid}.signal.{n}.allowed", n in allowed, f"signal {n!r} on the policy allowlist")
                c(f"{iid}.signal.{n}.hash", isinstance(s.get("source_sha256"), str) and bool(_HEX.match(s["source_sha256"])),
                  "raw source committed by SHA-256")
                c(f"{iid}.signal.{n}.no_raw", not any(k in s for k in ("raw", "raw_events", "keystrokes", "mouse_path")),
                  "no raw behaviour stored")
            c(f"{iid}.signals.unique", len(names) == len(set(names)), "each signal once")
            risk = min(1.0, sum(weights.get(n, 0.0) * v for n, v in vals.items()))
            agent_score = min(1.0, sum(agent_w.get(n, 0.0) * v for n, v in vals.items()))
            is_agent = agent_score >= agent_threshold
            stated = _num(it.get("risk_score"), f"{iid}.risk_score", 0.0, 1.0)
            c(f"{iid}.risk_recomputed", abs(stated - risk) <= 1e-6, f"stated {stated} vs recomputed {round(risk, 6)}")
            c(f"{iid}.agent_flag", it.get("agent_detected") is is_agent,
              f"stated {it.get('agent_detected')!r} vs recomputed {is_agent} (score {round(agent_score, 4)})")

            tx = it.get("transaction")
            if not isinstance(tx, dict):
                raise Bad(f"{iid}.transaction must be an object")
            amount = _num(tx.get("amount"), f"{iid}.transaction.amount")
            mid = it.get("mandate_id")
            m = M.get(mid) if mid else None
            problems = []
            if m is None:
                problems.append("no mandate" if not mid else f"unknown mandate {mid!r}")
            else:
                if not (isinstance(m.get("principal"), str) and m["principal"].startswith("human:")):
                    problems.append("mandate principal is not a named human")
                if m.get("account") != it.get("account"):
                    problems.append("mandate is for another account")
                if tx.get("payee") not in (m.get("payees") or []):
                    problems.append("payee not in mandate")
                if amount > _num(m.get("max_amount"), f"{mid}.max_amount") + 1e-9:
                    problems.append("amount over mandate")
                if not (_num(m.get("valid_from"), f"{mid}.valid_from") <= at <= _num(m.get("valid_to"), f"{mid}.valid_to")):
                    problems.append("outside mandate validity")
                rv = m.get("revoked_at")
                if rv is not None and _num(rv, f"{mid}.revoked_at") <= at:
                    problems.append("mandate revoked")
            mandate_ok = not problems
            hold = it.get("fraud_hold") is True
            decision = it.get("decision")
            if decision not in DECISIONS:
                raise Bad(f"{iid}.decision must be one of {sorted(DECISIONS)}")
            if decision == "ALLOW":
                c(f"{iid}.allow.risk", risk <= threshold + 1e-9, f"risk {round(risk, 4)} <= {threshold}")
                c(f"{iid}.allow.no_hold", not hold, "no fraud hold")
                c(f"{iid}.allow.mandate", (not is_agent) or mandate_ok,
                  "agent holds a valid mandate" if mandate_ok else f"agent without valid mandate: {problems}")
            summary["interactions"][iid] = {"risk": round(risk, 6), "agent": is_agent, "mandate_ok": mandate_ok,
                                            "fraud_hold": hold, "decision": decision}

        claims = record.get("claims") if isinstance(record.get("claims"), dict) else {}

        def all_ok(pred):
            return all(x["ok"] for x in checks if pred(x["id"]))

        computed = {
            "risk_recomputed": all_ok(lambda i: i.endswith((".risk_recomputed", ".agent_flag"))),
            "agents_mandated": all_ok(lambda i: i.endswith(".allow.mandate")),
            "holds_respected": all_ok(lambda i: i.endswith((".allow.no_hold", ".allow.risk"))),
            "raw_behaviour_not_stored": all_ok(lambda i: ".signal" in i),
        }
        for key in sorted(claims):
            c(f"claims.{key}", key in computed and claims[key] == computed[key], f"claimed {claims[key]!r}, computed {computed.get(key)!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.agentrisk.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-050, {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))
