"""
Capture PayPal order function - standalone.
"""

import asyncio
from typing import Dict, Any

from apexsaas.infrastructure.paypal.client import PayPalClient
from apexsaas.infrastructure.paypal.service import PayPalService
from apexsaas.exceptions import ApexValidationError, ApexPaymentError


async def capture_order(
    order_id: str,
    client_id: str = None,
    client_secret: str = None,
    sandbox: bool = True
) -> Dict[str, Any]:
    """
    Capture a PayPal order (async).
    
    Args:
        order_id: PayPal order ID
        client_id: PayPal client ID
        client_secret: PayPal client secret
        sandbox: Use sandbox mode (default: True)
    
    Returns:
        dict with capture data:
        {
            'capture_id': str,
            'status': str,
            'amount': str,
            'currency': str,
            'payer': dict
        }
    
    Raises:
        ApexValidationError: If input validation fails
        ApexPaymentError: If PayPal API call fails
    """
    if not order_id:
        raise ApexValidationError("order_id is required")
    
    # Get credentials from environment if not provided
    import os
    client_id = client_id or os.getenv("PAYPAL_CLIENT_ID")
    client_secret = client_secret or os.getenv("PAYPAL_CLIENT_SECRET")
    
    if not client_id or not client_secret:
        raise ApexValidationError("PayPal credentials required (client_id and client_secret)")
    
    client = PayPalClient(
        client_id=client_id,
        client_secret=client_secret,
        mode="sandbox" if sandbox else "live"
    )
    service = PayPalService(client=client)
    
    result = await service.capture_order(order_id)
    
    # Extract capture details
    purchase_units = result.get("purchase_units", [])
    captures = purchase_units[0].get("payments", {}).get("captures", []) if purchase_units else []
    capture = captures[0] if captures else {}
    
    payer = result.get("payer", {})
    
    return {
        'capture_id': capture.get('id'),
        'status': capture.get('status') or result.get('status'),
        'amount': capture.get('amount', {}).get('value'),
        'currency': capture.get('amount', {}).get('currency_code'),
        'payer': {
            'name': payer.get('name', {}).get('given_name', '') + ' ' + payer.get('name', {}).get('surname', ''),
            'email': payer.get('email_address', '')
        }
    }


def capture_order_sync(
    order_id: str,
    client_id: str = None,
    client_secret: str = None,
    sandbox: bool = True
) -> Dict[str, Any]:
    """Sync wrapper for capture_order."""
    from apexsaas.core.utils.async_runner import run_async
    try:
        return run_async(capture_order(
            order_id=order_id,
            client_id=client_id,
            client_secret=client_secret,
            sandbox=sandbox
        ))
    except Exception as e:
        raise ApexPaymentError(f"Failed to capture order: {str(e)}")


