"""CAIN-A75-063 offline verifier (rules embedded verbatim). CAIN-A75-063 chat approval rules. Standard library only, no CAIN imports: embedded verbatim in the offline verifier.

Approving an agent's request inside a collaboration tool is convenient and easy to spoof. The approver must see the exact
action, target and consequence, and the approval must be bound to that action rather than to a message thread. A chat
message can carry the request; the approval record is separate, bound and single-use. The review recomputes the log:

  request      each request renders the exact action: the rendered digest equals SHA-256 of the canonical action, the
               rendered target equals the action target, and a consequence is stated; it has an expiry after it was posted
  approval     a structured approval record (never a free-text chat reply) names the request and carries that request's
               action digest; it is given after the request was posted and before it expired
  approver     the approver is registered, the chat account that clicked maps to that approver's registered chat identity
               (a display name is not identity), is neither the agent that posted nor the human who asked, and holds
               authority for the action kind, the target prefix and the amount
  single use   every approval nonce is unique and every approval is consumed by at most one execution
  execution    every execution names an approval for the same request, carries the approved digest exactly (a changed
               parameter is a different action), and runs after the approval and before the request expired
  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 approval log; it does
not connect to a chat platform or prove that the people are who the registry says.
"""
from __future__ import annotations

import hashlib
import json
import math
import re

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


class Bad(ValueError):
    pass


def action_digest(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 _list(record, key):
    v = record.get(key)
    if not isinstance(v, list) or not all(isinstance(x, dict) for x in v):
        raise Bad(f"{key} must be a list of objects")
    return 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.chatapproval.review.v1":
            raise Bad("not a cain42.a75.chatapproval.review.v1 record")
        A = {}
        for a in _list(record, "approvers"):
            A[_id(a.get("id"), "approver.id")] = a
        R = {}
        for q in _list(record, "requests"):
            qid = _id(q.get("id"), "request.id")
            if qid in R:
                raise Bad(f"duplicate request {qid}")
            R[qid] = q
            act = q.get("action")
            if not isinstance(act, dict):
                raise Bad(f"{qid}.action must be an object")
            at, exp = _num(q.get("at"), f"{qid}.at"), _num(q.get("expires_at"), f"{qid}.expires_at")
            rend = q.get("rendered") if isinstance(q.get("rendered"), dict) else {}
            d = action_digest(act)
            c(f"request.{qid}.rendered_digest", rend.get("action_sha256") == d, f"shown digest matches the action {d[:12]}")
            c(f"request.{qid}.rendered_target", rend.get("target") == act.get("target"), f"shown target {rend.get('target')!r}, action {act.get('target')!r}")
            c(f"request.{qid}.consequence", isinstance(rend.get("consequence"), str) and len(rend["consequence"].strip()) >= 8,
              "consequence stated to the approver")
            c(f"request.{qid}.expiry", exp > at, f"expires {exp:g} after posting {at:g}")
        if not R:
            raise Bad("requests must be non-empty")

        P, nonces = {}, {}
        for p in _list(record, "approvals"):
            pid = _id(p.get("id"), "approval.id")
            if pid in P:
                raise Bad(f"duplicate approval {pid}")
            P[pid] = p
            nonces[p.get("nonce")] = nonces.get(p.get("nonce"), 0) + 1
            q = R.get(p.get("request_id"))
            c(f"approval.{pid}.request", q is not None, f"for request {p.get('request_id')!r}")
            c(f"approval.{pid}.structured", p.get("via") in STRUCTURED, f"via {p.get('via')!r} (a chat reply is not an approval record)")
            if q is None:
                continue
            act, at = q["action"], _num(p.get("at"), f"{pid}.at")
            c(f"approval.{pid}.digest", p.get("action_sha256") == action_digest(act), "approval bound to the action digest")
            c(f"approval.{pid}.window", float(q["at"]) <= at < float(q["expires_at"]), f"approved at {at:g} inside {q['at']:g}..{q['expires_at']:g}")
            ap = A.get(p.get("approver"))
            c(f"approval.{pid}.registered", ap is not None, f"approver {p.get('approver')!r} registered")
            if ap is None:
                continue
            chat = ap.get("chat_identity") if isinstance(ap.get("chat_identity"), dict) else {}
            c(f"approval.{pid}.chat_identity", p.get("chat_user_id") == chat.get("user_id") and p.get("platform") == chat.get("platform")
              and isinstance(chat.get("user_id"), str), f"clicked by {p.get('platform')!r}/{p.get('chat_user_id')!r}, registered "
                                                       f"{chat.get('platform')!r}/{chat.get('user_id')!r}")
            c(f"approval.{pid}.independent", ap["id"] not in (q.get("posted_by"), q.get("requested_by")) and ap["id"].startswith("human:"),
              f"approver {ap['id']!r}, posted by {q.get('posted_by')!r}, asked by {q.get('requested_by')!r}")
            auth = ap.get("authority") if isinstance(ap.get("authority"), dict) else {}
            amt = act.get("amount", 0)
            amt_ok = isinstance(amt, (int, float)) and not isinstance(amt, bool) and math.isfinite(amt) and 0 <= amt <= float(auth.get("max_amount", -1))
            tgt = act.get("target")
            c(f"approval.{pid}.authority", act.get("kind") in (auth.get("actions") or []) and amt_ok and isinstance(tgt, str)
              and any(tgt.startswith(pre) for pre in (auth.get("targets") or []) if isinstance(pre, str)),
              f"{ap['id']} may approve {auth.get('actions')} on {auth.get('targets')} up to {auth.get('max_amount')}; "
              f"asked {act.get('kind')!r} on {tgt!r} for {amt!r}")
        dupn = sorted(str(k) for k, v in nonces.items() if v > 1 or not isinstance(k, str) or not k)
        c("approvals.nonces_unique", not dupn, f"reused or missing nonces {dupn}" if dupn else "every nonce used once")

        used, n_exec = {}, 0
        for k, x in enumerate(_list(record, "executions"), start=1):
            n_exec += 1
            q, p = R.get(x.get("request_id")), P.get(x.get("approval_id"))
            xid = f"execution.{k}"
            used[x.get("approval_id")] = used.get(x.get("approval_id"), 0) + 1
            c(f"{xid}.approved", q is not None and p is not None and p.get("request_id") == x.get("request_id"),
              f"request {x.get('request_id')!r} executed on approval {x.get('approval_id')!r}")
            if q is None or p is None:
                continue
            c(f"{xid}.digest", x.get("action_sha256") == action_digest(q["action"]) == p.get("action_sha256"),
              "executed exactly the approved action")
            at = _num(x.get("at"), f"{xid}.at")
            c(f"{xid}.window", isinstance(p.get("at"), (int, float)) and float(p["at"]) <= at < float(q["expires_at"]),
              f"executed at {at:g}, approved {p.get('at')!r}, expires {q['expires_at']:g}")
        reused = sorted(str(k) for k, v in used.items() if v > 1)
        c("approvals.single_use", not reused, f"approvals consumed more than once {reused}" if reused else "every approval consumed at most once")

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

        computed = {"exact_action_rendered": all_ok(lambda i: i.startswith("request.")),
                    "approval_bound_to_digest": all_ok(lambda i: i.endswith((".digest", ".structured", ".window", ".request"))),
                    "approver_verified": all_ok(lambda i: i.endswith((".registered", ".chat_identity", ".independent", ".authority"))),
                    "single_use": all_ok(lambda i: i.startswith("approvals.")),
                    "executed_only_approved": all_ok(lambda i: i.startswith("execution."))}
        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, "requests": len(R), "approvals": len(P), "executions": n_exec})
    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.chatapproval.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-063, {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))
