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

import stripe
from fastapi import HTTPException, status
from sqlalchemy import select, func, and_, or_, case
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import selectinload

from app.models.staff.store_model import Chain
from app.models.staff.transaction_model import ChainTransaction, TransactionTypeEnum, TransactionStatusEnum
from app.models.user.order_model import UserOrder
from app.schemas.staff.transaction_schemas import (
    TransactionResponse,
    ChainBalanceResponse,
    TransactionListResponse,
    WithdrawalRequest,
    WithdrawalResponse,
    TransactionSummaryResponse,
    StripeConnectCreateRequest,
    StripeConnectCreateResponse,
    StripeConnectStatusResponse,
)


class TransactionService:
    """Service for managing chain transactions and wallet balance"""
    
    def __init__(self, db: AsyncSession):
        self.db = db

    @staticmethod
    def _ensure_stripe_configured() -> str:
        """Ensure Stripe is configured"""
        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 _amount_to_cents(amount: float) -> int:
        """Convert dollars to cents"""
        quantized = Decimal(str(amount)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
        return int(quantized * 100)

    @staticmethod
    def _cents_to_dollars(cents: int) -> float:
        """Convert cents to dollars"""
        return float(Decimal(cents) / Decimal("100"))

    async def _get_chain(self, chain_id: int) -> Chain:
        """Get chain by ID (excludes deleted chains)"""
        stmt = select(Chain).where(
            and_(
                Chain.chain_id == chain_id,
                Chain.is_deleted == False
            )
        )
        result = await self.db.execute(stmt)
        chain = result.scalar_one_or_none()
        if not chain:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Chain not found"
            )
        return chain

    async def _calculate_stripe_fee(self, amount: float) -> float:
        """
        Calculate Stripe processing fee.
        Stripe charges: 2.9% + $0.30 per transaction
        """
        stripe_fee_percent = 0.029  # 2.9%
        stripe_fee_fixed = 0.30  # $0.30
        
        fee = (amount * stripe_fee_percent) + stripe_fee_fixed
        return float(Decimal(str(fee)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP))

    async def create_sale_transaction(
        self,
        chain_id: int,
        order_id: int,
        gross_amount: float,
        stripe_payment_intent_id: str
    ) -> ChainTransaction:
        """
        Create a transaction record when an order is paid.
        Calculates platform fee, Stripe fee, and net amount for the chain.
        """
        chain = await self._get_chain(chain_id)
        
        # Get profit_percentage (platform fee percentage)
        # If profit_percentage is 10%, platform takes 10%, chain gets 90%
        profit_percentage = chain.profit_percentage if chain.profit_percentage is not None else 10.0
        platform_fee_percent = profit_percentage / 100.0
        
        # Calculate Stripe fee
        stripe_fee = await self._calculate_stripe_fee(gross_amount)
        
        # Calculate platform fee (on gross amount before Stripe fee)
        platform_fee = gross_amount * platform_fee_percent
        
        # Calculate net amount chain receives
        # Net = Gross - Stripe Fee - Platform Fee
        net_amount = gross_amount - stripe_fee - platform_fee
        net_amount = float(Decimal(str(net_amount)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP))
        
        # Create transaction
        transaction = ChainTransaction(
            chain_id=chain_id,
            order_id=order_id,
            transaction_type=TransactionTypeEnum.SALE,
            status=TransactionStatusEnum.COMPLETED,
            gross_amount=gross_amount,
            stripe_fee=stripe_fee,
            platform_fee=platform_fee,
            net_amount=net_amount,
            stripe_payment_intent_id=stripe_payment_intent_id,
            description=f"Sale from order #{order_id}",
            completed_at=datetime.utcnow()
        )
        
        self.db.add(transaction)
        
        # Update chain balance
        chain.balance += net_amount
        
        await self.db.commit()
        await self.db.refresh(transaction)
        
        return transaction

    async def create_refund_transaction(
        self,
        chain_id: int,
        order_id: int,
        refund_amount: float
    ) -> ChainTransaction:
        """
        Create a refund transaction when an order is refunded.
        Deducts the net amount that was previously credited to the chain.
        """
        # Find the original sale transaction
        stmt = select(ChainTransaction).where(
            and_(
                ChainTransaction.chain_id == chain_id,
                ChainTransaction.order_id == order_id,
                ChainTransaction.transaction_type == TransactionTypeEnum.SALE,
                ChainTransaction.status == TransactionStatusEnum.COMPLETED
            )
        ).order_by(ChainTransaction.created_at.desc())
        result = await self.db.execute(stmt)
        original_transaction = result.scalar_one_or_none()
        
        if not original_transaction:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Original sale transaction not found for this order"
            )
        
        # Calculate proportional refund
        # If refund is partial, calculate proportion
        refund_ratio = refund_amount / original_transaction.gross_amount
        
        # Refund the net amount proportionally
        refund_net_amount = original_transaction.net_amount * refund_ratio
        refund_net_amount = float(Decimal(str(refund_net_amount)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP))
        
        # Create refund transaction
        transaction = ChainTransaction(
            chain_id=chain_id,
            order_id=order_id,
            transaction_type=TransactionTypeEnum.REFUND,
            status=TransactionStatusEnum.COMPLETED,
            gross_amount=refund_amount,
            stripe_fee=0.0,  # Stripe refunds fees
            platform_fee=0.0,  # Platform fee is also refunded
            net_amount=-refund_net_amount,  # Negative because it's a deduction
            stripe_payment_intent_id=original_transaction.stripe_payment_intent_id,
            description=f"Refund for order #{order_id}",
            completed_at=datetime.utcnow()
        )
        
        self.db.add(transaction)
        
        # Deduct from chain balance
        chain = await self._get_chain(chain_id)
        chain.balance -= refund_net_amount
        if chain.balance < 0:
            chain.balance = 0.0  # Balance can't go negative
        
        await self.db.commit()
        await self.db.refresh(transaction)
        
        return transaction

    async def get_chain_balance(self, chain_id: int) -> ChainBalanceResponse:
        """Get current balance and statistics for a chain"""
        chain = await self._get_chain(chain_id)
        
        # Calculate statistics from transactions
        # Get all completed transactions for total_earned (net amount chain received)
        completed_stmt = select(
            func.sum(ChainTransaction.net_amount).label("total_earned")
        ).where(
            and_(
                ChainTransaction.chain_id == chain_id,
                ChainTransaction.status == TransactionStatusEnum.COMPLETED
            )
        )
        
        # Get platform fees earned (sum of platform_fee from all SALE transactions)
        platform_fees_stmt = select(
            func.sum(ChainTransaction.platform_fee).label("platform_earned")
        ).where(
            and_(
                ChainTransaction.chain_id == chain_id,
                ChainTransaction.transaction_type == TransactionTypeEnum.SALE,
                ChainTransaction.status == TransactionStatusEnum.COMPLETED
            )
        )
        
        # Get total gross sales (sum of gross_amount from all SALE transactions)
        total_sales_stmt = select(
            func.sum(ChainTransaction.gross_amount).label("total_sales")
        ).where(
            and_(
                ChainTransaction.chain_id == chain_id,
                ChainTransaction.transaction_type == TransactionTypeEnum.SALE,
                ChainTransaction.status == TransactionStatusEnum.COMPLETED
            )
        )
        
        # Get withdrawals (only completed)
        withdrawal_stmt = select(
            func.sum(func.abs(ChainTransaction.net_amount)).label("total_withdrawn")
        ).where(
            and_(
                ChainTransaction.chain_id == chain_id,
                ChainTransaction.transaction_type == TransactionTypeEnum.WITHDRAWAL,
                ChainTransaction.status == TransactionStatusEnum.COMPLETED
            )
        )
        
        # Get refunds (only completed)
        refund_stmt = select(
            func.sum(func.abs(ChainTransaction.net_amount)).label("total_refunded")
        ).where(
            and_(
                ChainTransaction.chain_id == chain_id,
                ChainTransaction.transaction_type == TransactionTypeEnum.REFUND,
                ChainTransaction.status == TransactionStatusEnum.COMPLETED
            )
        )
        
        # Get pending sales
        pending_stmt = select(
            func.sum(ChainTransaction.net_amount).label("pending_balance")
        ).where(
            and_(
                ChainTransaction.chain_id == chain_id,
                ChainTransaction.transaction_type == TransactionTypeEnum.SALE,
                ChainTransaction.status == TransactionStatusEnum.PENDING
            )
        )
        
        # Get balance on hold (sales transactions less than 3 days old)
        # 3-day hold period: transactions created within last 3 days are on hold
        from datetime import timedelta
        three_days_ago = datetime.utcnow() - timedelta(days=3)
        
        on_hold_stmt = select(
            func.sum(ChainTransaction.net_amount).label("on_hold_balance")
        ).where(
            and_(
                ChainTransaction.chain_id == chain_id,
                ChainTransaction.transaction_type == TransactionTypeEnum.SALE,
                ChainTransaction.status == TransactionStatusEnum.COMPLETED,
                ChainTransaction.created_at >= three_days_ago
            )
        )
        
        # Execute all queries
        completed_result = await self.db.execute(completed_stmt)
        platform_fees_result = await self.db.execute(platform_fees_stmt)
        total_sales_result = await self.db.execute(total_sales_stmt)
        withdrawal_result = await self.db.execute(withdrawal_stmt)
        refund_result = await self.db.execute(refund_stmt)
        pending_result = await self.db.execute(pending_stmt)
        on_hold_result = await self.db.execute(on_hold_stmt)
        
        completed_stats = completed_result.first()
        platform_fees_stats = platform_fees_result.first()
        total_sales_stats = total_sales_result.first()
        withdrawal_stats = withdrawal_result.first()
        refund_stats = refund_result.first()
        pending_stats = pending_result.first()
        on_hold_stats = on_hold_result.first()
        
        total_earned = float(completed_stats.total_earned or 0.0)
        platform_earned = float(platform_fees_stats.platform_earned or 0.0)
        total_sales = float(total_sales_stats.total_sales or 0.0)
        total_withdrawn = float(withdrawal_stats.total_withdrawn or 0.0)
        total_refunded = float(refund_stats.total_refunded or 0.0)
        pending_balance = float(pending_stats.pending_balance or 0.0)
        on_hold_balance = float(on_hold_stats.on_hold_balance or 0.0)
        
        # Available balance = total balance - pending - on hold (3-day hold)
        available_balance = chain.balance - pending_balance - on_hold_balance
        
        return ChainBalanceResponse(
            chain_id=chain.chain_id,
            chain_name=chain.chain_name,
            balance=chain.balance,
            pending_balance=pending_balance,
            on_hold_balance=on_hold_balance,
            available_balance=max(available_balance, 0.0),
            total_earned=total_earned,
            total_withdrawn=total_withdrawn,
            total_refunded=total_refunded,
            platform_earned=platform_earned,
            total_sales=total_sales
        )

    async def get_chain_transactions(
        self,
        chain_id: int,
        skip: int = 0,
        limit: int = 100,
        transaction_type: Optional[TransactionTypeEnum] = None,
        status: Optional[TransactionStatusEnum] = None
    ) -> TransactionListResponse:
        """Get transactions for a chain with filtering and pagination"""
        await self._get_chain(chain_id)  # Verify chain exists
        
        # Build query
        stmt = (
            select(ChainTransaction)
            .options(selectinload(ChainTransaction.chain))
            .where(ChainTransaction.chain_id == chain_id)
            .order_by(ChainTransaction.created_at.desc())
        )
        
        # Apply filters
        if transaction_type:
            stmt = stmt.where(ChainTransaction.transaction_type == transaction_type)
        if status:
            stmt = stmt.where(ChainTransaction.status == status)
        
        # Get total count
        count_stmt = select(func.count()).select_from(stmt.subquery())
        count_result = await self.db.execute(count_stmt)
        total = count_result.scalar() or 0
        
        # Apply pagination
        stmt = stmt.offset(skip).limit(limit)
        
        result = await self.db.execute(stmt)
        transactions = result.scalars().all()
        
        transaction_responses = []
        for tx in transactions:
            tx_dict = TransactionResponse.model_validate(tx)
            if tx.chain:
                tx_dict.chain_name = tx.chain.chain_name
            transaction_responses.append(tx_dict)
        
        return TransactionListResponse(
            transactions=transaction_responses,
            total=total,
            skip=skip,
            limit=limit
        )

    async def initiate_withdrawal(
        self,
        chain_id: int,
        withdrawal_request: WithdrawalRequest
    ) -> WithdrawalResponse:
        """
        Initiate a withdrawal from chain wallet to their Stripe Connect account.
        """
        chain = await self._get_chain(chain_id)
        
        # Check if chain has Stripe Connect account
        if not chain.stripe_account_id:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="Chain does not have a Stripe Connect account. Please set up Stripe Connect first."
            )
        
        # Check available balance (after 3-day hold period)
        balance_info = await self.get_chain_balance(chain_id)
        if withdrawal_request.amount > balance_info.available_balance:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail=f"Insufficient available balance. Available: ${balance_info.available_balance:.2f}, On Hold (3-day period): ${balance_info.on_hold_balance:.2f}, Requested: ${withdrawal_request.amount:.2f}. Funds are held for 3 days after sale before withdrawal is allowed."
            )
        
        # Ensure Stripe is configured
        self._ensure_stripe_configured()
        
        # Convert amount to cents
        amount_cents = self._amount_to_cents(withdrawal_request.amount)
        
        try:
            # Create transfer to chain's Stripe Connect account
            transfer = stripe.Transfer.create(
                amount=amount_cents,
                currency="usd",
                destination=chain.stripe_account_id,
                description=withdrawal_request.description or f"Withdrawal for {chain.chain_name}",
                metadata={
                    "chain_id": str(chain_id),
                    "chain_name": chain.chain_name
                }
            )
        except stripe.error.StripeError as exc:
            raise HTTPException(
                status_code=status.HTTP_502_BAD_GATEWAY,
                detail=f"Stripe error creating transfer: {exc.user_message or str(exc)}"
            )
        
        # Create withdrawal transaction
        transaction = ChainTransaction(
            chain_id=chain_id,
            transaction_type=TransactionTypeEnum.WITHDRAWAL,
            status=TransactionStatusEnum.COMPLETED,
            gross_amount=withdrawal_request.amount,
            stripe_fee=0.0,  # Stripe Connect transfers may have fees, but we'll track separately
            platform_fee=0.0,
            net_amount=-withdrawal_request.amount,  # Negative because it's a withdrawal
            stripe_transfer_id=transfer.id,
            stripe_account_id=chain.stripe_account_id,
            description=withdrawal_request.description or f"Withdrawal to Stripe Connect account",
            notes=f"Transfer ID: {transfer.id}",
            completed_at=datetime.utcnow()
        )
        
        self.db.add(transaction)
        
        # Deduct from chain balance
        chain.balance -= withdrawal_request.amount
        if chain.balance < 0:
            chain.balance = 0.0
        
        await self.db.commit()
        await self.db.refresh(transaction)
        
        return WithdrawalResponse(
            transaction_id=transaction.transaction_id,
            chain_id=chain_id,
            amount=withdrawal_request.amount,
            status=TransactionStatusEnum.COMPLETED,
            stripe_transfer_id=transfer.id,
            message=f"Withdrawal of ${withdrawal_request.amount:.2f} initiated successfully. Transfer ID: {transfer.id}"
        )

    async def get_all_chains_balance(self) -> List[ChainBalanceResponse]:
        """Get balance for all chains (Superadmin only)"""
        # Only get non-deleted chains
        stmt = select(Chain).where(Chain.is_deleted == False)
        result = await self.db.execute(stmt)
        chains = result.scalars().all()
        
        balances = []
        for chain in chains:
            balance = await self.get_chain_balance(chain.chain_id)
            balances.append(balance)
        
        return balances

    async def get_all_transactions(
        self,
        skip: int = 0,
        limit: int = 100,
        chain_id: Optional[int] = None,
        transaction_type: Optional[TransactionTypeEnum] = None,
        status: Optional[TransactionStatusEnum] = None
    ) -> TransactionListResponse:
        """Get all transactions across all chains (Superadmin only)"""
        stmt = (
            select(ChainTransaction)
            .options(selectinload(ChainTransaction.chain))
            .order_by(ChainTransaction.created_at.desc())
        )
        
        # Apply filters
        if chain_id:
            stmt = stmt.where(ChainTransaction.chain_id == chain_id)
        if transaction_type:
            stmt = stmt.where(ChainTransaction.transaction_type == transaction_type)
        if status:
            stmt = stmt.where(ChainTransaction.status == status)
        
        # Get total count
        count_stmt = select(func.count()).select_from(stmt.subquery())
        count_result = await self.db.execute(count_stmt)
        total = count_result.scalar() or 0
        
        # Apply pagination
        stmt = stmt.offset(skip).limit(limit)
        
        result = await self.db.execute(stmt)
        transactions = result.scalars().all()
        
        transaction_responses = []
        for tx in transactions:
            tx_dict = TransactionResponse.model_validate(tx)
            if tx.chain:
                tx_dict.chain_name = tx.chain.chain_name
            transaction_responses.append(tx_dict)
        
        return TransactionListResponse(
            transactions=transaction_responses,
            total=total,
            skip=skip,
            limit=limit
        )

    async def create_stripe_connect_account(
        self,
        chain_id: int,
        connect_request: Optional[StripeConnectCreateRequest] = None
    ) -> StripeConnectCreateResponse:
        """
        Create a Stripe Connect account for a chain and return account link for onboarding.
        """
        chain = await self._get_chain(chain_id)
        
        # Check if account already exists
        if chain.stripe_account_id:
            # Account exists, create new account link for onboarding/updates
            self._ensure_stripe_configured()
            
            try:
                account_link = stripe.AccountLink.create(
                    account=chain.stripe_account_id,
                    refresh_url=f"{os.getenv('FRONTEND_URL', 'http://localhost:3000')}/stripe-connect/refresh",
                    return_url=f"{os.getenv('FRONTEND_URL', 'http://localhost:3000')}/stripe-connect/return",
                    type="account_onboarding",
                )
                
                return StripeConnectCreateResponse(
                    chain_id=chain_id,
                    stripe_account_id=chain.stripe_account_id,
                    account_link_url=account_link.url,
                    message="Stripe Connect account already exists. Use this link to complete or update onboarding."
                )
            except stripe.error.StripeError as exc:
                raise HTTPException(
                    status_code=status.HTTP_502_BAD_GATEWAY,
                    detail=f"Stripe error creating account link: {exc.user_message or str(exc)}"
                )
        
        # Create new Stripe Connect account
        self._ensure_stripe_configured()
        
        try:
            # Create Express account (simplest for chains)
            # Country is always USA
            account_data = {
                "type": "express",
                "country": "US",
            }
            
            if connect_request and connect_request.email:
                account_data["email"] = connect_request.email
            
            account = stripe.Account.create(**account_data)
            
            # Create account link for onboarding
            account_link = stripe.AccountLink.create(
                account=account.id,
                refresh_url=f"{os.getenv('FRONTEND_URL', 'http://localhost:3000')}/stripe-connect/refresh",
                return_url=f"{os.getenv('FRONTEND_URL', 'http://localhost:3000')}/stripe-connect/return",
                type="account_onboarding",
            )
            
            # Save account ID to chain
            chain.stripe_account_id = account.id
            await self.db.commit()
            await self.db.refresh(chain)
            
            return StripeConnectCreateResponse(
                chain_id=chain_id,
                stripe_account_id=account.id,
                account_link_url=account_link.url,
                message="Stripe Connect account created. Please complete onboarding using the provided link."
            )
            
        except stripe.error.StripeError as exc:
            raise HTTPException(
                status_code=status.HTTP_502_BAD_GATEWAY,
                detail=f"Stripe error creating account: {exc.user_message or str(exc)}"
            )

    async def get_stripe_connect_status(
        self,
        chain_id: int
    ) -> StripeConnectStatusResponse:
        """
        Get Stripe Connect account status for a chain.
        """
        chain = await self._get_chain(chain_id)
        
        if not chain.stripe_account_id:
            return StripeConnectStatusResponse(
                chain_id=chain_id,
                chain_name=chain.chain_name,
                stripe_account_id=None,
                is_setup_complete=False
            )
        
        self._ensure_stripe_configured()
        
        try:
            account = stripe.Account.retrieve(chain.stripe_account_id)
            
            # Check account status
            # For Express accounts, we need charges_enabled and payouts_enabled to be True
            # details_submitted indicates if all required information was provided
            charges_enabled = getattr(account, 'charges_enabled', False) or False
            payouts_enabled = getattr(account, 'payouts_enabled', False) or False
            details_submitted = getattr(account, 'details_submitted', False) or False
            
            # Account is complete when:
            # 1. Details are submitted (onboarding form completed)
            # 2. Payouts are enabled (bank account verified and ready)
            # Charges might not always be enabled for Express accounts, but payouts are required for withdrawals
            is_setup_complete = details_submitted and payouts_enabled
            
            # Determine account status
            if payouts_enabled and details_submitted:
                account_status = "active"
            elif details_submitted:
                account_status = "pending_verification"  # Details submitted but payouts not enabled yet
            else:
                account_status = "pending"
            
            return StripeConnectStatusResponse(
                chain_id=chain_id,
                chain_name=chain.chain_name,
                stripe_account_id=chain.stripe_account_id,
                account_status=account_status,
                charges_enabled=charges_enabled,
                payouts_enabled=payouts_enabled,
                details_submitted=details_submitted,
                is_setup_complete=is_setup_complete
            )
            
        except stripe.error.StripeError as exc:
            raise HTTPException(
                status_code=status.HTTP_502_BAD_GATEWAY,
                detail=f"Stripe error retrieving account: {exc.user_message or str(exc)}"
            )

    async def create_stripe_connect_account_link(
        self,
        chain_id: int
    ) -> StripeConnectCreateResponse:
        """
        Create a new account link for existing Stripe Connect account (for re-onboarding or updates).
        """
        chain = await self._get_chain(chain_id)
        
        if not chain.stripe_account_id:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="Chain does not have a Stripe Connect account. Please create one first."
            )
        
        self._ensure_stripe_configured()
        
        try:
            account_link = stripe.AccountLink.create(
                account=chain.stripe_account_id,
                refresh_url=f"{os.getenv('FRONTEND_URL', 'http://localhost:3000')}/stripe-connect/refresh",
                return_url=f"{os.getenv('FRONTEND_URL', 'http://localhost:3000')}/stripe-connect/return",
                type="account_onboarding",
            )
            
            return StripeConnectCreateResponse(
                chain_id=chain_id,
                stripe_account_id=chain.stripe_account_id,
                account_link_url=account_link.url,
                message="Account link created. Use this link to complete or update onboarding."
            )
            
        except stripe.error.StripeError as exc:
            raise HTTPException(
                status_code=status.HTTP_502_BAD_GATEWAY,
                detail=f"Stripe error creating account link: {exc.user_message or str(exc)}"
            )
