"""
Currency Service for Multi-Currency Support
Handles currency conversion, validation, and formatting
"""

import logging
from decimal import Decimal, ROUND_HALF_UP
from typing import Tuple, Optional

from .currency_config import (
    EXCHANGE_RATES,
    CURRENCY_SYMBOLS,
    CURRENCY_NAMES,
    PROVIDER_CURRENCIES,
    MIN_AMOUNTS,
    MAX_AMOUNTS,
    WAEMU_COUNTRIES,
    CEMAC_COUNTRIES,
    EUROZONE_COUNTRIES,
    DEFAULT_CURRENCY,
)

logger = logging.getLogger(__name__)


class CurrencyService:
    """
    Service class for currency-related operations
    """
    
    @staticmethod
    def convert(amount: float, from_currency: str, to_currency: str) -> Decimal:
        """
        Convert amount from one currency to another
        
        Args:
            amount: Amount to convert
            from_currency: Source currency code (XOF, EUR, USD, etc.)
            to_currency: Target currency code
            
        Returns:
            Decimal: Converted amount rounded to 2 decimal places
            
        Example:
            >>> CurrencyService.convert(10, 'EUR', 'XOF')
            Decimal('6559.57')
        """
        if from_currency == to_currency:
            return Decimal(str(amount))
        
        # Validate currencies
        if from_currency not in EXCHANGE_RATES:
            logger.error(f"Invalid source currency: {from_currency}")
            raise ValueError(f"Unsupported currency: {from_currency}")
        
        if to_currency not in EXCHANGE_RATES:
            logger.error(f"Invalid target currency: {to_currency}")
            raise ValueError(f"Unsupported currency: {to_currency}")
        
        amount = Decimal(str(amount))
        
        # Convert to XOF first (base currency)
        if from_currency != 'XOF':
            amount_xof = amount * Decimal(str(EXCHANGE_RATES[from_currency]))
        else:
            amount_xof = amount
        
        # Convert from XOF to target currency
        if to_currency != 'XOF':
            result = amount_xof / Decimal(str(EXCHANGE_RATES[to_currency]))
        else:
            result = amount_xof
        
        # Round to 2 decimal places for display currencies, 0 for XOF
        if to_currency == 'XOF':
            return result.quantize(Decimal('1'), rounding=ROUND_HALF_UP)
        else:
            return result.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)
    
    @staticmethod
    def to_xof(amount: float, from_currency: str) -> Decimal:
        """
        Convert any currency to XOF (base currency)
        
        Args:
            amount: Amount to convert
            from_currency: Source currency code
            
        Returns:
            Decimal: Amount in XOF
        """
        return CurrencyService.convert(amount, from_currency, 'XOF')
    
    @staticmethod
    def format_amount(amount: float, currency: str) -> str:
        """
        Format amount with proper currency symbol and thousand separators
        
        Args:
            amount: Amount to format
            currency: Currency code
            
        Returns:
            str: Formatted amount (e.g., "5 000 FCFA", "10.00 €", "$25.50")
            
        Example:
            >>> CurrencyService.format_amount(5000, 'XOF')
            '5 000 FCFA'
            >>> CurrencyService.format_amount(10.5, 'EUR')
            '10.50 €'
        """
        amount = float(amount)
        symbol = CURRENCY_SYMBOLS.get(currency, currency)
        
        if currency == 'XOF':
            # No decimals for XOF, space as thousand separator
            formatted = f"{int(amount):,}".replace(',', ' ')
            return f"{formatted} {symbol}"
        else:
            # 2 decimals for other currencies
            if currency == 'EUR':
                # European style: amount before symbol
                return f"{amount:,.2f} {symbol}".replace(',', ' ')
            else:
                # US/UK style: symbol before amount
                return f"{symbol}{amount:,.2f}"
    
    @staticmethod
    def get_exchange_rate(currency: str) -> Decimal:
        """
        Get exchange rate for currency relative to XOF
        
        Args:
            currency: Currency code
            
        Returns:
            Decimal: Exchange rate (1 CURRENCY = X XOF)
        """
        return Decimal(str(EXCHANGE_RATES.get(currency, 1.0)))
    
    @staticmethod
    def provider_supports_currency(provider: str, currency: str) -> bool:
        """
        Check if payment provider supports the given currency
        
        Args:
            provider: Payment provider name ('paytech' or 'paydunya')
            currency: Currency code
            
        Returns:
            bool: True if provider supports currency
            
        Example:
            >>> CurrencyService.provider_supports_currency('paytech', 'XOF')
            True
            >>> CurrencyService.provider_supports_currency('paytech', 'EUR')
            False
        """
        supported_currencies = PROVIDER_CURRENCIES.get(provider, [])
        return currency in supported_currencies
    
    @staticmethod
    def get_provider_currency(provider: str, requested_currency: str) -> Tuple[str, bool]:
        """
        Determine which currency to use for payment provider
        If provider doesn't support requested currency, fallback to XOF with conversion
        
        Args:
            provider: Payment provider name
            requested_currency: User's preferred currency
            
        Returns:
            tuple: (currency_to_use, needs_conversion)
            
        Example:
            >>> CurrencyService.get_provider_currency('paytech', 'EUR')
            ('XOF', True)
            >>> CurrencyService.get_provider_currency('paydunya', 'EUR')
            ('EUR', False)
        """
        if CurrencyService.provider_supports_currency(provider, requested_currency):
            logger.debug(f"{provider} supports {requested_currency} - no conversion needed")
            return (requested_currency, False)
        else:
            logger.info(
                f"{provider} doesn't support {requested_currency}, "
                f"will convert to XOF"
            )
            return ('XOF', True)
    
    @staticmethod
    def detect_currency_from_country(country_code: str) -> str:
        """
        Detect default currency based on country code
        
        Args:
            country_code: ISO 2-letter country code (from django-countries)
            
        Returns:
            str: Currency code (XOF, EUR, USD, etc.)
            
        Example:
            >>> CurrencyService.detect_currency_from_country('SN')
            'XOF'
            >>> CurrencyService.detect_currency_from_country('FR')
            'EUR'
        """
        if not country_code:
            return DEFAULT_CURRENCY
        
        country_code = country_code.upper()
        
        # West African CFA countries
        if country_code in WAEMU_COUNTRIES or country_code in CEMAC_COUNTRIES:
            return 'XOF'
        
        # Eurozone countries
        if country_code in EUROZONE_COUNTRIES:
            return 'EUR'
        
        # Specific countries
        if country_code == 'GB':
            return 'GBP'
        elif country_code == 'US':
            return 'USD'
        elif country_code == 'CA':
            return 'CAD'
        else:
            # Default to EUR for international users
            return DEFAULT_CURRENCY
    
    @staticmethod
    def validate_amount(amount: float, currency: str) -> Tuple[bool, Optional[str]]:
        """
        Validate if amount is within acceptable range for currency
        
        Args:
            amount: Amount to validate
            currency: Currency code
            
        Returns:
            tuple: (is_valid, error_message)
            
        Example:
            >>> CurrencyService.validate_amount(500, 'XOF')
            (False, 'Le montant minimum est 1 000 FCFA')
        """
        min_amount = MIN_AMOUNTS.get(currency, 0)
        max_amount = MAX_AMOUNTS.get(currency, float('inf'))
        
        if amount < min_amount:
            formatted_min = CurrencyService.format_amount(min_amount, currency)
            return (False, f"Le montant minimum est {formatted_min}")
        
        if amount > max_amount:
            formatted_max = CurrencyService.format_amount(max_amount, currency)
            return (False, f"Le montant maximum est {formatted_max}")
        
        return (True, None)
    
    @staticmethod
    def get_currency_info(currency: str) -> dict:
        """
        Get comprehensive information about a currency
        
        Args:
            currency: Currency code
            
        Returns:
            dict: Currency information including symbol, name, rates, etc.
        """
        return {
            'code': currency,
            'symbol': CURRENCY_SYMBOLS.get(currency, currency),
            'name': CURRENCY_NAMES.get(currency, currency),
            'min_amount': MIN_AMOUNTS.get(currency, 0),
            'max_amount': MAX_AMOUNTS.get(currency, 0),
            'exchange_rate': float(EXCHANGE_RATES.get(currency, 1.0)),
        }
