import os
from decimal import Decimal, ROUND_HALF_UP
from typing import List, Optional
from datetime import datetime, timedelta

import stripe

from fastapi import HTTPException, status
from sqlalchemy import select, and_, cast, String
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import selectinload

from app.models.user.subscription_model import (
    SubscriptionPlan,
    UserSubscription,
    SubscriptionPlanType,
    SubscriptionStatus
)
from app.models.user.user_model import User
from app.schemas.user.subscription_schemas import (
    SubscriptionPlanResponse,
    BenefitItem,
    UserSubscriptionResponse,
    SubscriptionPaymentIntentResponse,
    SubscriptionConfirmResponse
)


class SubscriptionService:
    def __init__(self, db: AsyncSession):
        self.db = db

    @staticmethod
    def _ensure_stripe_configured() -> str:
        api_key = os.getenv("STRIPE_SECRET_KEY")
        if not api_key:
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail="Stripe secret key not configured"
            )
        stripe.api_key = api_key
        return api_key

    @staticmethod
    def _get_stripe_currency() -> str:
        return os.getenv("STRIPE_PAYMENT_CURRENCY", "usd")

    @staticmethod
    def _amount_to_cents(amount: float) -> int:
        quantized = Decimal(str(amount)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
        return int(quantized * 100)

    def _get_plan_benefits(self, plan_type: SubscriptionPlanType) -> List[BenefitItem]:
        """Get benefits for a subscription plan"""
        if plan_type == SubscriptionPlanType.FREE:
            return [
                BenefitItem(
                    title="Get discounts when travelling",
                    subtitle="1 time per month"
                ),
                BenefitItem(
                    title="Get notified for discounts",
                    subtitle="4 times per month"
                )
            ]
        else:  # PRO
            return [
                BenefitItem(
                    title="Get discounts when travelling",
                    subtitle="Unlimited times"
                ),
                BenefitItem(
                    title="Get notified for discounts",
                    subtitle="Unlimited times"
                )
            ]

    async def get_subscription_plans(self) -> List[SubscriptionPlanResponse]:
        """Get all available subscription plans with benefits"""
        stmt = select(SubscriptionPlan).where(SubscriptionPlan.is_active == True)
        result = await self.db.execute(stmt)
        plans = result.scalars().all()
        
        # If plans don't exist in DB, return default plans
        if not plans:
            return [
                SubscriptionPlanResponse(
                    plan_id=0,
                    plan_type=SubscriptionPlanType.FREE.value,
                    name="Free",
                    price=0.0,
                    billing_period="month",
                    benefits=self._get_plan_benefits(SubscriptionPlanType.FREE)
                ),
                SubscriptionPlanResponse(
                    plan_id=1,
                    plan_type=SubscriptionPlanType.PRO.value,
                    name="Pro",
                    price=14.99,
                    billing_period="month",
                    benefits=self._get_plan_benefits(SubscriptionPlanType.PRO)
                )
            ]
        
        # Convert DB plans to response with benefits
        plan_responses = []
        for plan in plans:
            plan_type = SubscriptionPlanType(plan.plan_type)
            plan_responses.append(SubscriptionPlanResponse(
                plan_id=plan.plan_id,
                plan_type=plan.plan_type,
                name=plan.name,
                price=plan.price,
                billing_period=plan.billing_period,
                benefits=self._get_plan_benefits(plan_type)
            ))
        
        return plan_responses

    async def get_user_subscription(self, user_id: int) -> UserSubscriptionResponse:
        """Get user's current subscription status"""
        # Check if user exists
        user_stmt = select(User).where(User.user_id == user_id)
        user_result = await self.db.execute(user_stmt)
        user = user_result.scalar_one_or_none()
        
        if not user:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="User not found"
            )
        
        # Check subscription expiry
        await self._check_and_update_subscription_expiry(user)
        
        # Get active subscription
        # Cast status to string to handle VARCHAR column type mismatch
        stmt = (
            select(UserSubscription)
            .where(
                and_(
                    UserSubscription.user_id == user_id,
                    cast(UserSubscription.status, String) == SubscriptionStatus.ACTIVE.value
                )
            )
            .options(selectinload(UserSubscription.plan))
            .order_by(UserSubscription.started_at.desc())
        )
        result = await self.db.execute(stmt)
        subscription = result.scalar_one_or_none()
        
        if subscription:
            # Get plan type and benefits
            # Convert plan_type to enum for benefits lookup
            plan_type = SubscriptionPlanType(subscription.plan.plan_type)
            benefits = self._get_plan_benefits(plan_type)
            
            # Get plan_type as string (handle both enum and string)
            plan_type_str = subscription.plan.plan_type
            if not isinstance(plan_type_str, str):
                plan_type_str = plan_type_str.value if hasattr(plan_type_str, 'value') else str(plan_type_str)
            
            return UserSubscriptionResponse(
                subscription_id=subscription.subscription_id,
                plan_type=plan_type_str,
                plan_name=subscription.plan.name,
                plan_price=subscription.plan.price,
                billing_period=subscription.plan.billing_period,
                benefits=benefits,
                is_pro=plan_type == SubscriptionPlanType.PRO,
                status=subscription.status.value,
                started_at=subscription.started_at,
                expires_at=subscription.expires_at,
                auto_renew=subscription.auto_renew
            )
        else:
            # User is on free plan
            benefits = self._get_plan_benefits(SubscriptionPlanType.FREE)
            return UserSubscriptionResponse(
                subscription_id=None,
                plan_type=SubscriptionPlanType.FREE.value,
                plan_name="Free",
                plan_price=0.0,
                billing_period="month",
                benefits=benefits,
                is_pro=False,
                status=SubscriptionStatus.ACTIVE.value,
                started_at=None,
                expires_at=None,
                auto_renew=False
            )

    async def _check_and_update_subscription_expiry(self, user: User) -> None:
        """Check if subscription has expired and update user status"""
        if user.is_pro and user.subscription_expires_at:
            from datetime import timezone
            now = datetime.now(timezone.utc)
            if user.subscription_expires_at <= now:
                # Subscription expired
                user.is_pro = False
                user.subscription_expires_at = None
                
                # Update subscription status
                # Cast status to string to handle VARCHAR column type mismatch
                stmt = select(UserSubscription).where(
                    and_(
                        UserSubscription.user_id == user.user_id,
                        cast(UserSubscription.status, String) == SubscriptionStatus.ACTIVE.value
                    )
                )
                result = await self.db.execute(stmt)
                active_subscription = result.scalar_one_or_none()
                
                if active_subscription:
                    active_subscription.status = SubscriptionStatus.EXPIRED
                    active_subscription.expires_at = now
                
                await self.db.commit()

    async def create_subscription_payment_intent(
        self,
        user_id: int,
        plan_type: str
    ) -> SubscriptionPaymentIntentResponse:
        """Create Stripe payment intent for subscription"""
        # Validate plan type
        if plan_type not in [SubscriptionPlanType.FREE.value, SubscriptionPlanType.PRO.value]:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="Invalid plan type. Must be 'FREE' or 'PRO'"
            )
        
        if plan_type == SubscriptionPlanType.FREE.value:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="Free plan does not require payment"
            )
        
        # Get user
        user_stmt = select(User).where(User.user_id == user_id)
        user_result = await self.db.execute(user_stmt)
        user = user_result.scalar_one_or_none()
        
        if not user:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="User not found"
            )
        
        # Get Pro plan
        # Cast plan_type to string to handle VARCHAR column type mismatch
        plan_stmt = select(SubscriptionPlan).where(
            cast(SubscriptionPlan.plan_type, String) == SubscriptionPlanType.PRO.value
        )
        plan_result = await self.db.execute(plan_stmt)
        plan = plan_result.scalar_one_or_none()
        
        if not plan:
            # Use default price if plan not in DB
            price = 14.99
        else:
            price = plan.price
        
        amount_cents = self._amount_to_cents(price)
        if amount_cents <= 0:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="Invalid subscription price"
            )
        
        self._ensure_stripe_configured()
        currency = self._get_stripe_currency()
        
        try:
            payment_intent = stripe.PaymentIntent.create(
                amount=amount_cents,
                currency=currency,
                metadata={
                    "user_id": user_id,
                    "plan_type": plan_type,
                    "type": "subscription"
                },
                automatic_payment_methods={"enabled": True},
            )
        except stripe.error.StripeError as exc:
            raise HTTPException(
                status_code=status.HTTP_502_BAD_GATEWAY,
                detail=f"Stripe error: {exc.user_message or str(exc)}"
            )
        
        client_secret = payment_intent.client_secret
        if not client_secret:
            try:
                refreshed_intent = stripe.PaymentIntent.retrieve(payment_intent.id)
                client_secret = refreshed_intent.client_secret
            except stripe.error.StripeError as exc:
                raise HTTPException(
                    status_code=status.HTTP_502_BAD_GATEWAY,
                    detail=f"Stripe error: {exc.user_message or str(exc)}"
                )
        
        if not client_secret:
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail="Unable to retrieve Stripe payment intent client secret"
            )
        
        return SubscriptionPaymentIntentResponse(
            payment_intent_id=payment_intent.id,
            client_secret=client_secret,
            amount=payment_intent.amount,
            currency=payment_intent.currency,
            status=payment_intent.status
        )

    async def confirm_subscription_payment(
        self,
        user_id: int,
        payment_intent_id: str
    ) -> SubscriptionConfirmResponse:
        """Confirm subscription payment and activate subscription"""
        # Get user
        user_stmt = select(User).where(User.user_id == user_id)
        user_result = await self.db.execute(user_stmt)
        user = user_result.scalar_one_or_none()
        
        if not user:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="User not found"
            )
        
        self._ensure_stripe_configured()
        
        try:
            payment_intent = stripe.PaymentIntent.retrieve(payment_intent_id)
        except stripe.error.StripeError as exc:
            raise HTTPException(
                status_code=status.HTTP_502_BAD_GATEWAY,
                detail=f"Stripe error: {exc.user_message or str(exc)}"
            )
        
        # Verify payment intent belongs to user
        if payment_intent.metadata.get("user_id") != str(user_id):
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="Payment intent does not belong to this user"
            )
        
        # Verify it's a subscription payment
        if payment_intent.metadata.get("type") != "subscription":
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="Payment intent is not for a subscription"
            )
        
        plan_type = payment_intent.metadata.get("plan_type", SubscriptionPlanType.PRO.value)
        
        # Check payment status
        if payment_intent.status != "succeeded":
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail=f"Payment intent status is {payment_intent.status}. Payment must be succeeded."
            )
        
        # Get or create Pro plan
        # Cast plan_type to string to handle VARCHAR column type mismatch
        plan_stmt = select(SubscriptionPlan).where(
            cast(SubscriptionPlan.plan_type, String) == SubscriptionPlanType.PRO.value
        )
        plan_result = await self.db.execute(plan_stmt)
        plan = plan_result.scalar_one_or_none()
        
        if not plan:
            # Create Pro plan if it doesn't exist
            plan = SubscriptionPlan(
                plan_type=SubscriptionPlanType.PRO.value,
                name="Pro",
                price=14.99,
                billing_period="month",
                is_active=True
            )
            self.db.add(plan)
            await self.db.flush()
        
        # Cancel any existing active subscriptions
        # Cast status to string to handle VARCHAR column type mismatch
        existing_stmt = select(UserSubscription).where(
            and_(
                UserSubscription.user_id == user_id,
                cast(UserSubscription.status, String) == SubscriptionStatus.ACTIVE.value
            )
        )
        existing_result = await self.db.execute(existing_stmt)
        existing_subscriptions = existing_result.scalars().all()
        
        for sub in existing_subscriptions:
            sub.status = SubscriptionStatus.CANCELLED
            from datetime import timezone
            sub.cancelled_at = datetime.now(timezone.utc)
        
        # Calculate expiry date (1 month from now)
        # Approximate 30 days for simplicity (can be improved with dateutil if needed)
        from datetime import timezone
        expires_at = datetime.now(timezone.utc) + timedelta(days=30)
        
        # Create new subscription
        new_subscription = UserSubscription(
            user_id=user_id,
            plan_id=plan.plan_id,
            status=SubscriptionStatus.ACTIVE,
            stripe_payment_intent_id=payment_intent_id,
            expires_at=expires_at,
            auto_renew=True
        )
        self.db.add(new_subscription)
        
        # Update user subscription status
        user.is_pro = True
        user.subscription_expires_at = expires_at
        
        await self.db.commit()
        await self.db.refresh(new_subscription)
        await self.db.refresh(user)
        
        return SubscriptionConfirmResponse(
            success=True,
            message="Subscription activated successfully",
            subscription=UserSubscriptionResponse(
                subscription_id=new_subscription.subscription_id,
                plan_type=plan.plan_type,
                is_pro=True,
                status=new_subscription.status.value,
                started_at=new_subscription.started_at,
                expires_at=new_subscription.expires_at,
                auto_renew=new_subscription.auto_renew
            )
        )
