"""
Create PayPal subscription plan function - standalone.
"""

import asyncio
from typing import Dict, Any, List

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


async def create_subscription_plan(
    name: str,
    description: str,
    amount: str,
    currency: str = "USD",
    billing_cycle: str = "MONTH",
    product_id: str = None,
    billing_cycles: List[Dict[str, Any]] = None,
    client_id: str = None,
    client_secret: str = None,
    sandbox: bool = True
) -> Dict[str, Any]:
    """
    Create a PayPal subscription plan (async).
    
    Args:
        name: Plan name
        description: Plan description
        amount: Plan amount
        currency: Currency code (default: "USD")
        billing_cycle: Billing cycle (MONTH or YEAR)
        product_id: Product ID (optional, will create if not provided)
        billing_cycles: Billing cycle configuration (optional)
        client_id: PayPal client ID
        client_secret: PayPal client secret
        sandbox: Use sandbox mode (default: True)
    
    Returns:
        dict with plan data
    
    Raises:
        ApexValidationError: If input validation fails
        ApexPaymentError: If PayPal API call fails
    """
    if not name:
        raise ApexValidationError("name is required")
    if not amount:
        raise ApexValidationError("amount 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)")
    
    # Build billing cycles if not provided
    if not billing_cycles:
        billing_cycles = [{
            "frequency": {
                "interval_unit": billing_cycle,
                "interval_count": 1
            },
            "tenure_type": "REGULAR",
            "sequence": 1,
            "total_cycles": 0,  # 0 means infinite
            "pricing_scheme": {
                "fixed_price": {
                    "value": amount,
                    "currency_code": currency
                }
            }
        }]
    
    client = PayPalClient(
        client_id=client_id,
        client_secret=client_secret,
        mode="sandbox" if sandbox else "live"
    )
    service = PayPalService(client=client)
    
    # Create product first if product_id not provided
    final_product_id = product_id
    if not final_product_id:
        product = await service.create_product(name=name, description=description)
        final_product_id = product.get("id")
    
    result = await service.create_plan(
        product_id=final_product_id,
        name=name,
        description=description,
        billing_cycles=billing_cycles
    )
    
    # Ensure plan_id is in the response
    if 'plan_id' not in result and 'id' in result:
        result['plan_id'] = result['id']
    # Add name, amount, currency for compatibility
    if 'name' not in result:
        result['name'] = name
    if 'amount' not in result:
        result['amount'] = amount
    if 'currency' not in result:
        result['currency'] = currency
    return result


def create_subscription_plan_sync(
    name: str,
    description: str,
    amount: str,
    currency: str = "USD",
    billing_cycle: str = "MONTH",
    product_id: str = None,
    billing_cycles: List[Dict[str, Any]] = None,
    client_id: str = None,
    client_secret: str = None,
    sandbox: bool = True
) -> Dict[str, Any]:
    """Sync wrapper for create_subscription_plan."""
    from apexsaas.core.utils.async_runner import run_async
    try:
        return run_async(create_subscription_plan(
            name=name,
            description=description,
            amount=amount,
            currency=currency,
            billing_cycle=billing_cycle,
            product_id=product_id,
            billing_cycles=billing_cycles,
            client_id=client_id,
            client_secret=client_secret,
            sandbox=sandbox
        ))
    except Exception as e:
        raise ApexPaymentError(f"Failed to create subscription plan: {str(e)}")
