"""商业运行计量的轻量策略，避免执行桥接与账本服务互相依赖。"""

from __future__ import annotations

from decimal import Decimal, InvalidOperation
from typing import Any, Literal

from app.services.commercial_access_policy import CommercialConfigurationError

ToolCallMeteringState = Literal["billable", "collecting", "not_billable"]

SUCCESSFUL_TOOL_STATUSES = {"completed", "ok", "success", "succeeded"}
COLLECTING_TOOL_STATUSES = {"pending", "queued", "running"}
NON_OCCURRED_TOOL_STATUSES = {"blocked", "cancelled", "canceled", "skipped"}


def tool_call_metering_state(status: Any) -> ToolCallMeteringState:
    normalized = str(status or "").strip().lower()
    if normalized in SUCCESSFUL_TOOL_STATUSES:
        return "billable"
    if normalized in COLLECTING_TOOL_STATUSES:
        return "collecting"
    return "not_billable"


def tool_call_business_occurred(status: Any) -> bool:
    return str(status or "").strip().lower() not in NON_OCCURRED_TOOL_STATUSES


def runtime_meter_config(config: Any) -> dict[str, Any] | None:
    if not isinstance(config, dict):
        return None
    runtime = config.get("runtime_meter")
    if not isinstance(runtime, dict) or runtime.get("enabled") is not True:
        return None
    return runtime


def runtime_meter_matches(runtime: dict[str, Any], tool_type: str, tool_name: str) -> bool:
    return _dimension_matches(runtime, "tool_type", "tool_types", tool_type) and _dimension_matches(
        runtime,
        "tool_name",
        "tool_names",
        tool_name,
    )


def preflight_quantity(runtime_configs: list[dict[str, Any]]) -> Decimal:
    """返回调用前最小预留量；变动计量可由配置声明更保守的预留量。"""

    raw_values = [item.get("preflight_quantity", 1) for item in runtime_configs]
    quantities = {_positive_decimal(value) for value in raw_values}
    if len(quantities) != 1:
        raise CommercialConfigurationError("多个匹配计量器的 preflight_quantity 不一致。")
    return quantities.pop()


def tenant_from_agent_route(route: Any) -> str | None:
    if not isinstance(route, dict):
        return None
    value = route.get("tenant_id")
    if not isinstance(value, str):
        return None
    normalized = value.strip()
    return normalized or None


def _dimension_matches(
    config: dict[str, Any],
    singular: str,
    plural: str,
    actual: str,
) -> bool:
    expected = config.get(singular)
    if isinstance(expected, str) and expected.strip():
        return expected.strip() == str(actual or "").strip()
    choices = config.get(plural)
    if not isinstance(choices, list) or not choices:
        return False
    normalized = {item.strip() for item in choices if isinstance(item, str) and item.strip()}
    return str(actual or "").strip() in normalized


def _positive_decimal(value: Any) -> Decimal:
    if value is None or isinstance(value, bool):
        raise CommercialConfigurationError("runtime_meter.preflight_quantity 必须是正数。")
    try:
        result = Decimal(str(value))
    except (InvalidOperation, ValueError) as error:
        raise CommercialConfigurationError(
            "runtime_meter.preflight_quantity 必须是正数。"
        ) from error
    if not result.is_finite() or result <= 0:
        raise CommercialConfigurationError("runtime_meter.preflight_quantity 必须是正数。")
    return result
