"""
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
"""

from __future__ import annotations

from datetime import UTC, datetime
from typing import TYPE_CHECKING

from aicippy.billing.models import PlanInfo, PlanStatus
from aicippy.config import is_founder
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).
    No hardcoded admin email bypass exists in application config.

    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.

        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()

        # Founder bypass — unlimited privileges, instant validation
        if is_founder(email_lower):
            return PlanInfo(
                tenant_id="founder",
                org_tenant_id="aivibe",
                email=email_lower,
                plan="chakra",
                status=PlanStatus.ACTIVE,
                credits_remaining=999999,
                credits_total=999999,
                expiry=None,
                is_admin=True,
            )

        return self._validate_via_platform(email_lower)

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

            # 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

        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 validate_or_cached(self, email: str) -> PlanInfo:
        """Return cached plan info if fresh, otherwise re-validate.

        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)

    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())
