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


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.
    
    Args:
        product_id: Product ID
        name: Plan name
        description: Plan description
        billing_cycles: Billing cycle configuration
        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
                }
            }
        }]
    
    async def _create():
        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")
        
        return await service.create_plan(
            product_id=final_product_id,
            name=name,
            description=description,
            billing_cycles=billing_cycles
        )
    
    try:
        result = asyncio.run(_create())
        # 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
    except Exception as e:
        raise ApexPaymentError(f"Failed to create subscription plan: {str(e)}")


