"""CAIN-A75-061 offline verifier (rules embedded verbatim). CAIN-A75-061 domain-model authority rules. Standard library only, no CAIN imports: embedded verbatim in the offline verifier.

A domain model (for example a CRM-specialised reasoning model) is still a model. Specialisation can improve the answer while
leaving the authority, data-access and action-boundary questions where they were. The model proposes; authority decides. The
review recomputes every decision in a CRM agent log:

  model        the model is pinned by id and version, and every proposal names exactly that model and version
  proposer     no decision is made by the model, and no decision lists the model, its id or its confidence as a basis;
               the basis may only cite tenant, role, record_sensitivity, delegation, action_consequence and approval
  binding      each decision commits the exact action it authorises by SHA-256 (not the proposal text)
  authority    recomputed here: the user, the agent and the record share a tenant; the user's role permits the action kind
               on a record of that sensitivity; the agent holds an unexpired delegation from that user for that kind;
               a consequential action (send_email, export, delete, change_owner, a discount above the role's limit, or
               any unknown kind) also needs approval by a named human other than the requester and the agent, before the
               decision. Expected decision: DENY if not permitted, REQUIRE_APPROVAL if consequential and unapproved, else ALLOW
  outcome      the stated decision equals the expected one, and an action executed only on ALLOW
  claims       every boolean the log asserts matches what this review computed

Verdict: SOUND, else UNSOUND with every failing check named. Malformed input is UNSOUND. It reviews the decision log; it does
not run the model, judge the quality of a proposal, or read the CRM.
"""
from __future__ import annotations

import hashlib
import json
import math
import re

_ID = re.compile(r"^[A-Za-z0-9_.:\-/@]{1,120}$")
SENSITIVITY = ("public", "internal", "confidential", "restricted")
KNOWN_KINDS = ("read", "update_field", "log_call", "send_email", "export", "delete", "change_owner", "discount")
ALWAYS_CONSEQUENTIAL = ("send_email", "export", "delete", "change_owner")
BASIS = ("tenant", "role", "record_sensitivity", "delegation", "action_consequence", "approval")


class Bad(ValueError):
    pass


def action_hash(action):
    return hashlib.sha256(json.dumps(action, 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 _id(v, what):
    if not isinstance(v, str) or not _ID.match(v):
        raise Bad(f"{what} must be an id")
    return v


def consequential(action, role):
    kind = action.get("kind")
    if kind not in KNOWN_KINDS or kind in ALWAYS_CONSEQUENTIAL:
        return True
    if kind == "discount":
        pct = action.get("percent")
        return not isinstance(pct, (int, float)) or isinstance(pct, bool) or pct > float(role.get("discount_limit_pct", 0))
    return False


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

    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.domainmodel.review.v1":
            raise Bad("not a cain42.a75.domainmodel.review.v1 record")
        model = record.get("model") if isinstance(record.get("model"), dict) else {}
        mid, mver = model.get("id"), model.get("version")
        c("model.pinned", isinstance(mid, str) and bool(_ID.match(mid)) and isinstance(mver, str) and bool(mver),
          f"model {mid!r} version {mver!r}")

        roles = record.get("roles")
        if not isinstance(roles, dict) or not roles:
            raise Bad("roles must be a non-empty object")
        for rn, r in roles.items():
            if not isinstance(r, dict) or not isinstance(r.get("actions"), list) or r.get("max_sensitivity") not in SENSITIVITY:
                raise Bad(f"role {rn} needs actions and a max_sensitivity in {list(SENSITIVITY)}")
        users = {}
        for u in record.get("users") or []:
            if not isinstance(u, dict):
                raise Bad("a user must be an object")
            users[_id(u.get("id"), "user.id")] = u
        crm = {}
        for x in record.get("records") or []:
            if not isinstance(x, dict) or x.get("sensitivity") not in SENSITIVITY:
                raise Bad("a CRM record needs an id, tenant and sensitivity")
            crm[_id(x.get("id"), "record.id")] = x
        agents = {}
        for a in record.get("agents") or []:
            if not isinstance(a, dict):
                raise Bad("an agent must be an object")
            agents[_id(a.get("id"), "agent.id")] = a
        dels = [d for d in (record.get("delegations") or []) if isinstance(d, dict)]
        if not users or not crm or not agents:
            raise Bad("users, records and agents must be non-empty")

        decisions = record.get("decisions")
        if not isinstance(decisions, list) or not decisions:
            raise Bad("decisions must be a non-empty list")
        seen = set()
        for d in decisions:
            if not isinstance(d, dict):
                raise Bad("a decision must be an object")
            did = _id(d.get("id"), "decision.id")
            if did in seen:
                raise Bad(f"duplicate decision {did}")
            seen.add(did)
            at = _num(d.get("at"), f"{did}.at")
            action = d.get("action")
            if not isinstance(action, dict):
                raise Bad(f"{did}.action must be an object")
            user, agent, rec = users.get(d.get("user")), agents.get(d.get("agent")), crm.get(d.get("record_id"))
            prop = d.get("proposal") if isinstance(d.get("proposal"), dict) else {}
            auth = d.get("authority") if isinstance(d.get("authority"), dict) else {}

            c(f"{did}.known", user is not None and agent is not None and rec is not None,
              f"user {d.get('user')!r}, agent {d.get('agent')!r}, record {d.get('record_id')!r} are registered")
            c(f"{did}.proposal_model", prop.get("model_id") == mid and prop.get("model_version") == mver,
              f"proposed by {prop.get('model_id')!r} {prop.get('model_version')!r}")
            by = auth.get("by")
            c(f"{did}.not_decided_by_model", isinstance(by, str) and by.startswith(("policy:", "human:")) and by != mid
              and by not in agents, f"decided by {by!r}")
            basis = auth.get("basis")
            bad_basis = [b for b in (basis if isinstance(basis, list) else [basis]) if b not in BASIS]
            c(f"{did}.basis", isinstance(basis, list) and bool(basis) and not bad_basis,
              f"basis cites {bad_basis}, which the model or its confidence must never be" if bad_basis else f"basis {basis}")
            ah = action_hash(action)
            c(f"{did}.bound_to_action", auth.get("action_sha256") == ah, f"decision commits the action {ah[:12]}")
            if user is None or agent is None or rec is None:
                continue

            role = roles.get(user.get("role"), {"actions": [], "max_sensitivity": "public"})
            kind = action.get("kind")
            tenant_ok = user.get("tenant") == rec.get("tenant") == agent.get("tenant")
            role_ok = kind in role["actions"]
            sens_ok = SENSITIVITY.index(rec["sensitivity"]) <= SENSITIVITY.index(role["max_sensitivity"])
            deleg_ok = any(x.get("agent") == agent["id"] and x.get("user") == user["id"] and kind in (x.get("actions") or [])
                           and isinstance(x.get("expires_at"), (int, float)) and at < x["expires_at"] for x in dels)
            cons = consequential(action, role)
            ap = d.get("approval") if isinstance(d.get("approval"), dict) else None
            ap_ok = bool(ap) and isinstance(ap.get("by"), str) and ap["by"].startswith("human:") and len(ap["by"]) > 6 \
                and ap["by"] not in (user["id"], agent["id"]) and isinstance(ap.get("at"), (int, float)) \
                and not isinstance(ap.get("at"), bool) and ap["at"] <= at
            permitted = tenant_ok and role_ok and sens_ok and deleg_ok
            expected = "DENY" if not permitted else ("REQUIRE_APPROVAL" if cons and not ap_ok else "ALLOW")
            why = [n for n, ok in (("tenant", tenant_ok), ("role", role_ok), ("record_sensitivity", sens_ok),
                                    ("delegation", deleg_ok)) if not ok]
            c(f"{did}.decision", auth.get("decision") == expected,
              f"stated {auth.get('decision')!r}, recomputed {expected!r}" + (f" (fails {why})" if why else "")
              + (" (consequential, " + ("approved" if ap_ok else "no valid approval") + ")" if cons and permitted else ""))
            c(f"{did}.executed", d.get("executed") is (expected == "ALLOW" and auth.get("decision") == "ALLOW"),
              f"executed {d.get('executed')!r} on {auth.get('decision')!r}")
            if ap is not None and expected != "DENY":
                c(f"{did}.approval", ap_ok, f"approval by {ap.get('by')!r} at {ap.get('at')!r}")
            summary["decisions"].append({"id": did, "kind": kind, "expected": expected, "consequential": cons,
                                         "model_confidence": prop.get("confidence")})

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

        computed = {"model_version_recorded": all_ok(lambda i: i == "model.pinned" or i.endswith(".proposal_model")),
                    "model_proposes_only": all_ok(lambda i: i.endswith((".not_decided_by_model", ".basis"))),
                    "decisions_bound_to_action": all_ok(lambda i: i.endswith(".bound_to_action")),
                    "authority_recomputed": all_ok(lambda i: i.endswith((".decision", ".executed", ".known"))),
                    "consequential_approved": all_ok(lambda i: i.endswith((".approval", ".decision", ".executed")))}
        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["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.domainmodel.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-061, {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))
