"""
Get PayPal subscription 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 get_subscription(
    subscription_id: str,
    client_id: str = None,
    client_secret: str = None,
    sandbox: bool = True
) -> Dict[str, Any]:
    """
    Get PayPal subscription details (async).
    
    Args:
        subscription_id: Subscription ID
        client_id: PayPal client ID
        client_secret: PayPal client secret
        sandbox: Use sandbox mode (default: True)
    
    Returns:
        dict with subscription data
    
    Raises:
        ApexValidationError: If input validation fails
        ApexPaymentError: If PayPal API call fails
    """
    if not subscription_id:
        raise ApexValidationError("subscription_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)
    
    return await service.get_subscription(subscription_id)


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