"""按可信租户和工具维度解析唯一运行时商业计量器。"""

from __future__ import annotations

from dataclasses import dataclass
from datetime import UTC, datetime
from typing import Any

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

from app.models.commercial import CommercialEntitlement, TenantSubscription
from app.services.commercial_runtime_policy import (
    runtime_meter_config,
    runtime_meter_matches,
)


@dataclass(frozen=True)
class ConfiguredRuntimeMeter:
    entitlement: CommercialEntitlement
    subscription: TenantSubscription
    config: dict[str, Any]


def matching_runtime_meters(
    db: Session,
    *,
    tenant_id: str,
    tool_type: str,
    tool_name: str,
    as_of: datetime | None = None,
) -> list[ConfiguredRuntimeMeter]:
    """返回当前窗口内显式配置的计量器，包括需失败关闭的暂停合同。"""

    tenant = str(tenant_id or "").strip()
    if not tenant:
        return []
    when = _utc(as_of or datetime.now(UTC))
    rows = db.execute(
        select(CommercialEntitlement, TenantSubscription)
        .join(
            TenantSubscription,
            TenantSubscription.id == CommercialEntitlement.subscription_id,
        )
        .where(
            CommercialEntitlement.tenant_id == tenant,
            TenantSubscription.tenant_id == tenant,
            TenantSubscription.status.in_(
                ("trialing", "active", "past_due", "suspended")
            ),
            TenantSubscription.starts_at <= when,
            or_(TenantSubscription.ends_at.is_(None), TenantSubscription.ends_at > when),
            TenantSubscription.current_period_start <= when,
            TenantSubscription.current_period_end > when,
            CommercialEntitlement.status.in_(("active", "suspended")),
            CommercialEntitlement.effective_from <= when,
            or_(
                CommercialEntitlement.effective_to.is_(None),
                CommercialEntitlement.effective_to > when,
            ),
        )
    ).all()
    meters: list[ConfiguredRuntimeMeter] = []
    for entitlement, subscription in rows:
        runtime = runtime_meter_config(entitlement.config_json)
        if runtime is None or not runtime_meter_matches(runtime, tool_type, tool_name):
            continue
        meters.append(
            ConfiguredRuntimeMeter(
                entitlement=entitlement,
                subscription=subscription,
                config=runtime,
            )
        )
    return meters


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