"""
PayTech Payment Gateway Service
Based on official PayTech documentation: https://doc.intech.sn/doc_paytech.php
"""

import requests
import hashlib
import hmac
import json
import logging
from django.conf import settings

logger = logging.getLogger(__name__)


class PaytechService:
    """
    Service class for PayTech API integration
    Documentation: https://doc.intech.sn/doc_paytech.php
    """
    
    def __init__(self):
        self.api_key = settings.PAYTECH_API_KEY
        self.api_secret = settings.PAYTECH_API_SECRET
        self.base_url = settings.PAYTECH_BASE_URL
        self.env = settings.PAYTECH_ENV
        
    def request_payment(self, item_name, item_price, ref_command, command_name, 
                       custom_field=None, target_payment=None, user=None):
        """
        Create a payment request with PayTech
        
        Args:
            item_name (str): Name of the product/service
            item_price (int): Price in XOF
            ref_command (str): Unique reference for the command
            command_name (str): Description of the command
            custom_field (dict): Additional custom data (will be JSON encoded)
            target_payment (str): Payment method(s) - "Orange Money", "Wave", etc.
            user (User): Django User object for auto-fill (requires phone_number attribute)
            
        Returns:
            dict: Response from PayTech API
        """
        url = f'{self.base_url}/payment/request-payment'
        
        payload = {
            'item_name': item_name,
            'item_price': item_price,
            'currency': 'xof',
            'ref_command': ref_command,
            'command_name': command_name,
            'env': self.env,
            'ipn_url': settings.PAYTECH_IPN_URL,
            'success_url': settings.PAYTECH_SUCCESS_URL,
            'cancel_url': settings.PAYTECH_CANCEL_URL,
        }
        
        # Add custom field if provided
        if custom_field:
            payload['custom_field'] = json.dumps(custom_field)
        
        # Add target payment method if specified
        if target_payment:
            payload['target_payment'] = target_payment
        
        headers = {
            'API_KEY': self.api_key,
            'API_SECRET': self.api_secret,
            'Content-Type': 'application/json'
        }
        
        try:
            logger.info(f"PayTech payment request: {ref_command} - {item_price} XOF")
            response = requests.post(url, json=payload, headers=headers, timeout=30)
            response.raise_for_status()
            
            json_response = response.json()
            logger.info(f"PayTech response: {json_response.get('success')} - {json_response.get('token')}")
            
            # Add auto-fill parameters if single payment method and user provided
            if (json_response.get('success') == 1 and user and target_payment and 
                ',' not in target_payment):
                redirect_url = json_response.get('redirect_url', '')
                
                # Build auto-fill parameters
                auto_fill_params = self._build_autofill_params(user, target_payment)
                
                # Append to redirect URL
                from urllib.parse import urlencode
                query_string = urlencode(auto_fill_params)
                json_response['redirect_url'] = f"{redirect_url}?{query_string}"
                json_response['redirectUrl'] = json_response['redirect_url']
                
                logger.info(f"Auto-fill enabled for {target_payment}")
            
            return json_response
            
        except requests.exceptions.RequestException as e:
            logger.error(f"PayTech API error: {str(e)}")
            return {
                'success': 0,
                'message': f'Erreur de connexion à PayTech: {str(e)}'
            }
        except Exception as e:
            logger.error(f"Unexpected error: {str(e)}")
            return {
                'success': 0,
                'message': f'Erreur inattendue: {str(e)}'
            }
    
    def _build_autofill_params(self, user, target_payment):
        """
        Build auto-fill parameters for single payment method
        Documentation: https://doc.intech.sn/doc_paytech.php#pre-remplissage
        
        Args:
            user: Django User object with phone_number, first_name, last_name
            target_payment (str): Payment method name
            
        Returns:
            dict: Auto-fill parameters
        """
        # Get user phone number (assuming it's stored in user profile or user model)
        phone_number = getattr(user, 'phone_number', None)
        if not phone_number:
            # Try to get from related profile
            try:
                phone_number = user.userprofile.phone_number if hasattr(user, 'userprofile') else None
            except Exception as e:
                logger.debug(f"Could not access user profile: {e}")
                phone_number = None
        
        if not phone_number:
            logger.warning(f"No phone number found for user {user.username}")
            return {}
        
        # Format phone number (should be +221XXXXXXXXX)
        if not phone_number.startswith('+'):
            phone_number = f'+221{phone_number}'
        
        # Extract national number (without country code)
        national_number = phone_number[4:] if phone_number.startswith('+221') else phone_number
        
        # Full name
        full_name = f"{user.first_name} {user.last_name}".strip() or user.username
        
        # Auto-submit: 0 for manual (Carte Bancaire), 1 for auto
        nac = 0 if target_payment == 'Carte Bancaire' else 1
        
        return {
            'pn': phone_number,           # +221777777777
            'nn': national_number,         # 777777777
            'fn': full_name,               # John Smith
            'tp': target_payment,          # Orange Money
            'nac': nac                     # Auto-submit flag
        }
    
    def verify_ipn_hmac(self, ipn_data):
        """
        Verify IPN notification using HMAC-SHA256 (Recommended method)
        Documentation: https://doc.intech.sn/doc_paytech.php#notifications-ipn
        
        Args:
            ipn_data (dict): IPN notification data from PayTech
            
        Returns:
            bool: True if verification successful
        """
        try:
            received_hmac = ipn_data.get('hmac_compute')
            if not received_hmac:
                logger.warning("No HMAC in IPN notification")
                return False
            
            # Determine if it's a payment or transfer notification
            if 'ref_command' in ipn_data:
                # Payment notification: amount|ref_command|api_key
                message = f"{ipn_data.get('item_price')}|{ipn_data.get('ref_command')}|{self.api_key}"
            elif 'id_transfer' in ipn_data:
                # Transfer notification: amount|id_transfer|api_key
                message = f"{ipn_data.get('amount')}|{ipn_data.get('id_transfer')}|{self.api_key}"
            else:
                logger.warning("Unknown IPN notification type")
                return False
            
            # Calculate expected HMAC
            expected_hmac = hmac.new(
                self.api_secret.encode('utf-8'),
                message.encode('utf-8'),
                hashlib.sha256
            ).hexdigest()
            
            is_valid = hmac.compare_digest(expected_hmac, received_hmac)
            
            if not is_valid:
                logger.warning(f"HMAC verification failed. Expected: {expected_hmac}, Received: {received_hmac}")
            
            return is_valid
            
        except Exception as e:
            logger.error(f"HMAC verification error: {str(e)}")
            return False
    
    def verify_ipn_sha256(self, api_key_sha256, api_secret_sha256):
        """
        Verify IPN notification using SHA256 hashes (Classic method)
        Documentation: https://doc.intech.sn/doc_paytech.php#notifications-ipn
        
        Args:
            api_key_sha256 (str): SHA256 hash of API key from IPN
            api_secret_sha256 (str): SHA256 hash of API secret from IPN
            
        Returns:
            bool: True if verification successful
        """
        try:
            expected_key_hash = hashlib.sha256(self.api_key.encode('utf-8')).hexdigest()
            expected_secret_hash = hashlib.sha256(self.api_secret.encode('utf-8')).hexdigest()
            
            is_valid = (expected_key_hash == api_key_sha256 and 
                        expected_secret_hash == api_secret_sha256)
            
            if not is_valid:
                logger.warning("SHA256 verification failed")
            
            return is_valid
            
        except Exception as e:
            logger.error(f"SHA256 verification error: {str(e)}")
            return False
    
    def get_payment_status(self, token_payment):
        """
        Get payment status from PayTech
        Documentation: https://doc.intech.sn/doc_paytech.php#apis-de-statut
        
        Args:
            token_payment (str): Payment token from PayTech
            
        Returns:
            dict: Payment status response
        """
        url = f'{self.base_url}/payment/get-status'
        params = {'token_payment': token_payment}
        headers = {
            'API_KEY': self.api_key,
            'API_SECRET': self.api_secret
        }
        
        try:
            response = requests.get(url, params=params, headers=headers, timeout=30)
            response.raise_for_status()
            return response.json()
        except Exception as e:
            logger.error(f"Error getting payment status: {str(e)}")
            return {'success': 0, 'message': str(e)}
    
    def request_refund(self, ref_command):
        """
        Request a refund for a payment
        Documentation: https://doc.intech.sn/doc_paytech.php#api-de-remboursement
        
        Args:
            ref_command (str): Reference of the command to refund
            
        Returns:
            dict: Refund response
        """
        url = f'{self.base_url}/payment/refund-payment'
        payload = {'ref_command': ref_command}
        headers = {
            'API_KEY': self.api_key,
            'API_SECRET': self.api_secret,
            'Content-Type': 'application/x-www-form-urlencoded'
        }
        
        try:
            response = requests.post(url, data=payload, headers=headers, timeout=30)
            response.raise_for_status()
            return response.json()
        except Exception as e:
            logger.error(f"Error requesting refund: {str(e)}")
            return {'success': -1, 'message': str(e)}
