"""
Subscription Management API Routes
Handles subscription plans, user subscriptions, and subscription operations
"""

from flask import Blueprint, request, jsonify, g
from services.subscription_manager import SubscriptionManager
from utils.decorators import require_api_key, require_admin
from utils.response_helpers import create_success_response, create_error_response
import logging

logger = logging.getLogger(__name__)

subscription_bp = Blueprint('subscription', __name__)


# ============================================================================
# PUBLIC ENDPOINTS - Subscription Plans
# ============================================================================

@subscription_bp.route('/api/subscriptions/types', methods=['GET'])
def get_subscription_types():
    """Get all available subscription types"""
    from database import get_db_connection
    
    try:
        conn = get_db_connection()
        cursor = conn.cursor(dictionary=True)
        
        cursor.execute("""
            SELECT * FROM subscription_types
            WHERE is_active = TRUE
            ORDER BY display_order ASC
        """)
        
        types = cursor.fetchall()
        
        return create_success_response(
            data={'subscription_types': types},
            message='Subscription types retrieved successfully'
        )
        
    except Exception as e:
        logger.error(f"Error getting subscription types: {e}")
        return create_error_response(str(e))
    finally:
        if conn:
            conn.close()


@subscription_bp.route('/api/subscriptions/plans', methods=['GET'])
def get_subscription_plans():
    """Get all available subscription plans, optionally filtered by type"""
    from database import get_db_connection
    import json
    
    subscription_type = request.args.get('type')  # e.g., 'ai_tokens'
    
    try:
        conn = get_db_connection()
        cursor = conn.cursor(dictionary=True)
        
        query = """
            SELECT sp.*, st.type_key, st.type_name, st.icon, st.color
            FROM subscription_plans sp
            JOIN subscription_types st ON sp.subscription_type_id = st.id
            WHERE sp.is_active = TRUE
        """
        
        params = []
        if subscription_type:
            query += " AND st.type_key = %s"
            params.append(subscription_type)
        
        query += " ORDER BY sp.display_order ASC"
        
        cursor.execute(query, params if params else None)
        plans = cursor.fetchall()
        
        # Parse JSON fields
        for plan in plans:
            if plan.get('benefits'):
                plan['benefits'] = json.loads(plan['benefits']) if isinstance(plan['benefits'], str) else plan['benefits']
            if plan.get('features_list'):
                plan['features_list'] = json.loads(plan['features_list']) if isinstance(plan['features_list'], str) else plan['features_list']
        
        return create_success_response(
            data={'plans': plans},
            message='Subscription plans retrieved successfully'
        )
        
    except Exception as e:
        logger.error(f"Error getting subscription plans: {e}")
        return create_error_response(str(e))
    finally:
        if conn:
            conn.close()


@subscription_bp.route('/api/subscriptions/plans/<int:plan_id>', methods=['GET'])
def get_plan_details(plan_id):
    """Get detailed information about a specific plan"""
    from database import get_db_connection
    import json
    
    try:
        conn = get_db_connection()
        cursor = conn.cursor(dictionary=True)
        
        cursor.execute("""
            SELECT sp.*, st.type_key, st.type_name, st.description as type_description,
                   st.icon, st.color, st.category
            FROM subscription_plans sp
            JOIN subscription_types st ON sp.subscription_type_id = st.id  
            WHERE sp.id = %s
        """, (plan_id,))
        
        plan = cursor.fetchone()
        
        if not plan:
            return create_error_response('Plan not found', status_code=404)
        
        # Parse JSON fields
        if plan.get('benefits'):
            plan['benefits'] = json.loads(plan['benefits']) if isinstance(plan['benefits'], str) else plan['benefits']
        if plan.get('features_list'):
            plan['features_list'] = json.loads(plan['features_list']) if isinstance(plan['features_list'], str) else plan['features_list']
        
        return create_success_response(
            data={'plan': plan},
            message='Plan details retrieved successfully'
        )
        
    except Exception as e:
        logger.error(f"Error getting plan details: {e}")
        return create_error_response(str(e))
    finally:
        if conn:
            conn.close()


# ============================================================================
# USER ENDPOINTS - Subscription Management
# ============================================================================

@subscription_bp.route('/api/subscriptions/my-subscriptions', methods=['GET'])
@require_api_key
def get_my_subscriptions():
    """Get current user's active subscriptions"""
    user_id = g.current_user_id
    subscription_type = request.args.get('type')
    
    subscriptions = SubscriptionManager.get_user_subscriptions(
        user_id=user_id,
        subscription_type=subscription_type,
        active_only=True
    )
    
    return create_success_response(
        data={'subscriptions': subscriptions},
        message='Your subscriptions retrieved successfully'
    )


@subscription_bp.route('/api/subscriptions/subscribe', methods=['POST'])
@require_api_key
def create_subscription():
    """Subscribe to a plan"""
    user_id = g.current_user_id
    data = request.get_json()
    
    plan_id = data.get('plan_id')
    billing_cycle = data.get('billing_cycle', 'monthly')
    payment_data = data.get('payment_data')
    
    if not plan_id:
        return create_error_response('plan_id is required', status_code=400)
    
    result = SubscriptionManager.create_subscription(
        user_id=user_id,
        plan_id=plan_id,
        billing_cycle=billing_cycle,
        payment_data=payment_data
    )
    
    if result['success']:
        return create_success_response(
            data=result,
            message=result.get('message', 'Subscription created successfully')
        )
    else:
        return create_error_response(
            result.get('message', 'Failed to create subscription'),
            status_code=400
        )


@subscription_bp.route('/api/subscriptions/<int:subscription_id>/cancel', methods=['POST'])
@require_api_key
def cancel_subscription(subscription_id):
    """Cancel a subscription"""
    user_id = g.current_user_id
    data = request.get_json() or {}
    
    reason = data.get('reason')
    immediate = data.get('immediate', False)
    
    result = SubscriptionManager.cancel_subscription(
        user_id=user_id,
        subscription_id=subscription_id,
        reason=reason,
        immediate=immediate
    )
    
    if result['success']:
        return create_success_response(
            data=result,
            message=result.get('message', 'Subscription cancelled successfully')
        )
    else:
        return create_error_response(
            result.get('message', 'Failed to cancel subscription'),
            status_code=400
        )


@subscription_bp.route('/api/subscriptions/check-access', methods=['POST'])
@require_api_key
def check_subscription_access():
    """Check if user has required subscription access"""
    user_id = g.current_user_id
    data = request.get_json()
    
    required_benefit = data.get('required_benefit')
    
    if not required_benefit:
        return create_error_response('required_benefit is required', status_code=400)
    
    result = SubscriptionManager.check_subscription_access(
        user_id=user_id,
        required_benefit=required_benefit
    )
    
    return create_success_response(
        data=result,
        message='Access check completed'
    )


@subscription_bp.route('/api/subscriptions/benefits/<subscription_type>', methods=['GET'])
@require_api_key
def get_my_benefits(subscription_type):
    """Get aggregated benefits for a subscription type"""
    user_id = g.current_user_id
    
    benefits = SubscriptionManager.get_subscription_benefits(
        user_id=user_id,
        subscription_type=subscription_type
    )
    
    return create_success_response(
        data={'benefits': benefits},
        message=f'Benefits for {subscription_type} retrieved successfully'
    )


# ==================================================================
# ADMIN ENDPOINTS
# ============================================================================

@subscription_bp.route('/api/admin/subscriptions/reset-allowances', methods=['POST'])
@require_admin
def admin_reset_monthly_allowances():
    """Manually trigger monthly allowance reset (admin only)"""
    result = SubscriptionManager.reset_monthly_allowances()
    
    if result['success']:
        return create_success_response(
            data=result,
            message=f'Reset allowances for {result["reset_count"]} subscriptions'
        )
    else:
        return create_error_response(
            result.get('message', 'Failed to reset allowances'),
            status_code=500
        )
