"""商业运行计量的标量校验、游标与安全错误文案。"""

from __future__ import annotations

from datetime import UTC, datetime
from decimal import Decimal, InvalidOperation
from typing import Any

from pydantic import ValidationError

from app.services.commercial_access_policy import (
    CommercialConfigurationError,
    CommercialConflictError,
)


def encode_cursor(created_at: datetime, tool_call_id: str) -> str:
    return f"{utc(created_at).isoformat()}|{tool_call_id}"


def usage_idempotency_key(tool_call_id: str, entitlement_id: str) -> str:
    return f"agent-tool:{tool_call_id}:{entitlement_id}:usage:v1"


def cost_idempotency_key(tool_call_id: str, entitlement_id: str) -> str:
    return f"agent-tool:{tool_call_id}:{entitlement_id}:cost:v1"


def decode_cursor(value: str) -> tuple[datetime, str]:
    try:
        raw_time, tool_call_id = str(value or "").rsplit("|", maxsplit=1)
        created_at = datetime.fromisoformat(raw_time)
    except (TypeError, ValueError) as error:
        raise ValueError("运行时计量游标格式无效。") from error
    if not tool_call_id.strip() or created_at.tzinfo is None or created_at.utcoffset() is None:
        raise ValueError("运行时计量游标必须包含显式时区和工具调用 ID。")
    return utc(created_at), tool_call_id.strip()


def currency(value: Any, label: str) -> str:
    normalized = str(value or "").strip().upper()
    if len(normalized) != 3 or not normalized.isalpha() or not normalized.isascii():
        raise CommercialConfigurationError(f"{label}必须是三位英文字母。")
    return normalized


def positive_decimal(value: Any, label: str) -> Decimal:
    quantity = decimal(value, label)
    if quantity <= 0:
        raise CommercialConfigurationError(f"{label}必须大于 0。")
    return quantity


def decimal(value: Any, label: str) -> Decimal:
    if value is None or isinstance(value, bool):
        raise CommercialConfigurationError(f"{label}必须是数值。")
    try:
        result = Decimal(str(value))
    except (InvalidOperation, ValueError) as error:
        raise CommercialConfigurationError(f"{label}必须是数值。") from error
    if not result.is_finite():
        raise CommercialConfigurationError(f"{label}必须是有限数值。")
    return result


def required(value: Any) -> str:
    normalized = str(value or "").strip()
    if not normalized:
        raise ValueError("标识不能为空。")
    return normalized


def optional_text(value: Any) -> str | None:
    normalized = str(value or "").strip()
    return normalized or None


def utc(value: datetime) -> datetime:
    return value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)


def safe_error_reason(error: Exception) -> str:
    if isinstance(error, ValidationError):
        return "运行时计量载荷不满足商业事实约束，未写入伪事实。"
    if isinstance(
        error,
        (CommercialConfigurationError, CommercialConflictError, LookupError, ValueError),
    ):
        return str(error)
    return "运行时计量发生内部错误，业务调用已发生并需要补偿核对。"
