"""Read-only order book and a refund gateway that does not trust the model."""

from __future__ import annotations

ORDERS = {
    "1042": {
        "id": "1042",
        "state": "shipped",
        "carrier": "Parcel North",
        "total_cents": 4200,
        "email": "ada@example.com",
    },
    "1043": {
        "id": "1043",
        "state": "paid",
        "carrier": None,
        "total_cents": 1500,
        "email": "lin@example.com",
    },
    "1044": {
        "id": "1044",
        "state": "cancelled",
        "carrier": None,
        "total_cents": 8000,
        "email": "sam@example.com",
    },
}

# Irreversible writes require this ceiling AND an explicit confirm flag set by
# server code, never by copying a bit out of the user message.
REFUND_CEILING_CENTS = 5000


def lookup_order(arguments: dict) -> dict:
    order_id = str(arguments.get("order_id", "")).strip()
    order = ORDERS.get(order_id)
    if not order:
        return {"error": "not_found", "order_id": order_id}
    # The model may see the email because the shopper asked about their order.
    # Traces must not. Callers redact before logging.
    return dict(order)


def refund_order(arguments: dict, *, confirmed: bool, ledger: list) -> dict:
    """Commit a refund only if server-side rules pass.

    `confirmed` must be decided by your UI or policy worker. If you set it by
    scanning the user string for "yes", a prompt injection can confirm itself.
    """
    if not confirmed:
        return {"error": "not_confirmed"}
    order_id = str(arguments.get("order_id", "")).strip()
    order = ORDERS.get(order_id)
    if not order:
        return {"error": "not_found", "order_id": order_id}
    if order["state"] not in {"paid", "shipped"}:
        return {"error": "state_blocked", "state": order["state"]}
    try:
        amount = int(arguments.get("amount_cents"))
    except (TypeError, ValueError):
        return {"error": "amount_invalid"}
    if amount <= 0 or amount > order["total_cents"] or amount > REFUND_CEILING_CENTS:
        return {"error": "amount_blocked", "amount_cents": amount}
    # Idempotency: one committed refund per key.
    key = arguments.get("idempotency_key")
    if not key:
        return {"error": "idempotency_key_required"}
    for prior in ledger:
        if prior["idempotency_key"] == key:
            return {"status": "already_committed", "refund": prior}
    row = {
        "order_id": order_id,
        "amount_cents": amount,
        "idempotency_key": key,
    }
    ledger.append(row)
    return {"status": "committed", "refund": row}
