"""CAIN-A75-069 offline verifier (rules embedded verbatim). CAIN-A75-069 agent interoperability authority rules. Standard library only, no CAIN imports: embedded verbatim in the offline
verifier.

Interoperability standards define message shape, not authority. Two compliant agents can still agree to a transaction neither
principal authorised. Keep authority outside the message standard: a mandate and a settlement check on each side, independent
of the protocol's fields. The review recomputes every transaction:

  protocol     every message uses a supported protocol version, all messages of a transaction use the same one, and the
               transaction records it
  principals   every message's agent is registered to a principal; buyer and seller principals differ
  agreement    the accepted message is an offer or counter from one side; the accept comes later from an agent of the other
               side and names it; the settlement terms (price, quantity, item class) equal the accepted message's terms
  authority    the transaction settles only when the buyer principal's mandate (item class, unit price ceiling, quantity
               ceiling, total budget, allowed counterparties, expiry) AND the seller principal's mandate (item class, unit price
               floor, allowed counterparties, expiry) both allow it; any authority, mandate or approval field carried inside a
               protocol message is ignored. The stated decision must equal the recomputed one
  record       the authority decision is recorded next to the protocol version and equals the stated decision
  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 interop record; it
does not implement or certify any protocol.
"""
from __future__ import annotations

import math
import re

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


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 buyer_ok(m, s, seller, at):
    why = []
    if s.get("item_class") not in (m.get("item_classes") or []):
        why.append("item class")
    if s["price"] > float(m.get("max_unit_price", -1)):
        why.append("unit price above the buyer's ceiling")
    if s["qty"] > float(m.get("max_qty", -1)):
        why.append("quantity above the buyer's ceiling")
    if s["price"] * s["qty"] > float(m.get("budget", -1)) + 1e-9:
        why.append("total above the buyer's budget")
    if seller not in (m.get("counterparties") or []):
        why.append("seller not an allowed counterparty")
    if at >= float(m.get("expires_at", -1)):
        why.append("buyer mandate expired")
    return why


def seller_ok(m, s, buyer, at):
    why = []
    if s.get("item_class") not in (m.get("item_classes") or []):
        why.append("item class")
    if s["price"] < float(m.get("min_unit_price", math.inf)):
        why.append("unit price below the seller's floor")
    if buyer not in (m.get("counterparties") or []):
        why.append("buyer not an allowed counterparty")
    if at >= float(m.get("expires_at", -1)):
        why.append("seller mandate expired")
    return why


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.interop.review.v1":
            raise Bad("not a cain42.a75.interop.review.v1 record")
        supported = record.get("supported_versions")
        agents = record.get("agents")
        mandates = record.get("mandates")
        if not isinstance(supported, list) or not supported or not isinstance(agents, dict) or not isinstance(mandates, dict):
            raise Bad("supported_versions, agents and mandates are required")
        M = {}
        for m in record.get("messages") or []:
            if not isinstance(m, dict) or not isinstance(m.get("id"), str):
                raise Bad("a message needs an id")
            if m["id"] in M:
                raise Bad(f"duplicate message {m['id']}")
            M[m["id"]] = m
        txs = record.get("transactions")
        if not isinstance(txs, list) or not txs or not all(isinstance(t, dict) for t in txs):
            raise Bad("transactions must be a non-empty list of objects")
        n_settle = n_refuse = 0
        for t in txs:
            tid = t.get("id") if isinstance(t.get("id"), str) and _ID.match(t["id"]) else None
            if tid is None:
                raise Bad("a transaction needs an id")
            om, am = M.get(t.get("accepted_message")), M.get(t.get("accept_message"))
            if om is None or am is None:
                c(f"tx.{tid}.messages", False, "accepted and accept messages must exist")
                continue
            vs = {om.get("protocol_version"), am.get("protocol_version")}
            c(f"tx.{tid}.protocol", len(vs) == 1 and om.get("protocol_version") in supported
              and (t.get("recorded") or {}).get("protocol_version") == om.get("protocol_version"),
              f"versions {sorted(map(str, vs))}, supported {supported}, recorded {(t.get('recorded') or {}).get('protocol_version')!r}")
            p_from, p_acc = agents.get(om.get("from_agent")), agents.get(am.get("from_agent"))
            buyer, seller = t.get("buyer_principal"), t.get("seller_principal")
            c(f"tx.{tid}.principals", p_from is not None and p_acc is not None and {p_from, p_acc} == {buyer, seller} and buyer != seller,
              f"offer by {om.get('from_agent')!r} ({p_from!r}), accept by {am.get('from_agent')!r} ({p_acc!r}); buyer {buyer!r}, seller {seller!r}")
            at_o, at_a = _num(om.get("at"), f"{tid}.offer.at"), _num(am.get("at"), f"{tid}.accept.at")
            c(f"tx.{tid}.agreement", om.get("type") in ("offer", "counter") and am.get("type") == "accept"
              and am.get("in_reply_to") == om["id"] and at_a > at_o and p_from != p_acc,
              f"{om.get('type')!r} at {at_o:g} accepted by {am.get('type')!r} at {at_a:g} replying to {am.get('in_reply_to')!r}")
            st = t.get("settlement") if isinstance(t.get("settlement"), dict) else {}
            f = om.get("fields") if isinstance(om.get("fields"), dict) else {}
            c(f"tx.{tid}.terms", all(st.get(k) == f.get(k) for k in TERMS), f"settlement {[st.get(k) for k in TERMS]} vs accepted {[f.get(k) for k in TERMS]}")
            s = {"price": _num(st.get("price"), f"{tid}.price"), "qty": _num(st.get("qty"), f"{tid}.qty"), "item_class": st.get("item_class")}
            bm, sm = mandates.get(buyer), mandates.get(seller)
            why = ["no buyer mandate"] if not isinstance(bm, dict) else buyer_ok(bm, s, seller, at_a)
            why += ["no seller mandate"] if not isinstance(sm, dict) else seller_ok(sm, s, buyer, at_a)
            exp = "REFUSE" if why else "SETTLE"
            ignored = sorted(k for k in f if k not in TERMS and k not in ("currency", "note"))
            c(f"tx.{tid}.decision", t.get("decision") == exp, f"stated {t.get('decision')!r}, recomputed {exp!r}"
              + (f" ({'; '.join(why)})" if why else "") + (f"; protocol fields ignored for authority: {ignored}" if ignored else ""))
            c(f"tx.{tid}.recorded", (t.get("recorded") or {}).get("authority_decision") == t.get("decision"),
              f"recorded authority decision {(t.get('recorded') or {}).get('authority_decision')!r}")
            n_settle += exp == "SETTLE"
            n_refuse += exp == "REFUSE"

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

        computed = {"protocol_recorded": all_ok(lambda i: i.endswith((".protocol", ".recorded"))),
                    "authority_outside_protocol": all_ok(lambda i: i.endswith(".decision")),
                    "agreement_consistent": all_ok(lambda i: i.endswith((".principals", ".agreement", ".terms", ".messages")))}
        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, "transactions": len(txs), "settle": n_settle, "refuse": n_refuse})
    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.interop.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-069, {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))
