"""CAIN-A75-064 offline verifier (rules embedded verbatim). CAIN-A75-064 agent inventory and cost accountability rules. Standard library only, no CAIN imports: embedded verbatim in
the offline verifier.

You cannot govern an agent you cannot enumerate. Inventory, owner, authority and spend have to be joined in one record, or every
control has a blind spot. An unregistered agent is denied by default, not discovered later. The review recomputes:

  registry     every registered agent names an active human owner from the people directory, a non-empty tool list, data
               scope and authority scopes, a positive budget for the period, and a registration time before any use
  boundary     every call seen at the boundary is re-decided here: ALLOW only when the agent is registered and not retired at
               the call time, the tool is in its inventory, the data class is in its data scope, the scope used is granted, and
               the agent's cumulative allowed spend in the period plus this call's quoted price stays within its budget;
               otherwise DENY. The stated decision must equal the recomputed one; an allowed call is billed its quote and a
               denied call is billed nothing
  cost         the cost report's per-agent and per-owner totals equal the sums of allowed calls, nothing is unattributed, and
               every agent with spend appears
  claims       every boolean the inventory asserts matches what this review computed

Verdict: SOUND, else UNSOUND with every failing check named. Malformed input is UNSOUND. It reviews the inventory and boundary
log; it does not discover agents on a network or read an invoice.
"""
from __future__ import annotations

import math
import re

_ID = re.compile(r"^[A-Za-z0-9_.:\-/@]{1,120}$")


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 _r2(x):
    return round(x + 0.0, 2)


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.agentinventory.review.v1":
            raise Bad("not a cain42.a75.agentinventory.review.v1 record")
        period = record.get("period") if isinstance(record.get("period"), dict) else {}
        p0, p1 = _num(period.get("from"), "period.from"), _num(period.get("to"), "period.to")
        if p1 <= p0:
            raise Bad("period.to must follow period.from")
        people = {}
        for p in record.get("people") or []:
            if isinstance(p, dict):
                people[_id(p.get("id"), "person.id")] = p
        reg = record.get("registry")
        if not isinstance(reg, list) or not reg:
            raise Bad("registry must be a non-empty list")
        AG = {}
        for a in reg:
            if not isinstance(a, dict):
                raise Bad("a registry entry must be an object")
            aid = _id(a.get("id"), "agent.id")
            if aid in AG:
                raise Bad(f"duplicate agent {aid}")
            AG[aid] = a
            owner = people.get(a.get("owner"))
            c(f"agent.{aid}.owner", isinstance(a.get("owner"), str) and a["owner"].startswith("human:") and owner is not None
              and owner.get("active") is True, f"owner {a.get('owner')!r} is an active person")
            for f in ("tools", "data_scope", "scopes"):
                v = a.get(f)
                c(f"agent.{aid}.{f}", isinstance(v, list) and bool(v) and all(isinstance(x, str) for x in v), f"{f} {v!r}")
            b = a.get("budget_usd")
            c(f"agent.{aid}.budget", isinstance(b, (int, float)) and not isinstance(b, bool) and math.isfinite(b) and b > 0, f"budget {b!r}")
            _num(a.get("registered_at"), f"{aid}.registered_at")
            if a.get("retired_at") is not None:
                _num(a.get("retired_at"), f"{aid}.retired_at")

        calls = record.get("boundary_log")
        if not isinstance(calls, list) or not calls:
            raise Bad("boundary_log must be a non-empty list")
        spent, by_owner, n_allow, n_deny, last = {}, {}, 0, 0, -1.0
        for k, x in enumerate(calls, start=1):
            if not isinstance(x, dict):
                raise Bad("a boundary call must be an object")
            at, cost = _num(x.get("at"), f"call {k}.at"), _num(x.get("cost_usd"), f"call {k}.cost_usd")
            quote = _num(x.get("quoted_usd"), f"call {k}.quoted_usd")
            if at < last:
                raise Bad("boundary_log must be in time order")
            last = at
            a = AG.get(x.get("agent"))
            why = []
            if a is None:
                why.append("unregistered")
            else:
                if at < float(a["registered_at"]):
                    why.append("before registration")
                if a.get("retired_at") is not None and at >= float(a["retired_at"]):
                    why.append("retired")
                if x.get("tool") not in (a.get("tools") or []):
                    why.append("tool not in inventory")
                if x.get("data_class") not in (a.get("data_scope") or []):
                    why.append("data class outside scope")
                if x.get("scope") not in (a.get("scopes") or []):
                    why.append("scope not granted")
                if not (p0 <= at < p1):
                    why.append("outside the period")
                if not why and spent.get(a["id"], 0.0) + quote > float(a.get("budget_usd") or 0) + 1e-9:
                    why.append("budget exhausted")
            expected = "DENY" if why else "ALLOW"
            c(f"call.{k}.decision", x.get("decision") == expected,
              f"{x.get('agent')!r} {x.get('tool')!r}: stated {x.get('decision')!r}, recomputed {expected!r}" + (f" ({', '.join(why)})" if why else ""))
            if expected == "ALLOW" and x.get("decision") == "ALLOW":
                c(f"call.{k}.billed", abs(cost - quote) <= 1e-9, f"billed {cost:g} for a call quoted at {quote:g}")
                n_allow += 1
                spent[a["id"]] = spent.get(a["id"], 0.0) + cost
                by_owner[a["owner"]] = by_owner.get(a["owner"], 0.0) + cost
            else:
                n_deny += 1
                c(f"call.{k}.denied_free", cost == 0 or x.get("decision") == "ALLOW", f"denied call billed {cost:g}")

        rep = record.get("cost_report") if isinstance(record.get("cost_report"), dict) else {}
        ra = rep.get("by_agent") if isinstance(rep.get("by_agent"), dict) else {}
        ro = rep.get("by_owner") if isinstance(rep.get("by_owner"), dict) else {}
        want_a = {k: _r2(spent[k]) for k in sorted(spent)}
        want_o = {k: _r2(by_owner[k]) for k in sorted(by_owner)}
        got_a = {str(k): _r2(ra[k]) for k in sorted(ra, key=str) if isinstance(ra[k], (int, float)) and not isinstance(ra[k], bool)}
        got_o = {str(k): _r2(ro[k]) for k in sorted(ro, key=str) if isinstance(ro[k], (int, float)) and not isinstance(ro[k], bool)}
        c("cost.by_agent", {k: v for k, v in got_a.items() if v} == {k: v for k, v in want_a.items() if v},
          f"stated {got_a}, recomputed {want_a}")
        c("cost.by_owner", {k: v for k, v in got_o.items() if v} == {k: v for k, v in want_o.items() if v},
          f"stated {got_o}, recomputed {want_o}")
        un = rep.get("unattributed_usd")
        c("cost.unattributed", un == 0, f"unattributed {un!r}")

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

        computed = {"every_agent_owned": all_ok(lambda i: i.endswith(".owner")),
                    "inventory_complete": all_ok(lambda i: i.startswith("agent.") and not i.endswith(".owner")),
                    "unregistered_denied": all_ok(lambda i: i.endswith(".decision")),
                    "budget_enforced": all_ok(lambda i: i.endswith((".decision", ".budget"))),
                    "cost_attributed": all_ok(lambda i: i.startswith("cost.") or i.endswith((".denied_free", ".billed")))}
        claims = record.get("claims") if isinstance(record.get("claims"), dict) else {}
        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.update({"computed": computed, "agents": len(AG), "allowed": n_allow, "denied": n_deny,
                        "spend_by_owner": want_o, "spend_by_agent": want_a})
    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.agentinventory.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-064, {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))
