# services/stripe_service.py

import stripe
import os
from flask import current_app

def init_stripe(app):
    """Initialize Stripe with Flask app"""
    # Get environment variables directly (not from app.config which isn't set yet)
    stripe_secret = os.environ.get('STRIPE_SECRET_KEY')
    stripe_public = os.environ.get('STRIPE_PUBLISHABLE_KEY')
    stripe_webhook = os.environ.get('STRIPE_WEBHOOK_SECRET')
    
    print(f"🔧 Initializing Stripe...")
    print(f"   Secret key found: {'YES' if stripe_secret else 'NO'}")
    print(f"   Public key found: {'YES' if stripe_public else 'NO'}")
    print(f"   Webhook secret found: {'YES' if stripe_webhook else 'NO'}")
    
    if not stripe_secret:
        print("⚠️  WARNING: STRIPE_SECRET_KEY not found - Stripe features will be disabled")
        print("   Set STRIPE_SECRET_KEY in .env to enable subscription features")
        app.config['STRIPE_ENABLED'] = False
        app.config['STRIPE_PUBLISHABLE_KEY'] = None
        app.config['STRIPE_SECRET_KEY'] = None
        app.config['STRIPE_WEBHOOK_SECRET'] = None
        return  # Exit gracefully without initializing Stripe

    if not stripe_secret.startswith(('sk_test_', 'sk_live_')):
        print("❌ ERROR: Invalid STRIPE_SECRET_KEY format!")
        print("   Stripe features will be disabled")
        app.config['STRIPE_ENABLED'] = False
        return  # Exit gracefully
    
    # Set Stripe API key FIRST (this was the bug - was using app.config before it was set)
    stripe.api_key = stripe_secret

    # Now set Flask config for later use
    app.config['STRIPE_ENABLED'] = True
    app.config['STRIPE_PUBLISHABLE_KEY'] = stripe_public
    app.config['STRIPE_SECRET_KEY'] = stripe_secret
    app.config['STRIPE_WEBHOOK_SECRET'] = stripe_webhook

    key_type = 'LIVE' if stripe_secret.startswith('sk_live_') else 'TEST'
    print(f"✅ Stripe initialized successfully with {key_type} keys")
    
    if key_type == 'LIVE':
        print("⚠️  WARNING: Using LIVE Stripe keys - real payments will be processed!")

class StripeService:
    """Service class for Stripe operations"""

    @staticmethod
    def create_customer(user):
        """Create a Stripe customer"""
        try:
            customer = stripe.Customer.create(
                email=user.email,
                name=f"{user.first_name} {user.last_name}",
                metadata={
                    'user_id': user.id,
                    'username': user.username,
                    'service': 'lawbot',
                    'source': 'lawbot_app'
                }
            )
            return customer
        except stripe.error.StripeError as e:
            current_app.logger.error(f"Stripe customer creation failed: {str(e)}")
            return None

    @staticmethod
    def create_subscription(customer_id, price_id, user_id):
        """Create a Stripe subscription"""
        try:
            subscription = stripe.Subscription.create(
                customer=customer_id,
                items=[{'price': price_id}],
                payment_behavior='default_incomplete',
                payment_settings={'save_default_payment_method': 'on_subscription'},
                expand=['latest_invoice.payment_intent'],
                metadata={
                    'user_id': user_id,
                    'service': 'lawbot',
                    'product_type': 'lawbot_subscription'
                }
            )
            return subscription
        except stripe.error.StripeError as e:
            current_app.logger.error(f"Stripe subscription creation failed: {str(e)}")
            return None

    @staticmethod
    def cancel_subscription(subscription_id, cancel_at_period_end=True):
        """Cancel a Stripe subscription"""
        try:
            subscription = stripe.Subscription.modify(
                subscription_id,
                cancel_at_period_end=cancel_at_period_end
            )
            return subscription
        except stripe.error.StripeError as e:
            current_app.logger.error(f"Stripe subscription cancellation failed: {str(e)}")
            return None

    @staticmethod
    def create_billing_portal_session(customer_id, return_url):
        """Create a billing portal session"""
        try:
            session = stripe.billing_portal.Session.create(
                customer=customer_id,
                return_url=return_url,
            )
            return session
        except stripe.error.StripeError as e:
            current_app.logger.error(f"Billing portal session creation failed: {str(e)}")
            return None

    @staticmethod
    def create_checkout_session(price_id, customer_id, success_url, cancel_url, user_id):
        """Create a Stripe checkout session"""
        try:
            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,
                metadata={
                    'user_id': user_id,
                    'service': 'lawbot'
                }
            )
            return session
        except stripe.error.StripeError as e:
            current_app.logger.error(f"Checkout session creation failed: {str(e)}")
            return None

    @staticmethod
    def retrieve_subscription(subscription_id):
        """Retrieve a Stripe subscription"""
        try:
            return stripe.Subscription.retrieve(subscription_id)
        except stripe.error.StripeError as e:
            current_app.logger.error(f"Subscription retrieval failed: {str(e)}")
            return None
