"""
Internal service for generating MercadoPago payment links.
"""
import mercadopago
from typing import Dict, Optional


class MercadoPagoService:
    """Service for interacting with the MercadoPago API."""
    
    def __init__(self, access_token: str, local_id: Optional[str] = None):
        """
        Initializes the MercadoPago client.
        
        Args:
            access_token: MercadoPago Access Token
            local_id: MercadoPago Local ID (optional)
        """
        self.sdk = mercadopago.SDK(access_token)
        self.local_id = local_id
    
    def create_payment_link(
        self,
        title: str,
        description: str,
        amount: float,
        currency: str = "ARS",
        quantity: int = 1,
        **kwargs
    ) -> Dict:
        """
        Creates a MercadoPago payment link.
        
        Args:
            title: Product/service title
            description: Product/service description
            amount: Payment amount
            currency: Currency (default: ARS). Can be ARS, USD, EUR, BRL, MXN, etc.
            quantity: Quantity (default: 1)
            **kwargs: Additional parameters for the preference:
                - success_url: Redirect URL after successful payment (optional)
                - failure_url: Redirect URL after failed payment (optional)
                - pending_url: Redirect URL for pending payment (optional)
                - external_reference: External reference for the payment (optional)
                - expires: Expiration date (optional)
        
        Returns:
            Dict with payment link information
        """
        # Build preference_data
        preference_data = {
            "items": [
                {
                    "title": title,
                    "description": description,
                    "quantity": quantity,
                    "currency_id": currency,
                    "unit_price": float(amount)
                }
            ],
            "external_reference": kwargs.get("external_reference", self.local_id or ""),
        }
        
        # Only add back_urls if at least one URL is provided
        success_url = kwargs.get("success_url")
        failure_url = kwargs.get("failure_url")
        pending_url = kwargs.get("pending_url")
        
        if success_url or failure_url or pending_url:
            back_urls = {}
            if success_url:
                back_urls["success"] = success_url
            if failure_url:
                back_urls["failure"] = failure_url
            if pending_url:
                back_urls["pending"] = pending_url
            
            preference_data["back_urls"] = back_urls
        
        # Add additional configuration if provided
        if "expires" in kwargs:
            preference_data["expiration_date_from"] = kwargs["expires"]
        
        try:
            preference_response = self.sdk.preference().create(preference_data)
            
            # The new SDK can return different structures
            response_data = None
            
            if isinstance(preference_response, dict):
                # Can come as {"response": {...}} or directly as {...}
                if "response" in preference_response:
                    response_data = preference_response["response"]
                elif "status" in preference_response:
                    # If there's a status, it might be an error
                    if preference_response.get("status") != 201:
                        return {
                            "success": False,
                            "error": preference_response.get("message", "Unknown MercadoPago error"),
                            "status": preference_response.get("status"),
                            "response": preference_response
                        }
                    response_data = preference_response.get("response", preference_response)
                else:
                    response_data = preference_response
            else:
                response_data = preference_response
            
            # Check if creation was successful
            if response_data and isinstance(response_data, dict):
                if "id" in response_data:
                    return {
                        "success": True,
                        "payment_link": response_data.get("init_point"),
                        "preference_id": response_data.get("id"),
                        "sandbox_init_point": response_data.get("sandbox_init_point"),
                    }
                elif "status" in response_data:
                    # Error in response
                    return {
                        "success": False,
                        "error": response_data.get("message", "Error creating preference"),
                        "status": response_data.get("status"),
                        "response": response_data
                    }
            
            # If we get here, the structure is not as expected
            return {
                "success": False,
                "error": "Unexpected response from MercadoPago",
                "response": preference_response
            }
            
        except Exception as e:
            return {
                "success": False,
                "error": f"Exception: {str(e)}",
                "status": "error"
            }
