"""CAIN-A75-052 offline verifier (rules embedded verbatim). CAIN-A75-052 agent-to-agent deal rules. Standard library only, no CAIN imports: embedded verbatim in the offline verifier.

A buyer agent and a seller agent negotiated and settled a deal. The package claims both principals authorised it. The
review recomputes it:

  mandates     each side has a mandate from a named human principal for one agent, issued before negotiation began, with a
               price bound (buyer ceiling, seller floor), a quantity cap, an item and the counterparties it may deal with
  negotiation  every message comes from one of the two agents, in increasing sequence and time, and is hash-chained to the
               previous message (SHA-256 of its canonical form); no message carries an off-book term (side payment,
               rebate, private channel)
  deal         the deal equals the offer that was accepted: the named offer's price and quantity, accepted afterwards by the
               other agent
  authority    the deal is inside BOTH mandates: item, unit price, quantity, counterparty, and before both expiries. Two
               agents agreeing never widens either mandate
  collusion    the principals differ, the agents differ, and (if the policy forbids it) the agents do not share an operator
  settlement   if settled, the amount equals unit price x quantity, after agreement and before either mandate expired, and
               only when every check above holds
  claims       every boolean the package asserts matches what this review computed

Verdict: SOUND, else UNSOUND with every failing check named. Malformed input is UNSOUND.
It reviews the deal record; it does not run a marketplace, move money, or judge whether the price was fair.
"""
from __future__ import annotations

import hashlib
import json
import math
import re

_ID = re.compile(r"^[A-Za-z0-9_.:\-/]{1,120}$")
OFF_BOOK = ("side_payment", "rebate", "private_channel", "kickback", "off_book")


class Bad(ValueError):
    pass


def msg_hash(m):
    return hashlib.sha256(json.dumps(m, 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 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.a2adeal.review.v1":
            raise Bad("not a cain42.a75.a2adeal.review.v1 record")
        pol = record.get("policy") if isinstance(record.get("policy"), dict) else {}
        mands = record.get("mandates")
        if not isinstance(mands, dict) or not isinstance(mands.get("buy"), dict) or not isinstance(mands.get("sell"), dict):
            raise Bad("mandates.buy and mandates.sell must be objects")
        B, S = mands["buy"], mands["sell"]
        msgs = record.get("negotiation")
        if not isinstance(msgs, list) or len(msgs) < 2:
            raise Bad("negotiation must list at least two messages")
        first_at = _num(msgs[0].get("at") if isinstance(msgs[0], dict) else None, "negotiation[0].at")
        for side, m in (("buy", B), ("sell", S)):
            _id(m.get("id"), f"{side}.id"); _id(m.get("agent"), f"{side}.agent")
            c(f"mandate.{side}.principal", isinstance(m.get("principal"), str) and m["principal"].startswith("human:"),
              f"principal {m.get('principal')!r}")
            c(f"mandate.{side}.before_negotiation", _num(m.get("issued_at"), f"{side}.issued_at") <= first_at,
              "issued before the first message")
            c(f"mandate.{side}.window", _num(m.get("issued_at"), f"{side}.issued_at") < _num(m.get("expires_at"), f"{side}.expires_at"),
              "non-empty validity window")
            _num(m.get("max_quantity"), f"{side}.max_quantity", 0.0)
        _num(B.get("max_unit_price"), "buy.max_unit_price"); _num(S.get("min_unit_price"), "sell.min_unit_price")
        agents = {B["agent"]: "buy", S["agent"]: "sell"}

        # ---- negotiation chain
        prev, last_seq, last_at, offers, offbook = None, -1, -1.0, {}, []
        for i, m in enumerate(msgs):
            if not isinstance(m, dict):
                raise Bad("a message must be an object")
            seq = int(_num(m.get("seq"), f"negotiation[{i}].seq", 0, 1e9))
            at = _num(m.get("at"), f"negotiation[{i}].at")
            c(f"negotiation.{seq}.party", m.get("from") in agents, f"from {m.get('from')!r}")
            c(f"negotiation.{seq}.order", seq > last_seq and at >= last_at, "sequence and time increase")
            body = {k: v for k, v in m.items() if k != "prev_sha256"}
            if prev is None:
                c(f"negotiation.{seq}.chain", m.get("prev_sha256") in (None, ""), "first message has no predecessor")
            else:
                c(f"negotiation.{seq}.chain", m.get("prev_sha256") == msg_hash(prev), "bound to the previous message's hash")
            terms = m.get("offer") if isinstance(m.get("offer"), dict) else {}
            bad_terms = sorted(k for k in list(m) + list(terms) if k in OFF_BOOK)
            if bad_terms:
                offbook.append(seq)
            c(f"negotiation.{seq}.on_book", not bad_terms, f"off-book terms {bad_terms}" if bad_terms else "no off-book terms")
            if m.get("type") == "offer":
                offers[seq] = {"from": m.get("from"), "at": at, "unit_price": _num(terms.get("unit_price"), f"offer {seq}.unit_price"),
                               "quantity": _num(terms.get("quantity"), f"offer {seq}.quantity", 0.0), "item": terms.get("item")}
            prev, last_seq, last_at = m, seq, at
            _ = body

        # ---- deal equals the accepted offer
        deal = record.get("deal")
        if not isinstance(deal, dict):
            raise Bad("deal must be an object")
        price, qty = _num(deal.get("unit_price"), "deal.unit_price"), _num(deal.get("quantity"), "deal.quantity", 0.0)
        agreed_at = _num(deal.get("agreed_at"), "deal.agreed_at")
        off = offers.get(deal.get("offer_seq"))
        c("deal.offer_exists", off is not None, f"offer {deal.get('offer_seq')!r}")
        if off is not None:
            c("deal.matches_offer", off["unit_price"] == price and off["quantity"] == qty and off["item"] == deal.get("item"),
              f"deal {price} x {qty} vs offer {off['unit_price']} x {off['quantity']}")
            acc = [m for m in msgs if isinstance(m, dict) and m.get("type") == "accept" and m.get("offer_seq") == deal.get("offer_seq")
                   and m.get("from") in agents and m.get("from") != off["from"] and m.get("at", -1) >= off["at"]]
            c("deal.accepted_by_other_side", bool(acc), "accepted by the counterparty after the offer")
            c("deal.agreed_time", bool(acc) and abs(agreed_at - acc[0]["at"]) <= 1e-9, "agreed_at equals the acceptance time")
        c("deal.parties", deal.get("buyer_agent") == B["agent"] and deal.get("seller_agent") == S["agent"], "deal names the mandated agents")

        # ---- authority under both mandates
        c("authority.buy.item", deal.get("item") == B.get("item"), f"item {deal.get('item')!r} vs buyer {B.get('item')!r}")
        c("authority.sell.item", deal.get("item") == S.get("item"), f"item {deal.get('item')!r} vs seller {S.get('item')!r}")
        c("authority.buy.price", price <= B["max_unit_price"] + 1e-9, f"{price} <= buyer ceiling {B['max_unit_price']}")
        c("authority.sell.price", price >= S["min_unit_price"] - 1e-9, f"{price} >= seller floor {S['min_unit_price']}")
        c("authority.buy.quantity", qty <= _num(B.get("max_quantity"), "buy.max_quantity") + 1e-9, f"{qty} <= buyer cap {B.get('max_quantity')}")
        c("authority.sell.quantity", qty <= _num(S.get("max_quantity"), "sell.max_quantity") + 1e-9, f"{qty} <= seller cap {S.get('max_quantity')}")
        c("authority.buy.counterparty", S.get("principal") in (B.get("counterparties") or []), f"buyer may deal with {S.get('principal')!r}")
        c("authority.sell.counterparty", B.get("principal") in (S.get("counterparties") or []), f"seller may deal with {B.get('principal')!r}")
        c("authority.buy.expiry", agreed_at < B["expires_at"], "agreed before the buyer mandate expired")
        c("authority.sell.expiry", agreed_at < S["expires_at"], "agreed before the seller mandate expired")

        # ---- collusion and self-dealing
        c("collusion.principals", B.get("principal") != S.get("principal"), "buyer and seller principals differ")
        c("collusion.agents", B["agent"] != S["agent"], "buyer and seller agents differ")
        ops = {g.get("agent"): g.get("operator") for g in (record.get("agent_graph") or []) if isinstance(g, dict)}
        if pol.get("forbid_shared_operator"):
            c("collusion.operator", B["agent"] in ops and S["agent"] in ops and ops[B["agent"]] != ops[S["agent"]],
              f"operators {ops.get(B['agent'])!r} / {ops.get(S['agent'])!r}")

        pre_settle_ok = all(x["ok"] for x in checks)
        st = record.get("settlement") if isinstance(record.get("settlement"), dict) else {}
        if st.get("settled"):
            amt = _num(st.get("amount"), "settlement.amount")
            s_at = _num(st.get("at"), "settlement.at")
            c("settlement.amount", abs(amt - price * qty) <= 0.005, f"{amt} == {price} x {qty}")
            c("settlement.timing", agreed_at <= s_at < min(B["expires_at"], S["expires_at"]), "after agreement, before expiry")
            c("settlement.authorized", pre_settle_ok, "settled only when every authority check holds")
        summary.update(deal_value=round(price * qty, 2), offers=len(offers), off_book_messages=offbook,
                       settled=bool(st.get("settled")))

        claims = record.get("claims") if isinstance(record.get("claims"), dict) else {}

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

        computed = {"mandates_recorded_first": all_ok("mandate."), "negotiation_chained": all_ok("negotiation."),
                    "deal_is_accepted_offer": all_ok("deal."), "within_both_mandates": all_ok("authority."),
                    "no_collusion": all_ok("collusion.") and not offbook,
                    "settled_within_authority": bool(st.get("settled")) and all_ok("settlement.")}
        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.a2adeal.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-052, {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))
