"""
Plan validator for subscription enforcement.

Validates subscription plans via the AiVibe platform API (api.aivibe.cloud).
All tenant/plan data is stored in PostgreSQL at db.aivibe.cloud.

Lookup flow:
  email -> platform_client.get_tenant(email) -> tenant_id
  tenant_id -> platform_client.validate_plan(tenant_id) -> plan info

Admin status, credits, and plan tier are ALL determined by the platform API.
No hardcoded bypasses exist.
"""

from __future__ import annotations

from datetime import UTC, datetime
from typing import TYPE_CHECKING, Any

from aicippy.billing.models import PlanInfo, PlanStatus
from aicippy.exceptions import PlanValidationError
from aicippy.utils.async_utils import TTLCache, run_sync
from aicippy.utils.logging import get_logger

if TYPE_CHECKING:
    from aicippy.platform.client import PlatformClient

logger = get_logger(__name__)


class PlanValidator:
    """Validates subscription plans for AiCippy access.

    Uses a 5-minute cache to reduce API reads. Admin status is determined
    by the platform API (is_admin field in validate_plan() response).

    Args:
        platform_client: PlatformClient for api.aivibe.cloud validation.
    """

    def __init__(self, platform_client: PlatformClient) -> None:
        self._platform_client = platform_client
        self._cache: TTLCache = TTLCache(max_size=1000, ttl_seconds=300)

    def validate(self, email: str) -> PlanInfo:
        """Validate a user's plan by email (sync version).

        Uses run_sync() to bridge async platform API calls. Safe to call
        from sync contexts (typer commands, login flow). For async contexts
        (start_interactive_session), use validate_async() instead.

        Args:
            email: User email address.

        Returns:
            PlanInfo with plan details and validity.

        Raises:
            PlanValidationError: If backend is unreachable and no cache exists.
        """
        email_lower = email.strip().lower()
        return self._validate_via_platform(email_lower)

    async def validate_async(self, email: str) -> PlanInfo:
        """Validate a user's plan by email (async version).

        Calls platform API directly with await. Use this from async contexts
        to avoid event loop conflicts with run_sync().

        Args:
            email: User email address.

        Returns:
            PlanInfo with plan details and validity.

        Raises:
            PlanValidationError: If backend is unreachable and no cache exists.
        """
        email_lower = email.strip().lower()
        return await self._validate_via_platform_async(email_lower)

    def _validate_via_platform(self, email: str) -> PlanInfo:
        """Validate using the AiVibe platform API (sync bridge)."""
        try:
            tenant_info = run_sync(self._platform_client.get_tenant(email))
            plan_data = run_sync(self._platform_client.validate_plan(tenant_info.tenant_id))
            return self._build_plan_info(email, tenant_info, plan_data)

        except Exception as e:
            logger.warning(
                "plan_validation_platform_error",
                email=email,
                error=str(e),
            )
            cached = self._cache.get(email)
            if cached is not None:
                return cached
            raise PlanValidationError(f"Unable to validate plan: {e}") from e

    async def _validate_via_platform_async(self, email: str) -> PlanInfo:
        """Validate using the AiVibe platform API (native async)."""
        try:
            tenant_info = await self._platform_client.get_tenant(email)
            plan_data = await self._platform_client.validate_plan(tenant_info.tenant_id)
            return self._build_plan_info(email, tenant_info, plan_data)

        except Exception as e:
            logger.warning(
                "plan_validation_platform_error",
                email=email,
                error=str(e),
            )
            cached = self._cache.get(email)
            if cached is not None:
                return cached
            raise PlanValidationError(f"Unable to validate plan: {e}") from e

    def _build_plan_info(
        self, email: str, tenant_info: Any, plan_data: dict[str, Any]
    ) -> PlanInfo:
        """Build PlanInfo from platform API response data."""
        # Map status string to enum
        try:
            plan_status = PlanStatus(plan_data.get("status", "no_plan"))
        except ValueError:
            plan_status = PlanStatus.SUSPENDED

        # Parse expiry date
        expiry_dt: datetime | None = None
        expiry_str = plan_data.get("expiry")
        if expiry_str:
            try:
                expiry_dt = datetime.fromisoformat(expiry_str.replace("Z", "+00:00"))
            except (ValueError, AttributeError):
                logger.debug("expiry_date_parse_failed", exc_info=True)

        # Check if expired based on date
        if (
            plan_status == PlanStatus.ACTIVE
            and expiry_dt is not None
            and expiry_dt < datetime.now(UTC)
        ):
            plan_status = PlanStatus.EXPIRED

        plan_info = PlanInfo(
            tenant_id=tenant_info.tenant_id,
            org_tenant_id=tenant_info.org_tenant_id,
            email=email,
            plan=plan_data.get("plan", "none"),
            status=plan_status,
            credits_remaining=int(plan_data.get("credits_remaining", 0)),
            credits_total=int(plan_data.get("credits_total", 0)),
            expiry=expiry_dt,
            is_admin=bool(plan_data.get("is_admin", False)),
        )
        self._cache.set(email, plan_info)
        return plan_info

    def validate_or_cached(self, email: str) -> PlanInfo:
        """Return cached plan info if fresh, otherwise re-validate (sync).

        Args:
            email: User email address.

        Returns:
            PlanInfo (cached if <5min old, fresh otherwise).
        """
        email_lower = email.strip().lower()

        cached = self._cache.get(email_lower)
        if cached is not None and not cached.is_cache_stale:
            return cached

        return self.validate(email_lower)

    async def validate_or_cached_async(self, email: str) -> PlanInfo:
        """Return cached plan info if fresh, otherwise re-validate (async).

        Args:
            email: User email address.

        Returns:
            PlanInfo (cached if <5min old, fresh otherwise).
        """
        email_lower = email.strip().lower()

        cached = self._cache.get(email_lower)
        if cached is not None and not cached.is_cache_stale:
            return cached

        return await self.validate_async(email_lower)

    def clear_cache(self) -> None:
        """Invalidate all cached plan data."""
        self._cache.clear()

    def get_cached(self, email: str) -> PlanInfo | None:
        """Get cached plan info without querying the backend."""
        return self._cache.get(email.strip().lower())
