"""CAIN-A75-006 offline verifier (rules embedded verbatim). CAIN-A75-006 swarm delegation rules. Standard library only, no CAIN imports: embedded verbatim in the offline verifier.

One prompt can start a team of specialised agents. Each handoff is a delegation, and a delegation must only ever narrow what the
parent held. The review recomputes a delegation graph from its root grant:

  root         the root capability is issued by a named human to an agent, with a scope, resources, a lifetime and a budget
  binding      every delegation names its parent, was issued by the parent's holder, and carries the SHA-256 of the exact parent
               capability it was cut from; a parent must appear before its children, so the graph cannot loop
  attenuation  a child's operations are a subset of the parent's, its resources are covered by the parent's, it expires no later
               than the parent, it stays in the parent's tenant and within the depth limit
  budget       what a capability hands down plus what its holder spends never exceeds its own budget
  one path     an agent holds one capability, so two partial grants cannot be merged into a wider one
  actions      every recorded action was taken by the capability's holder, inside its operations, resources and lifetime
  claims       every boolean the record asserts matches what this review computed

Verdict: SOUND, else UNSOUND with every failing check named. Malformed input is UNSOUND. It reviews the delegation record; it
does not observe the agents and cannot see a handoff that was never recorded.
"""
from __future__ import annotations

import hashlib
import json
import math
import re

_HEX = re.compile(r"^[0-9a-f]{64}$")
SCHEMA = "cain42.a75.swarmdelegation.review.v1"
CAP_FIELDS = ("id", "holder", "scope", "resources", "issued_at", "expires_at", "budget", "tenant")
MAX_CAPS, MAX_ACTIONS = 500, 5000


class Bad(ValueError):
    pass


def cap_sha256(cap):
    """SHA-256 of the capability's canonical JSON over its authority fields."""
    body = {k: cap.get(k) for k in CAP_FIELDS}
    return hashlib.sha256(json.dumps(body, sort_keys=True, separators=(",", ":"), ensure_ascii=True).encode()).hexdigest()


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 _strs(v, what):
    if not isinstance(v, list) or not v or not all(isinstance(x, str) and x for x in v):
        raise Bad(f"{what} must be a non-empty list of strings")
    return v


def _agent(v):
    return isinstance(v, str) and v.startswith("agent:") and len(v) > 6


def _covers(parent_resources, res):
    for p in parent_resources:
        if p == res or p == "*" or (p.endswith("*") and res.startswith(p[:-1])):
            return True
    return False


def _cap(c, what):
    if not isinstance(c, dict) or not isinstance(c.get("id"), str) or not c["id"]:
        raise Bad(f"{what} needs an id")
    cid = c["id"]
    _strs(c.get("scope"), f"{cid}.scope"); _strs(c.get("resources"), f"{cid}.resources")
    _num(c.get("issued_at"), f"{cid}.issued_at"); _num(c.get("expires_at"), f"{cid}.expires_at"); _num(c.get("budget"), f"{cid}.budget")
    if not isinstance(c.get("tenant"), str) or not c["tenant"]:
        raise Bad(f"{cid}.tenant is required")
    return cid


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") != SCHEMA:
            raise Bad(f"not a {SCHEMA} record")
        root, dels, acts = record.get("root"), record.get("delegations"), record.get("actions")
        if not isinstance(dels, list) or not isinstance(acts, list) or len(dels) > MAX_CAPS or len(acts) > MAX_ACTIONS:
            raise Bad(f"delegations (at most {MAX_CAPS}) and actions (at most {MAX_ACTIONS}) must be lists")
        max_depth = record.get("max_depth")
        if isinstance(max_depth, bool) or not isinstance(max_depth, int) or not (1 <= max_depth <= 32):
            raise Bad("max_depth must be an integer from 1 to 32")
        rid = _cap(root, "root")
        by = root.get("issued_by")
        c("root.issued_by_human", isinstance(by, str) and by.startswith("human:") and len(by) > 6 and _agent(root.get("holder")),
          f"issued by {by!r} to {root.get('holder')!r}")
        c("root.lifetime", root["issued_at"] < root["expires_at"], f"issued {root['issued_at']}, expires {root['expires_at']}")
        caps, depth, handed, holders = {rid: root}, {rid: 0}, {rid: 0.0}, {}
        holders.setdefault(root.get("holder"), []).append(rid)
        for d in dels:
            did = _cap(d, "a delegation")
            if did in caps:
                raise Bad(f"capability id {did!r} is used twice")
            k = f"edge.{did}"
            p = caps.get(d.get("parent"))
            c(f"{k}.parent_bound", p is not None and d.get("parent_sha256") == cap_sha256(p),
              f"parent {d.get('parent')!r} " + ("not defined before this delegation" if p is None else
                                                 "digest matches" if d.get("parent_sha256") == cap_sha256(p) else "digest does not match the parent capability"))
            caps[did], handed[did] = d, 0.0
            holders.setdefault(d.get("holder"), []).append(did)
            if p is None:
                depth[did] = max_depth + 1
                continue
            pid = p["id"]
            depth[did] = depth[pid] + 1
            handed[pid] += float(d["budget"])
            c(f"{k}.issuer", d.get("issued_by") == p.get("holder") and _agent(d.get("holder")) and d.get("holder") != p.get("holder"),
              f"issued by {d.get('issued_by')!r} (parent holder {p.get('holder')!r}) to {d.get('holder')!r}")
            extra = sorted(set(d["scope"]) - set(p["scope"]))
            c(f"{k}.scope_narrowed", not extra, f"operations beyond the parent: {extra}" if extra else f"{len(d['scope'])} of the parent's {len(p['scope'])} operations")
            wide = sorted(r for r in d["resources"] if not _covers(p["resources"], r))
            c(f"{k}.resources_narrowed", not wide, f"resources beyond the parent: {wide}" if wide else "every resource is covered by the parent")
            c(f"{k}.lifetime", p["issued_at"] <= d["issued_at"] < d["expires_at"] <= p["expires_at"],
              f"child {d['issued_at']}..{d['expires_at']}, parent {p['issued_at']}..{p['expires_at']}")
            c(f"{k}.tenant", d["tenant"] == p["tenant"], f"child tenant {d['tenant']!r}, parent tenant {p['tenant']!r}")
            c(f"{k}.depth", depth[did] <= max_depth, f"depth {depth[did]}, limit {max_depth}")
        for h in sorted(x for x in holders if isinstance(x, str)):
            if len(holders[h]) > 1:
                c(f"holder.{h}.single_grant", False, f"{h} holds {len(holders[h])} capabilities {sorted(holders[h])}; grants cannot be merged")
        spent = {cid: 0.0 for cid in caps}
        for a in acts:
            if not isinstance(a, dict) or not isinstance(a.get("id"), str):
                raise Bad("an action needs an id")
            k = f"action.{a['id']}"
            cap = caps.get(a.get("capability"))
            cost = _num(a.get("cost", 0.0), f"{a['id']}.cost")
            at = _num(a.get("at"), f"{a['id']}.at")
            ok = cap is not None and a.get("agent") == cap.get("holder") and a.get("op") in cap["scope"] \
                and isinstance(a.get("resource"), str) and _covers(cap["resources"], a["resource"]) and cap["issued_at"] <= at <= cap["expires_at"]
            c(f"{k}.authorised", ok, f"{a.get('agent')!r} did {a.get('op')!r} on {a.get('resource')!r} at {at} under {a.get('capability')!r}")
            if cap is not None:
                spent[cap["id"]] += cost
        for cid in sorted(caps):
            used = round(handed[cid] + spent[cid], 6)
            c(f"budget.{cid}", used <= float(caps[cid]["budget"]) + 1e-9,
              f"handed down {round(handed[cid], 6)} + spent {round(spent[cid], 6)} = {used} of {float(caps[cid]['budget'])}")

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

        computed = {"root_issued_by_human": all_ok(lambda i: i.startswith("root.")),
                    "every_handoff_narrows": all_ok(lambda i: i.startswith("edge.")),
                    "budgets_conserved": all_ok(lambda i: i.startswith("budget.")),
                    "one_authority_path_per_agent": all_ok(lambda i: i.startswith("holder.")),
                    "actions_inside_authority": all_ok(lambda i: i.startswith("action."))}
        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, "capabilities": len(caps), "agents": len([h for h in holders if isinstance(h, str)]),
                        "max_depth_seen": max(depth.values()), "actions": len(acts),
                        "budget_handed_down": round(sum(handed.values()), 6), "budget_spent": round(sum(spent.values()), 6)})
    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.swarmdelegation.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-006, {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))
