"""
API routes - Public API endpoints
"""
from flask import Blueprint, jsonify, request
from app import db, limiter
from app.models import User, Instance
from datetime import datetime, timedelta

api_bp = Blueprint('api', __name__)


@api_bp.route('/health', methods=['GET'])
def health():
    """Health check endpoint"""
    try:
        # Test database
        db.session.execute(db.text('SELECT 1'))

        return jsonify({
            'status': 'healthy',
            'timestamp': datetime.utcnow().isoformat(),
            'database': 'connected'
        }), 200
    except Exception as e:
        return jsonify({
            'status': 'unhealthy',
            'error': str(e)
        }), 503


@api_bp.route('/stats', methods=['GET'])
def stats():
    """Public platform statistics"""
    total_users = User.query.count()
    active_users = User.query.filter(
        User.subscription_expires_at > datetime.utcnow()
    ).count()
    total_instances = Instance.query.count()
    running_instances = Instance.query.filter_by(status='running').count()

    return jsonify({
        'total_users': total_users,
        'active_users': active_users,
        'total_instances': total_instances,
        'running_instances': running_instances
    })


@api_bp.route('/pricing', methods=['GET'])
def pricing():
    """Get pricing information"""
    return jsonify({
        'plans': [
            {
                'name': 'Free',
                'price': 0,
                'instances': 1,
                'features': [
                    'Basic voice assistant',
                    'Web speech STT',
                    'Basic TTS',
                    'Limited canvas pages'
                ]
            },
            {
                'name': 'Pro',
                'price': 29,
                'period': 'month',
                'instances': 3,
                'features': [
                    'Everything in Free',
                    'Priority support',
                    'Better TTS voices',
                    'Unlimited canvas',
                    'Google Calendar integration',
                    'Gmail integration',
                    'Usage analytics'
                ]
            },
            {
                'name': 'Enterprise',
                'price': 'Custom',
                'instances': 'Unlimited',
                'features': [
                    'Everything in Pro',
                    'Custom integrations',
                    'SLA guarantee',
                    'Dedicated support',
                    'White-label options',
                    'API access'
                ]
            }
        ]
    })


@api_bp.route('/features', methods=['GET'])
def features():
    """Get feature list"""
    return jsonify({
        'features': {
            'voice': {
                'name': 'Voice Control',
                'description': 'Hands-free voice control with live transcription',
                'available': ['free', 'pro', 'enterprise']
            },
            'canvas': {
                'name': 'Live Canvas',
                'description': 'AI renders real HTML pages in real-time',
                'available': ['free', 'pro', 'enterprise']
            },
            'calendar': {
                'name': 'Google Calendar',
                'description': 'Voice-controlled calendar management',
                'available': ['pro', 'enterprise']
            },
            'gmail': {
                'name': 'Gmail Integration',
                'description': 'Read and compose emails by voice',
                'available': ['pro', 'enterprise']
            },
            'music': {
                'name': 'AI Music Generation',
                'description': 'Generate songs on the fly with Suno',
                'available': ['enterprise']
            },
            '3d_ui': {
                'name': '3D Holographic UI',
                'description': 'Jarvis-inspired Iron Man HUD interface',
                'available': ['pro', 'enterprise']
            },
            'custom_persona': {
                'name': 'Custom Personas',
                'description': 'Create custom agent personalities',
                'available': ['enterprise']
            }
        }
    })


@api_bp.route('/webhooks/stripe', methods=['POST'])
@limiter.limit("10/minute")
def stripe_webhook():
    """Handle Stripe webhook events"""
    # TODO: Implement Stripe webhook handling
    return jsonify({'status': 'not implemented'}), 501
