import uuid
from datetime import datetime, timezone
from typing import Any
from sqlalchemy.ext.asyncio import AsyncSession
from core.exceptions import ForbiddenError, NotFoundError, QuotaExceededError
from modules.billing.models import Plan, Subscription
from modules.billing.repository import BillingRepository


class EntitlementService:
    """Enforces plan quotas, feature entitlement gates, and tracks usage."""

    def __init__(self, db: AsyncSession):
        self.db = db
        self.repo = BillingRepository(db)

    async def get_tenant_plan_and_sub(self, tenant_id: uuid.UUID) -> tuple[Plan, Subscription]:
        sub = await self.repo.get_tenant_subscription(tenant_id)
        if not sub:
            # Create default free subscription
            now = datetime.now(timezone.utc)
            period_end = datetime(2099, 12, 31, tzinfo=timezone.utc)
            sub = await self.repo.create_subscription(
                tenant_id=tenant_id,
                plan_id="free",
                status="active",
                current_period_start=now,
                current_period_end=period_end,
                gateway_provider="manual",
            )

        plan = await self.repo.get_plan_by_id(sub.plan_id)
        if not plan:
            plan = await self.repo.get_plan_by_id("free")
            if not plan:
                raise NotFoundError(f"Plan '{sub.plan_id}' not found in database")

        return plan, sub

    async def check_bot_creation_limit(self, tenant_id: uuid.UUID) -> None:
        """
        Validates whether tenant can add a new bot under current plan limits.
        Raises QuotaExceededError if limit is reached.
        """
        plan, sub = await self.get_tenant_plan_and_sub(tenant_id)

        # If subscription is expired or past due outside grace period, restrict to free tier
        now = datetime.now(timezone.utc)
        if sub.status == "expired" or (sub.status == "past_due" and sub.grace_period_ends_at and now > sub.grace_period_ends_at):
            free_plan = await self.repo.get_plan_by_id("free")
            if free_plan:
                plan = free_plan

        if plan.max_bots != -1:
            current_bots = await self.repo.count_active_bots(tenant_id)
            if current_bots >= plan.max_bots:
                raise QuotaExceededError(
                    f"Plan '{plan.name}' limit of {plan.max_bots} active bot(s) reached. "
                    f"Please upgrade your subscription to connect more bots.",
                    details={
                        "current_usage": current_bots,
                        "limit": plan.max_bots,
                        "plan_id": plan.id,
                        "upgrade_url": "/billing",
                    },
                )

    async def check_feature_access(self, tenant_id: uuid.UUID, feature_name: str) -> None:
        """
        Validates boolean feature entitlement (e.g. ai_enabled, advanced_studio, custom_domain).
        Raises ForbiddenError if feature is not included.
        """
        plan, sub = await self.get_tenant_plan_and_sub(tenant_id)
        has_access = getattr(plan, feature_name, False)
        if not has_access:
            raise ForbiddenError(
                f"Feature '{feature_name}' is not available on the '{plan.name}' plan. "
                f"Please upgrade to unlock this feature.",
                details={"feature": feature_name, "plan_id": plan.id},
            )

    async def get_tenant_limits_and_usage(self, tenant_id: uuid.UUID) -> dict[str, Any]:
        """Compiles usage vs entitlement limits for the tenant dashboard."""
        plan, sub = await self.get_tenant_plan_and_sub(tenant_id)
        current_bots = await self.repo.count_active_bots(tenant_id)
        current_emojis = await self.repo.count_custom_emojis(tenant_id)

        now = datetime.now(timezone.utc)
        in_grace = (
            sub.status == "grace_period"
            or (sub.grace_period_ends_at is not None and now < sub.grace_period_ends_at)
        )

        return {
            "plan_id": plan.id,
            "plan_name": plan.name,
            "subscription_status": sub.status,
            "period_start": sub.current_period_start,
            "period_end": sub.current_period_end,
            "grace_period_active": in_grace,
            "bots": {
                "current": current_bots,
                "limit": plan.max_bots,
                "allowed": plan.max_bots == -1 or current_bots < plan.max_bots,
            },
            "broadcasts": {
                "current": 0,
                "limit": plan.max_broadcasts_per_month,
                "allowed": True,
            },
            "custom_emojis": {
                "current": current_emojis,
                "limit": plan.max_custom_emojis,
                "allowed": plan.max_custom_emojis == -1 or current_emojis < plan.max_custom_emojis,
            },
            "features": {
                "ai_enabled": plan.ai_enabled,
                "advanced_studio": plan.advanced_studio,
                "custom_domain": plan.custom_domain,
                "priority_support": plan.priority_support,
            },
        }
