"""CAIN-A75-068 offline verifier (rules embedded verbatim). CAIN-A75-068 bring-your-own-agent rules. Standard library only, no CAIN imports: embedded verbatim in the offline verifier.

A customer-supplied agent running on a platform is third-party code with budget authority. Treat it as an untrusted workload:
platform-scoped credentials, a typed tool surface (not a general API key), a spend mandate, and platform-side evidence that
does not depend on the customer's own logging. The review recomputes:

  credentials  each call presents a credential the platform issued to that customer's agent, unexpired and unrevoked at the
               call time, whose scopes include the tool
  surface      the tool is in the platform's typed surface and the parameters match its schema exactly: every declared
               parameter present with the right type (str / int / number / bool / enum), no extra parameters
  mandate      a spending call is in the mandate currency, to an allowed counterparty, before the mandate expires, within the
               per-call limit of the tool, and the customer's allowed spend stays within the mandate budget
  decision     the stated decision equals the one recomputed from the above
  evidence     the platform log is a SHA-256 hash chain with contiguous sequence numbers, sealed by a head and count; the
               reconciliation against the customer's own log (calls missing from it, calls only it claims, spend that differs)
               equals the recomputation; the customer's log is never used as evidence
  claims       every boolean the platform record asserts matches what this review computed

Verdict: SOUND, else UNSOUND with every failing check named. Malformed input is UNSOUND. It reviews the platform record; it does
not run the customer's agent or call an ad platform.
"""
from __future__ import annotations

import hashlib
import json
import math
import re

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


class Bad(ValueError):
    pass


def entry_hash(prev, entry):
    body = {k: v for k, v in entry.items() if k not in ("hash", "prev")}
    return hashlib.sha256((prev + json.dumps(body, sort_keys=True, separators=(",", ":"), ensure_ascii=True)).encode()).hexdigest()


def chain(log):
    prev = GENESIS
    for k, e in enumerate(log, start=1):
        e["seq"] = k
        e["prev"] = prev
        e["hash"] = prev = entry_hash(prev, e)
    return prev


def type_ok(value, spec):
    if spec == "str":
        return isinstance(value, str) and 0 < len(value) <= 500
    if spec == "int":
        return isinstance(value, int) and not isinstance(value, bool)
    if spec == "number":
        return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value)
    if spec == "bool":
        return isinstance(value, bool)
    if isinstance(spec, str) and spec.startswith("enum:"):
        return isinstance(value, str) and value in spec[5:].split("|")
    return False


def params_ok(params, schema):
    if not isinstance(params, dict) or not isinstance(schema, dict):
        return False, "parameters or schema missing"
    extra = sorted(set(params) - set(schema))
    missing = sorted(set(schema) - set(params))
    wrong = sorted(k for k in schema if k in params and not type_ok(params[k], schema[k]))
    ok = not extra and not missing and not wrong
    return ok, ("parameters match the schema" if ok else f"extra {extra}, missing {missing}, wrong type {wrong}")


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 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.byoagent.review.v1":
            raise Bad("not a cain42.a75.byoagent.review.v1 record")
        surface = record.get("tool_surface")
        if not isinstance(surface, dict) or not surface:
            raise Bad("tool_surface must be a non-empty object")
        creds = {}
        for cr in record.get("credentials") or []:
            if not isinstance(cr, dict) or not isinstance(cr.get("id"), str):
                raise Bad("a credential needs an id")
            creds[cr["id"]] = cr
        mandates = {}
        for m in record.get("mandates") or []:
            if not isinstance(m, dict) or not isinstance(m.get("customer"), str):
                raise Bad("a mandate needs a customer")
            mandates[m["customer"]] = m
        log = record.get("platform_log")
        if not isinstance(log, list) or not log or not all(isinstance(e, dict) for e in log):
            raise Bad("platform_log must be a non-empty list of objects")

        prev, chain_ok, seq_ok, spent, n_allow, n_deny = GENESIS, True, True, {}, 0, 0
        for k, e in enumerate(log, start=1):
            seq_ok &= e.get("seq") == k
            chain_ok &= e.get("prev") == prev and e.get("hash") == entry_hash(prev, e)
            prev = e.get("hash") if isinstance(e.get("hash"), str) else ""
            at = _num(e.get("at"), f"call {k}.at")
            cr, tool = creds.get(e.get("credential")), e.get("tool")
            why = []
            if cr is None:
                why.append("unknown credential")
            else:
                if cr.get("agent") != e.get("agent") or cr.get("customer") != e.get("customer"):
                    why.append("credential issued to another agent or customer")
                if not (float(cr.get("issued_at", math.inf)) <= at < float(cr.get("expires_at", -1))):
                    why.append("credential not valid at this time")
                if cr.get("revoked_at") is not None and at >= float(cr["revoked_at"]):
                    why.append("credential revoked")
                if tool not in (cr.get("scopes") or []):
                    why.append("tool outside the credential's scopes")
            spec = surface.get(tool) if isinstance(tool, str) else None
            if not isinstance(spec, dict):
                why.append("tool not on the typed surface")
            else:
                ok, detail = params_ok(e.get("params"), spec.get("params"))
                if not ok:
                    why.append(detail)
            spend = e.get("spend")
            if spend is not None:
                amt = _num(spend.get("amount") if isinstance(spend, dict) else None, f"call {k}.spend.amount")
                m = mandates.get(e.get("customer"))
                if m is None:
                    why.append("no mandate for this customer")
                else:
                    if spend.get("currency") != m.get("currency"):
                        why.append("currency")
                    if spend.get("counterparty") not in (m.get("counterparties") or []):
                        why.append("counterparty outside the mandate")
                    if at >= float(m.get("expires_at", -1)):
                        why.append("mandate expired")
                    if isinstance(spec, dict) and amt > float(spec.get("max_spend", 0)):
                        why.append("over the tool's per-call limit")
                    if not why and spent.get(e["customer"], 0.0) + amt > float(m.get("budget", 0)) + 1e-9:
                        why.append("mandate budget exhausted")
            elif isinstance(spec, dict) and spec.get("spends"):
                why.append("spending tool called without a recorded spend")
            exp = "DENY" if why else "ALLOW"
            c(f"call.{k}.decision", e.get("decision") == exp,
              f"{e.get('agent')!r} {tool!r}: stated {e.get('decision')!r}, recomputed {exp!r}" + (f" ({'; '.join(why)})" if why else ""))
            if exp == "ALLOW" and e.get("decision") == "ALLOW":
                n_allow += 1
                if spend is not None:
                    spent[e["customer"]] = spent.get(e["customer"], 0.0) + float(spend["amount"])
            else:
                n_deny += 1
        c("evidence.chain", chain_ok, "platform log chains by SHA-256")
        c("evidence.contiguous", seq_ok, "sequence numbers 1..n")
        seal = record.get("platform_seal") if isinstance(record.get("platform_seal"), dict) else {}
        c("evidence.sealed", seal.get("head") == prev and seal.get("events") == len(log),
          f"sealed head {str(seal.get('head'))[:12]} / {seal.get('events')!r} vs recomputed {prev[:12]} / {len(log)}")
        c("evidence.platform_source", record.get("evidence_source") == "platform", f"evidence source {record.get('evidence_source')!r}")

        cust = record.get("customer_log") if isinstance(record.get("customer_log"), list) else []
        plat = {e.get("request_id"): e for e in log if e.get("decision") == "ALLOW"}
        mine = {x.get("request_id"): x for x in cust if isinstance(x, dict)}
        missing = sorted(str(k) for k in plat if k not in mine)
        only_customer = sorted(str(k) for k in mine if k not in plat)
        differ = sorted(str(k) for k in plat if k in mine and (plat[k].get("spend") or {}).get("amount") != (mine[k].get("spend") or {}).get("amount"))
        want = {"missing_from_customer_log": missing, "only_in_customer_log": only_customer, "spend_differs": differ}
        got = record.get("reconciliation") if isinstance(record.get("reconciliation"), dict) else {}
        c("evidence.reconciliation", {k: sorted(map(str, got.get(k) or [])) for k in want} == want, f"stated {got}, recomputed {want}")

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

        computed = {"decisions_recomputed": all_ok(lambda i: i.endswith(".decision")),
                    "platform_evidence_independent": all_ok(lambda i: i.startswith("evidence.")),
                    "customer_log_matches": not any(want.values())}
        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, "calls": len(log), "allowed": n_allow, "denied": n_deny,
                        "spent": {k: round(spent[k], 2) for k in sorted(spent)}, "reconciliation": want})
    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.byoagent.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-068, {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))
