"""将已发生的 Agent 工具调用安全映射为商业用量与内部成本事实。"""

from __future__ import annotations

from dataclasses import asdict, dataclass
from datetime import UTC, datetime
from decimal import Decimal
from typing import Any, Literal

from sqlalchemy import and_, or_, select
from sqlalchemy.orm import Session

from app.models.agent_run import AgentRun, AgentToolCall
from app.models.commercial import CommercialEntitlement, TenantSubscription
from app.models.commercial_runtime import CommercialRuntimeReservation
from app.schemas.commercial import CommercialCostEventCreate, UsageMeterEventCreate
from app.services.commercial_access_policy import (
    CommercialConfigurationError,
    CommercialConflictError,
)
from app.services.commercial_entitlements import CommercialEntitlementService
from app.services.commercial_metering import CommercialMeteringService
from app.services.commercial_runtime_costs import RuntimeCostConfig as _CostConfig
from app.services.commercial_runtime_costs import runtime_cost_config as _cost_config
from app.services.commercial_runtime_policy import (
    runtime_meter_config,
    runtime_meter_matches,
    tenant_from_agent_route,
    tool_call_business_occurred,
    tool_call_metering_state,
)
from app.services.commercial_runtime_values import (
    cost_idempotency_key as _cost_idempotency_key,
)
from app.services.commercial_runtime_values import (
    decimal as _decimal,
)
from app.services.commercial_runtime_values import (
    decode_cursor as _decode_cursor,
)
from app.services.commercial_runtime_values import (
    encode_cursor as _encode_cursor,
)
from app.services.commercial_runtime_values import (
    positive_decimal as _positive_decimal,
)
from app.services.commercial_runtime_values import (
    required as _required,
)
from app.services.commercial_runtime_values import (
    safe_error_reason as _safe_error_reason,
)
from app.services.commercial_runtime_values import (
    usage_idempotency_key as _usage_idempotency_key,
)
from app.services.commercial_runtime_values import (
    utc as _utc,
)

QuantityBasis = Literal[
    "call",
    "bytes",
    "events",
    "input_tokens",
    "objects",
    "output_tokens",
    "pages",
    "total_tokens",
    "duration_ms",
]
SecurityDecision = Literal["allow", "deny", "human_review"]
ResultStatus = Literal["created", "replayed", "skipped", "error"]

SOURCE_SYSTEM = "agent-runtime-metering"
METER_VERSION = "agent-tool-call-v1"
MAX_BATCH_SIZE = 200
SUPPORTED_BASES = {
    "call",
    "bytes",
    "events",
    "input_tokens",
    "objects",
    "output_tokens",
    "pages",
    "total_tokens",
    "duration_ms",
}
INPUT_TOKEN_KEYS = ("input_tokens", "prompt_tokens")
OUTPUT_TOKEN_KEYS = ("output_tokens", "completion_tokens")
TOTAL_TOKEN_KEYS = ("total_tokens",)
TOKEN_CONTAINERS = ("usage", "token_usage", "metrics")
RESOURCE_QUANTITY_KEYS = {
    "bytes": ("bytes", "byte_count", "content_length", "size_bytes"),
    "events": ("events", "event_count"),
    "objects": ("objects", "object_count"),
    "pages": ("pages", "page_count", "processed_pages"),
}


@dataclass(frozen=True)
class RuntimeQuotaPreflight:
    allowed: bool
    reason_code: str
    reason: str
    run_id: str
    tenant_id: str | None
    entitlement_id: str | None
    quantity_basis: str | None
    requested_quantity: Decimal | None
    commercially_allowed: bool
    security_decision: SecurityDecision


@dataclass(frozen=True)
class RuntimeMeteringResult:
    status: ResultStatus
    reason_code: str
    reason: str
    tool_call_id: str
    run_id: str
    tenant_id: str | None
    entitlement_id: str | None = None
    quantity_basis: str | None = None
    quantity: Decimal | None = None
    usage_event_id: str | None = None
    cost_event_id: str | None = None
    usage_created: bool = False
    cost_created: bool = False
    collecting: bool = False
    business_call_occurred: bool = True
    requires_reconciliation: bool = False

    def to_dict(self) -> dict[str, Any]:
        payload = asdict(self)
        if self.quantity is not None:
            payload["quantity"] = str(self.quantity)
        payload.update(
            created=self.status == "created",
            replayed=self.status == "replayed",
            skipped=self.status == "skipped",
            error=self.status == "error",
        )
        return payload


@dataclass(frozen=True)
class RuntimeMeteringBatchResult:
    items: tuple[RuntimeMeteringResult, ...]
    created: int
    replayed: int
    skipped: int
    errors: int
    limit: int
    has_more: bool
    next_cursor: str | None

    def to_dict(self) -> dict[str, Any]:
        return {
            "items": [item.to_dict() for item in self.items],
            "created": self.created,
            "replayed": self.replayed,
            "skipped": self.skipped,
            "errors": self.errors,
            "limit": self.limit,
            "has_more": self.has_more,
            "next_cursor": self.next_cursor,
        }


@dataclass(frozen=True)
class _ResolvedMeter:
    subscription: TenantSubscription
    entitlement: CommercialEntitlement
    quantity_basis: QuantityBasis
    cost: _CostConfig | None


class _SkipMetering(RuntimeError):
    def __init__(self, code: str, reason: str, *, collecting: bool = False) -> None:
        super().__init__(reason)
        self.code = code
        self.reason = reason
        self.collecting = collecting


class CommercialRuntimeMeteringService:
    def __init__(self, db: Session) -> None:
        self.db = db

    def preflight_run_tool(
        self,
        run_id: str,
        *,
        tool_type: str,
        tool_name: str,
        requested_quantity: Decimal | int | None = None,
        security_decision: SecurityDecision = "allow",
        as_of: datetime | None = None,
    ) -> RuntimeQuotaPreflight:
        run = self.db.scalar(select(AgentRun).where(AgentRun.run_id == _required(run_id)))
        if run is None:
            return RuntimeQuotaPreflight(
                allowed=False,
                reason_code="run_not_found",
                reason="Agent 运行记录不存在，不能建立可信租户归属。",
                run_id=str(run_id or ""),
                tenant_id=None,
                entitlement_id=None,
                quantity_basis=None,
                requested_quantity=None,
                commercially_allowed=False,
                security_decision=security_decision,
            )
        tenant_id = tenant_from_agent_route(run.route_json)
        if tenant_id is None:
            return self._preflight_denied(
                run.run_id,
                None,
                "missing_tenant",
                "AgentRun.route_json 未显式提供可信 tenant_id。",
                security_decision,
            )
        when = _utc(as_of or datetime.now(UTC))
        try:
            meter = self._resolve_meter(tenant_id, tool_type, tool_name, when)
            quantity = (
                Decimal("1")
                if requested_quantity is None and meter.quantity_basis == "call"
                else _positive_decimal(requested_quantity, "调用前预留数量")
            )
            gate = CommercialEntitlementService(self.db).check(
                tenant_id,
                entitlement_key=meter.entitlement.entitlement_key,
                requested_quantity=quantity,
                security_decision=security_decision,
                as_of=when,
            )
        except _SkipMetering as error:
            return self._preflight_denied(
                run.run_id,
                tenant_id,
                error.code,
                error.reason,
                security_decision,
            )
        except (CommercialConfigurationError, CommercialConflictError, ValueError) as error:
            return self._preflight_denied(
                run.run_id,
                tenant_id,
                "configuration_error",
                _safe_error_reason(error),
                security_decision,
            )
        return RuntimeQuotaPreflight(
            allowed=gate.final_allowed,
            reason_code="allowed" if gate.final_allowed else "quota_or_security_denied",
            reason=gate.reason,
            run_id=run.run_id,
            tenant_id=tenant_id,
            entitlement_id=meter.entitlement.id,
            quantity_basis=meter.quantity_basis,
            requested_quantity=quantity,
            commercially_allowed=gate.commercial_allowed,
            security_decision=security_decision,
        )

    def assert_run_tool_allowed(self, *args: Any, **kwargs: Any) -> RuntimeQuotaPreflight:
        result = self.preflight_run_tool(*args, **kwargs)
        if not result.allowed:
            raise CommercialConflictError(result.reason)
        return result

    def sync_tool_call(self, tool_call_id: str) -> RuntimeMeteringResult:
        pair = self._tool_call_pair(tool_call_id)
        if pair is None:
            return RuntimeMeteringResult(
                status="error",
                reason_code="tool_call_not_found",
                reason="Agent 工具调用记录不存在。",
                tool_call_id=str(tool_call_id or ""),
                run_id="",
                tenant_id=None,
                business_call_occurred=False,
                requires_reconciliation=False,
            )
        return self._guarded_sync(*pair)

    def sync_reserved_tool_call(
        self,
        tool_call_id: str,
        reservation: CommercialRuntimeReservation,
    ) -> RuntimeMeteringResult:
        pair = self._tool_call_pair(tool_call_id)
        if pair is None:
            return RuntimeMeteringResult(
                status="error",
                reason_code="tool_call_not_found",
                reason="Agent 工具调用记录不存在。",
                tool_call_id=str(tool_call_id or ""),
                run_id="",
                tenant_id=reservation.tenant_id,
                business_call_occurred=False,
                requires_reconciliation=False,
            )
        if reservation.tool_call_id != pair[0].id or reservation.run_id != pair[1].run_id:
            return RuntimeMeteringResult(
                status="error",
                reason_code="reservation_identity_mismatch",
                reason="商业预占与 Agent 工具调用身份不一致。",
                tool_call_id=pair[0].id,
                run_id=pair[1].run_id,
                tenant_id=reservation.tenant_id,
                business_call_occurred=True,
                requires_reconciliation=True,
            )
        return self._guarded_sync(*pair, reservation=reservation)

    def sync_batch(
        self,
        *,
        limit: int = 100,
        cursor: str | None = None,
    ) -> RuntimeMeteringBatchResult:
        """按 created_at + id 稳定游标同步一页，单页硬上限 200。"""

        if (
            not isinstance(limit, int)
            or isinstance(limit, bool)
            or not 1 <= limit <= MAX_BATCH_SIZE
        ):
            raise ValueError(f"运行时计量批次大小必须介于 1 和 {MAX_BATCH_SIZE} 之间。")
        cursor_value = _decode_cursor(cursor) if cursor else None
        statement = (
            select(AgentToolCall, AgentRun)
            .join(AgentRun, AgentRun.run_id == AgentToolCall.run_id)
            .order_by(AgentToolCall.created_at.asc(), AgentToolCall.id.asc())
        )
        if cursor_value is not None:
            created_at, call_id = cursor_value
            statement = statement.where(
                or_(
                    AgentToolCall.created_at > created_at,
                    and_(
                        AgentToolCall.created_at == created_at,
                        AgentToolCall.id > call_id,
                    ),
                )
            )
        rows = list(self.db.execute(statement.limit(limit + 1)).all())
        has_more = len(rows) > limit
        page = rows[:limit]
        items = tuple(self._guarded_sync(tool_call, run) for tool_call, run in page)
        next_cursor = _encode_cursor(page[-1][0].created_at, page[-1][0].id) if page else None
        return RuntimeMeteringBatchResult(
            items=items,
            created=sum(item.status == "created" for item in items),
            replayed=sum(item.status == "replayed" for item in items),
            skipped=sum(item.status == "skipped" for item in items),
            errors=sum(item.status == "error" for item in items),
            limit=limit,
            has_more=has_more,
            next_cursor=next_cursor,
        )

    def _guarded_sync(
        self,
        tool_call: AgentToolCall,
        run: AgentRun,
        *,
        reservation: CommercialRuntimeReservation | None = None,
    ) -> RuntimeMeteringResult:
        tenant_id = tenant_from_agent_route(run.route_json)
        try:
            with self.db.begin_nested():
                return self._sync_pair(tool_call, run, tenant_id, reservation=reservation)
        except Exception as error:  # 错误必须结构化返回，不能把已发生调用伪装为未发生。
            return RuntimeMeteringResult(
                status="error",
                reason_code="metering_failed_after_business_call",
                reason=_safe_error_reason(error),
                tool_call_id=tool_call.id,
                run_id=run.run_id,
                tenant_id=tenant_id,
                business_call_occurred=True,
                requires_reconciliation=True,
            )

    def _sync_pair(
        self,
        tool_call: AgentToolCall,
        run: AgentRun,
        tenant_id: str | None,
        *,
        reservation: CommercialRuntimeReservation | None = None,
    ) -> RuntimeMeteringResult:
        metering_state = tool_call_metering_state(tool_call.status)
        if metering_state != "billable":
            return self._skipped(
                tool_call,
                run,
                tenant_id,
                (
                    "tool_call_not_terminal"
                    if metering_state == "collecting"
                    else "tool_call_not_billable"
                ),
                "工具调用尚未完成，等待终态后再计量。"
                if metering_state == "collecting"
                else "只有成功完成的真实工具调用才进入商业用量与成本账本。",
                collecting=metering_state == "collecting",
                reconcile=metering_state == "collecting",
                business_call_occurred=tool_call_business_occurred(tool_call.status),
            )
        if tenant_id is None:
            return self._skipped(
                tool_call,
                run,
                None,
                "missing_tenant",
                "AgentRun.route_json 未显式提供可信 tenant_id，调用已发生但不能归属计量。",
                reconcile=True,
            )
        occurred_at = _utc(
            reservation.created_at if reservation is not None else tool_call.created_at
        )
        try:
            meter = (
                self._reserved_meter(reservation, tenant_id)
                if reservation is not None
                else self._resolve_meter(
                    tenant_id,
                    tool_call.tool_type,
                    tool_call.tool_name,
                    occurred_at,
                )
            )
            quantity = self.measured_quantity(tool_call, meter.quantity_basis)
            if (
                reservation is not None
                and reservation.actual_quantity is not None
                and quantity != Decimal(reservation.actual_quantity)
            ):
                raise CommercialConflictError("商业预占结算数量与工具调用事实不一致。")
        except _SkipMetering as error:
            return self._skipped(
                tool_call,
                run,
                tenant_id,
                error.code,
                error.reason,
                collecting=error.collecting,
                reconcile=True,
            )

        metadata = {
            "meter_version": METER_VERSION,
            "tool_call_id": tool_call.id,
            "tool_type": tool_call.tool_type,
            "tool_name": tool_call.tool_name,
            "tool_status": tool_call.status,
            "quantity_basis": meter.quantity_basis,
            "entitlement_key": meter.entitlement.entitlement_key,
        }
        if reservation is not None:
            metadata["reservation_id"] = reservation.id
        usage_payload = UsageMeterEventCreate(
            subscription_id=meter.subscription.id,
            entitlement_id=meter.entitlement.id,
            quantity=quantity,
            occurred_at=occurred_at,
            source_system=SOURCE_SYSTEM,
            idempotency_key=_usage_idempotency_key(tool_call.id, meter.entitlement.id),
            subject_type="agent_tool_call",
            subject_id=tool_call.id,
            correlation_id=run.run_id,
            metadata_json=metadata,
        )
        usage_event, usage_created = CommercialMeteringService(self.db).record_usage(
            tenant_id,
            usage_payload,
            actor_type="system",
            actor_id="commercial-runtime-meter",
        )
        cost_event = None
        cost_created = False
        if meter.cost is not None:
            try:
                with self.db.begin_nested():
                    cost_event, cost_created = CommercialMeteringService(self.db).record_cost(
                        tenant_id,
                        self._cost_payload(
                            tool_call,
                            run,
                            meter,
                            quantity,
                            usage_event.id,
                            occurred_at,
                            metadata,
                        ),
                    )
            except Exception as error:
                return RuntimeMeteringResult(
                    status="error",
                    reason_code="cost_metering_failed",
                    reason=_safe_error_reason(error),
                    tool_call_id=tool_call.id,
                    run_id=run.run_id,
                    tenant_id=tenant_id,
                    entitlement_id=meter.entitlement.id,
                    quantity_basis=meter.quantity_basis,
                    quantity=quantity,
                    usage_event_id=usage_event.id,
                    usage_created=usage_created,
                    business_call_occurred=True,
                    requires_reconciliation=True,
                )
        created = usage_created or cost_created
        return RuntimeMeteringResult(
            status="created" if created else "replayed",
            reason_code="metered" if created else "idempotent_replay",
            reason=(
                "Agent 工具调用已追加写入商业用量与成本事实。"
                if created
                else "相同 Agent 工具调用已计量，本次返回原事实。"
            ),
            tool_call_id=tool_call.id,
            run_id=run.run_id,
            tenant_id=tenant_id,
            entitlement_id=meter.entitlement.id,
            quantity_basis=meter.quantity_basis,
            quantity=quantity,
            usage_event_id=usage_event.id,
            cost_event_id=cost_event.id if cost_event is not None else None,
            usage_created=usage_created,
            cost_created=cost_created,
            business_call_occurred=True,
            requires_reconciliation=False,
        )

    def _resolve_meter(
        self,
        tenant_id: str,
        tool_type: str,
        tool_name: str,
        occurred_at: datetime,
    ) -> _ResolvedMeter:
        subscriptions = list(
            self.db.scalars(
                select(TenantSubscription).where(
                    TenantSubscription.tenant_id == tenant_id,
                    TenantSubscription.status.in_(("active", "trialing")),
                )
            ).all()
        )
        subscriptions = [row for row in subscriptions if _subscription_active_at(row, occurred_at)]
        if not subscriptions:
            raise _SkipMetering(
                "no_active_subscription",
                "工具调用已发生，但租户没有覆盖该发生时间的 active/trialing 订阅。",
            )
        if len(subscriptions) > 1:
            raise CommercialConfigurationError("租户存在多个可消费订阅，拒绝重复归属计量。")
        subscription = subscriptions[0]
        entitlements = list(
            self.db.scalars(
                select(CommercialEntitlement).where(
                    CommercialEntitlement.tenant_id == tenant_id,
                    CommercialEntitlement.subscription_id == subscription.id,
                    CommercialEntitlement.status == "active",
                )
            ).all()
        )
        matches: list[tuple[CommercialEntitlement, dict[str, Any]]] = []
        for entitlement in entitlements:
            if not _entitlement_active_at(entitlement, occurred_at):
                continue
            runtime = runtime_meter_config(entitlement.config_json)
            if runtime is not None and runtime_meter_matches(runtime, tool_type, tool_name):
                matches.append((entitlement, runtime))
        if not matches:
            raise _SkipMetering(
                "no_matching_runtime_meter",
                "没有 active 权益显式启用并匹配该工具类型与名称。",
            )
        if len(matches) > 1:
            raise CommercialConfigurationError("多个 active 权益匹配同一工具，拒绝重复计量。")
        entitlement, runtime = matches[0]
        basis = str(runtime.get("quantity_basis") or "").strip()
        if basis not in SUPPORTED_BASES:
            raise CommercialConfigurationError("runtime_meter.quantity_basis 未配置或不受支持。")
        cost = _cost_config(runtime.get("internal_cost"), entitlement.unit)
        return _ResolvedMeter(
            subscription=subscription,
            entitlement=entitlement,
            quantity_basis=basis,  # type: ignore[arg-type]
            cost=cost,
        )

    @staticmethod
    def measured_quantity(tool_call: AgentToolCall, basis: QuantityBasis) -> Decimal:
        if basis == "call":
            return Decimal("1")
        if basis == "duration_ms":
            duration = Decimal(int(tool_call.duration_ms or 0))
            if duration <= 0:
                raise _SkipMetering(
                    "collecting_missing_duration",
                    "duration_ms 尚无真实正数值，等待工具调用完成后再计量。",
                    collecting=True,
                )
            return duration
        request = tool_call.request_json if isinstance(tool_call.request_json, dict) else {}
        response = tool_call.response_json if isinstance(tool_call.response_json, dict) else {}
        if basis in RESOURCE_QUANTITY_KEYS:
            quantity = _read_token(
                (response, request),
                RESOURCE_QUANTITY_KEYS[basis],
            )
            if quantity is None or quantity <= 0:
                raise _SkipMetering(
                    f"collecting_missing_{basis}",
                    f"{basis} 缺少真实结构化正数，拒绝按正文或文件名估算用量。",
                    collecting=True,
                )
            return quantity
        input_tokens = _read_token((request, response), INPUT_TOKEN_KEYS)
        output_tokens = _read_token((response, request), OUTPUT_TOKEN_KEYS)
        if basis == "input_tokens":
            quantity = input_tokens
        elif basis == "output_tokens":
            quantity = output_tokens
        else:
            quantity = _read_token((response, request), TOTAL_TOKEN_KEYS)
            if quantity is None and input_tokens is not None and output_tokens is not None:
                quantity = input_tokens + output_tokens
        if quantity is None or quantity <= 0:
            raise _SkipMetering(
                "collecting_missing_tokens",
                f"{basis} 缺少真实结构化数值，正文长度不会被用于估算 token。",
                collecting=True,
            )
        return quantity

    def _reserved_meter(
        self,
        reservation: CommercialRuntimeReservation,
        tenant_id: str,
    ) -> _ResolvedMeter:
        if reservation.tenant_id != tenant_id:
            raise CommercialConflictError("商业预占不属于 AgentRun 的可信租户。")
        subscription = self.db.scalar(
            select(TenantSubscription).where(
                TenantSubscription.tenant_id == tenant_id,
                TenantSubscription.id == reservation.subscription_id,
            )
        )
        entitlement = self.db.scalar(
            select(CommercialEntitlement).where(
                CommercialEntitlement.tenant_id == tenant_id,
                CommercialEntitlement.subscription_id == reservation.subscription_id,
                CommercialEntitlement.id == reservation.entitlement_id,
            )
        )
        if subscription is None or entitlement is None:
            raise LookupError("商业预占引用的订阅或权益不存在。")
        basis = reservation.quantity_basis
        if basis not in SUPPORTED_BASES:
            raise CommercialConfigurationError("商业预占的计量基准不受支持。")
        runtime = reservation.meter_config_json
        cost = _cost_config(runtime.get("internal_cost"), entitlement.unit)
        return _ResolvedMeter(
            subscription=subscription,
            entitlement=entitlement,
            quantity_basis=basis,  # type: ignore[arg-type]
            cost=cost,
        )

    @staticmethod
    def _cost_payload(
        tool_call: AgentToolCall,
        run: AgentRun,
        meter: _ResolvedMeter,
        quantity: Decimal,
        usage_event_id: str,
        occurred_at: datetime,
        usage_metadata: dict[str, Any],
    ) -> CommercialCostEventCreate:
        cost = meter.cost
        if cost is None:
            raise CommercialConfigurationError("内部成本配置不存在。")
        return CommercialCostEventCreate(
            subscription_id=meter.subscription.id,
            usage_event_id=usage_event_id,
            cost_category=cost.cost_category,  # type: ignore[arg-type]
            quantity=quantity,
            unit=cost.unit,
            unit_cost=cost.unit_cost,
            original_currency=cost.original_currency,
            reporting_currency=cost.reporting_currency,
            fx_rate=cost.fx_rate,
            provider=cost.provider,
            sku=cost.sku,
            model_name=cost.model_name,
            allocation_key=f"runtime:{meter.entitlement.id}",
            occurred_at=occurred_at,
            source_system=SOURCE_SYSTEM,
            idempotency_key=_cost_idempotency_key(tool_call.id, meter.entitlement.id),
            correlation_id=run.run_id,
            metadata_json=dict(usage_metadata),
        )

    def _tool_call_pair(self, tool_call_id: str) -> tuple[AgentToolCall, AgentRun] | None:
        return self.db.execute(
            select(AgentToolCall, AgentRun)
            .join(AgentRun, AgentRun.run_id == AgentToolCall.run_id)
            .where(AgentToolCall.id == str(tool_call_id or "").strip())
        ).one_or_none()

    @staticmethod
    def _skipped(
        tool_call: AgentToolCall,
        run: AgentRun,
        tenant_id: str | None,
        code: str,
        reason: str,
        *,
        collecting: bool = False,
        reconcile: bool = False,
        business_call_occurred: bool = True,
    ) -> RuntimeMeteringResult:
        return RuntimeMeteringResult(
            status="skipped",
            reason_code=code,
            reason=reason,
            tool_call_id=tool_call.id,
            run_id=run.run_id,
            tenant_id=tenant_id,
            collecting=collecting,
            business_call_occurred=business_call_occurred,
            requires_reconciliation=reconcile,
        )

    @staticmethod
    def _preflight_denied(
        run_id: str,
        tenant_id: str | None,
        code: str,
        reason: str,
        security_decision: SecurityDecision,
    ) -> RuntimeQuotaPreflight:
        return RuntimeQuotaPreflight(
            allowed=False,
            reason_code=code,
            reason=reason,
            run_id=run_id,
            tenant_id=tenant_id,
            entitlement_id=None,
            quantity_basis=None,
            requested_quantity=None,
            commercially_allowed=False,
            security_decision=security_decision,
        )


def _read_token(payloads: tuple[dict[str, Any], ...], keys: tuple[str, ...]) -> Decimal | None:
    for payload in payloads:
        containers = [payload]
        containers.extend(
            value for key in TOKEN_CONTAINERS if isinstance((value := payload.get(key)), dict)
        )
        for container in containers:
            for key in keys:
                if key not in container:
                    continue
                value = container[key]
                if isinstance(value, bool) or not isinstance(value, (int, float, Decimal)):
                    raise CommercialConfigurationError(f"结构化 token 字段 {key} 必须是数值。")
                quantity = _decimal(value, key)
                if quantity < 0 or quantity != quantity.to_integral_value():
                    raise CommercialConfigurationError(f"结构化 token 字段 {key} 必须是非负整数。")
                return quantity
    return None


def _subscription_active_at(row: TenantSubscription, when: datetime) -> bool:
    start = _utc(row.starts_at)
    end = _utc(row.ends_at) if row.ends_at is not None else None
    period_start = _utc(row.current_period_start)
    period_end = _utc(row.current_period_end)
    return start <= when < period_end and period_start <= when and (end is None or when < end)


def _entitlement_active_at(row: CommercialEntitlement, when: datetime) -> bool:
    start = _utc(row.effective_from)
    end = _utc(row.effective_to) if row.effective_to is not None else None
    return start <= when and (end is None or when < end)
