"""Stripe billing integration."""
import stripe
from typing import Optional
from datetime import datetime
from api.constants import Plan
import os

stripe.api_key = os.getenv("STRIPE_SECRET_KEY", "")


def create_stripe_customer(email: str, name: Optional[str] = None) -> str:
    """Create Stripe customer and return customer ID."""
    customer = stripe.Customer.create(
        email=email,
        name=name
    )
    return customer.id


def create_checkout_session(customer_id: str, price_id: str, success_url: str, cancel_url: str) -> str:
    """Create Stripe Checkout session and return session URL."""
    session = stripe.checkout.Session.create(
        customer=customer_id,
        payment_method_types=["card"],
        line_items=[{
            "price": price_id,
            "quantity": 1,
        }],
        mode="subscription",
        success_url=success_url,
        cancel_url=cancel_url,
    )
    return session.url


def get_subscription(customer_id: str) -> Optional[dict]:
    """Get active subscription for customer."""
    subscriptions = stripe.Subscription.list(customer=customer_id, status="active", limit=1)
    if subscriptions.data:
        return subscriptions.data[0]
    return None


def update_org_plan_from_stripe(org_id: str, stripe_customer_id: str):
    """Update organization plan from Stripe subscription."""
    from api.firestore_db import get_organization, update_organization
    
    org = get_organization(org_id)
    if not org or not stripe_customer_id:
        return
    
    subscription = get_subscription(stripe_customer_id)
    
    if subscription:
        # Map Stripe price to plan
        price_id = subscription["items"]["data"][0]["price"]["id"]
        starter_price_id = os.getenv("STRIPE_PRICE_ID_STARTER", "")
        pro_price_id = os.getenv("STRIPE_PRICE_ID_PRO", "")
        
        plan = "free"
        if "enterprise" in price_id.lower():
            plan = Plan.ENTERPRISE.value
        elif price_id == pro_price_id or "pro" in price_id.lower():
            plan = Plan.PRO.value
        elif price_id == starter_price_id or "starter" in price_id.lower():
            plan = Plan.STARTER.value
        
        update_organization(org_id, {
            'plan': plan,
            'subscription_status': subscription["status"],
            'current_period_end': datetime.fromtimestamp(subscription["current_period_end"]),
            'stripe_subscription_id': subscription["id"]
        })
    else:
        # No active subscription
        update_organization(org_id, {
            'plan': Plan.FREE.value,
            'subscription_status': 'canceled'
        })


def check_plan_access(org: dict, feature: str) -> bool:
    """Check if organization plan has access to feature."""
    # First check subscription status - must be active
    if org.get('subscription_status') != "active":
        return False
    
    plan = org.get('plan', 'free')
    
    if feature == "evidence_storage":
        return plan in [Plan.PRO.value, Plan.ENTERPRISE.value]
    elif feature == "api_access":
        return plan in [Plan.PRO.value, Plan.ENTERPRISE.value]
    elif feature == "pdf_export":
        return plan in [Plan.PRO.value, Plan.ENTERPRISE.value]
    elif feature == "regulator_portal":
        return plan == Plan.ENTERPRISE.value
    elif feature == "retention_guarantee":
        return plan == Plan.ENTERPRISE.value
    elif feature == "ai_config_generator":
        return plan in [Plan.PRO.value, Plan.ENTERPRISE.value]
    elif feature == "repo_analysis":
        return plan in [Plan.PRO.value, Plan.ENTERPRISE.value]
    elif feature == "policy_auto_selection":
        return plan in [Plan.PRO.value, Plan.ENTERPRISE.value]
    return False


def require_active_subscription(user: dict):
    """Dependency to require active subscription for premium endpoints."""
    from fastapi import HTTPException, status
    
    # Check user subscription status
    if not user.get('subscription_status') or user.get('subscription_status') != "active":
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Active subscription required. Please update your payment method or subscribe to a plan."
        )
    
    # Also check if subscription has expired
    current_period_end = user.get('current_period_end')
    if current_period_end:
        if isinstance(current_period_end, str):
            from dateutil.parser import parse
            current_period_end = parse(current_period_end)
        if current_period_end < datetime.utcnow():
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="Subscription has expired. Please renew your subscription."
            )
    
    return user

