"""校验并解析 Agent 运行时内部成本配置。"""

from __future__ import annotations

from dataclasses import dataclass
from decimal import Decimal
from typing import Any

from app.services.commercial_access_policy import CommercialConfigurationError
from app.services.commercial_runtime_values import currency, optional_text, positive_decimal

SUPPORTED_COST_CATEGORIES = {
    "ai_inference",
    "ocr",
    "storage",
    "connector",
    "support",
    "implementation",
    "infrastructure",
    "payment",
    "other",
}


@dataclass(frozen=True)
class RuntimeCostConfig:
    cost_category: str
    unit: str
    unit_cost: Decimal
    original_currency: str
    reporting_currency: str
    fx_rate: Decimal
    provider: str | None
    sku: str | None
    model_name: str | None


def runtime_cost_config(value: Any, default_unit: str) -> RuntimeCostConfig | None:
    if not isinstance(value, dict) or value.get("enabled") is not True:
        return None
    category = str(value.get("cost_category") or "").strip()
    if category not in SUPPORTED_COST_CATEGORIES:
        raise CommercialConfigurationError("internal_cost.cost_category 未配置或不受支持。")
    unit_cost = positive_decimal(value.get("unit_cost"), "internal_cost.unit_cost")
    fx_rate = positive_decimal(value.get("fx_rate"), "internal_cost.fx_rate")
    original_currency = currency(value.get("original_currency"), "原始币种")
    reporting_currency = currency(value.get("reporting_currency"), "报告币种")
    unit = str(value.get("unit") or default_unit or "").strip()
    if not unit:
        raise CommercialConfigurationError("internal_cost.unit 不能为空。")
    return RuntimeCostConfig(
        cost_category=category,
        unit=unit,
        unit_cost=unit_cost,
        original_currency=original_currency,
        reporting_currency=reporting_currency,
        fx_rate=fx_rate,
        provider=optional_text(value.get("provider")),
        sku=optional_text(value.get("sku")),
        model_name=optional_text(value.get("model_name")),
    )
