"""
Paydunya Payment Service
Based on official Paydunya Python SDK documentation: https://developers.paydunya.com/doc/FR/Python

This service handles:
- Invoice creation for donations (one-time and recurring)
- Payment verification
- IPN (Instant Payment Notification) hash verification
"""

import logging
import hashlib
from decimal import Decimal
from django.conf import settings
from django.contrib.auth.models import User

# Import paydunya SDK
import paydunya
from paydunya import Store, Invoice as PaydunyaInvoice, InvoiceItem

logger = logging.getLogger(__name__)


class PaydunyaService:
    """
    Service class to handle all Paydunya payment operations
    """
    
    def __init__(self):
        """
        Initialize Paydunya SDK with configuration from settings
        """
        try:
            # Configure API keys
            paydunya.debug = settings.PAYDUNYA_CONFIG['MODE'] == 'test'
            paydunya.api_keys = {
                'PAYDUNYA-MASTER-KEY': settings.PAYDUNYA_CONFIG['MASTER_KEY'],
                'PAYDUNYA-PRIVATE-KEY': settings.PAYDUNYA_CONFIG['PRIVATE_KEY'],
                'PAYDUNYA-TOKEN': settings.PAYDUNYA_CONFIG['TOKEN'],
            }
            
            # Configure store information
            self.store = Store(**settings.PAYDUNYA_STORE)
            
            logger.info(f"PaydunyaService initialized in {settings.PAYDUNYA_CONFIG['MODE']} mode")
        except Exception as e:
            logger.error(f"Failed to initialize PaydunyaService: {e}")
            raise
    
    def create_donation_invoice(self, amount, user, custom_data=None, description=None):
        """
        Create a Paydunya invoice for a donation
        
        Args:
            amount (int/float): Donation amount in FCFA
            user (User): Django User object (can be guest user)
            custom_data (dict): Custom data to attach to invoice
            description (str): Optional invoice description
            
        Returns:
            tuple: (success: bool, response: dict)
        """
        try:
            # Convert amount to proper format
            amount = Decimal(str(amount))
            
            # Create invoice
            invoice = PaydunyaInvoice(self.store)
            
            # Determine user details
            user_name = user.get_full_name() or user.username or 'Donateur Anonyme'
            
            # Add invoice item
            item_name = f"Don - {user_name}"
            item_description = description or f"Don de {amount} FCFA pour ONG Enfants Soleil Sénégal"
            
            items = [
                InvoiceItem(
                    name=item_name,
                    quantity=1,
                    unit_price=str(amount),
                    total_price=str(amount),
                    description=item_description
                )
            ]
            invoice.add_items(items)
            
            # Set total amount (CRITICAL: This is what Paydunya will charge)
            invoice.total_amount = float(amount)
            
            # Add optional description
            if description:
                invoice.description = description
            
            # Add custom data if provided
            if custom_data:
                custom_data_list = [(key, value) for key, value in custom_data.items()]
                invoice.add_custom_data(custom_data_list)
            
            # Configure callback URLs
            invoice.callback_url = settings.PAYDUNYA_CALLBACK_URL
            invoice.return_url = settings.PAYDUNYA_RETURN_URL
            invoice.cancel_url = settings.PAYDUNYA_CANCEL_URL
            
            # No payment method restrictions - show all available channels
            # invoice.add_channels(['card', 'orange-money-senegal', 'wave-senegal'])
            
            # Create invoice on Paydunya servers
            successful, response = invoice.create()
            
            if successful:
                logger.info(f"Invoice created successfully: {response.get('token')}")
                return True, {
                    'success': True,
                    'token': response.get('token'),
                    'redirect_url': response.get('response_text'),  # Payment page URL
                    'response': response
                }
            else:
                # Handle response - could be string or dict
                if isinstance(response, dict):
                    error_message = response.get('response_text', 'Erreur lors de la création de la facture')
                else:
                    error_message = str(response)
                
                logger.error(f"Invoice creation failed: {error_message}")
                return False, {
                    'success': False,
                    'message': error_message,
                    'response': response
                }
                
        except Exception as e:
            logger.error(f"Error creating Paydunya invoice: {e}", exc_info=True)
            return False, {
                'success': False,
                'message': f"Erreur technique: {str(e)}"
            }
    
    def confirm_payment(self, token):
        """
        Verify payment status using invoice token
        Called after user returns from payment page
        
        Args:
            token (str): Invoice token from Paydunya
            
        Returns:
            tuple: (success: bool, response: dict)
        """
        try:
            invoice = PaydunyaInvoice(self.store)
            successful, response = invoice.confirm(token)
            
            if successful:
                logger.info(f"Payment confirmed for token {token}: Status = {response.get('status')}")
                return True, response
            else:
                logger.warning(f"Payment confirmation failed for token {token}: {response}")
                return False, response
                
        except Exception as e:
            logger.error(f"Error confirming payment for token {token}: {e}", exc_info=True)
            return False, {
                'success': False,
                'message': f"Erreur lors de la vérification du paiement: {str(e)}"
            }
    
    def verify_ipn_hash(self, received_hash):
        """
        Verify IPN notification authenticity using SHA-512 hash
        
        IMPORTANT: Always verify hash to ensure data comes from Paydunya servers
        The hash is SHA-512 of your MASTER_KEY
        
        Args:
            received_hash (str): Hash received from Paydunya IPN
            
        Returns:
            bool: True if hash is valid, False otherwise
        """
        try:
            master_key = settings.PAYDUNYA_CONFIG['MASTER_KEY']
            
            # Calculate expected hash (SHA-512 of MASTER_KEY)
            expected_hash = hashlib.sha512(master_key.encode('utf-8')).hexdigest()
            
            # Compare hashes
            is_valid = expected_hash == received_hash
            
            if is_valid:
                logger.info("IPN hash verification successful")
            else:
                logger.warning(f"IPN hash verification failed! Expected: {expected_hash[:20]}..., Received: {received_hash[:20]}...")
            
            return is_valid
            
        except Exception as e:
            logger.error(f"Error verifying IPN hash: {e}", exc_info=True)
            return False
    
    def create_subscription_invoice(self, user, giving_circle):
        """
        Create invoice for GivingCircle monthly subscription
        
        Args:
            user (User): Django User object
            giving_circle (GivingCircle): GivingCircle instance
            
        Returns:
            tuple: (success: bool, response: dict)
        """
        try:
            # Get monthly amount from GivingCircle
            amount = giving_circle.monthly_amount
            
            # Build custom data
            custom_data = {
                'user_id': user.id,
                'giving_circle_id': giving_circle.id,
                'giving_circle_name': giving_circle.name,
                'type': 'subscription',
                'is_recurring': True
            }
            
            # Build description
            description = (
                f"Don mensuel - {giving_circle.name}\n"
                f"Abonnement: {amount}€/mois\n"
                f"{giving_circle.description or ''}"
            )
            
            # Create invoice
            return self.create_donation_invoice(
                amount=amount,
                user=user,
                custom_data=custom_data,
                description=description
            )
            
        except Exception as e:
            logger.error(f"Error creating subscription invoice: {e}", exc_info=True)
            return False, {
                'success': False,
                'message': f"Erreur lors de la création de la facture d'abonnement: {str(e)}"
            }
    
    @staticmethod
    def get_guest_user():
        """
        Get or create the guest user for anonymous donations
        
        Returns:
            User: Guest user instance
        """
        guest_user, created = User.objects.get_or_create(
            username='guest',
            defaults={
                'email': 'guest@enfantsoleilmonde.org',
                'first_name': 'Invité',
                'last_name': 'Anonyme'
            }
        )
        if created:
            logger.info("Guest user created for anonymous donations")
        return guest_user
