"""
Get 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


def get_order(
    order_id: str,
    client_id: str = None,
    client_secret: str = None,
    sandbox: bool = True
) -> Dict[str, Any]:
    """
    Get PayPal order details.
    
    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 order data
    
    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)")
    
    async def _get():
        client = PayPalClient(
            client_id=client_id,
            client_secret=client_secret,
            mode="sandbox" if sandbox else "live"
        )
        service = PayPalService(client=client)
        
        return await service.get_order(order_id)
    
    try:
        result = asyncio.run(_get())
        # Ensure order_id is in the response
        if 'order_id' not in result and 'id' in result:
            result['order_id'] = result['id']
        elif 'order_id' not in result:
            # If order_id not found, add it from the function parameter
            result['order_id'] = order_id
        return result
    except Exception as e:
        raise ApexPaymentError(f"Failed to get order: {str(e)}")


