"""
Instance management routes - API endpoints for instance operations
"""
from flask import Blueprint, jsonify, request
from flask_login import login_required, current_user
from app import db
from app.models import Instance
from app.voice_engine.instance_manager import InstanceManager
import logging

logger = logging.getLogger(__name__)

instances_bp = Blueprint('instances', __name__)

instance_manager = None


def get_instance_manager():
    """Get instance manager singleton"""
    global instance_manager
    if instance_manager is None:
        instance_manager = InstanceManager()
    return instance_manager


@instances_bp.route('/create', methods=['POST'])
@login_required
def create_instance():
    """Create new voice AI instance"""
    data = request.get_json()

    # Validate input
    name = data.get('name')
    if not name:
        return jsonify({'error': 'Instance name is required'}), 400

    # Check instance limit
    instance_count = Instance.query.filter_by(user_id=current_user.id).count()
    max_instances = current_user.get_max_instances()

    if instance_count >= max_instances:
        return jsonify({
            'error': f'Instance limit reached ({max_instances}). Upgrade your plan.'
        }), 403

    try:
        # Create instance
        manager = get_instance_manager()
        instance = manager.create_instance(
            user_id=current_user.id,
            name=name,
            description=data.get('description', ''),
            config=data.get('config', {})
        )

        return jsonify({
            'status': 'success',
            'instance': {
                'id': instance.id,
                'instance_id': instance.instance_id,
                'name': instance.name,
                'subdomain': instance.subdomain,
                'url': instance.get_url(),
                'status': instance.status
            }
        }), 201

    except Exception as e:
        logger.error(f"Failed to create instance: {e}")
        return jsonify({'error': str(e)}), 500


@instances_bp.route('/<int:instance_id>', methods=['GET'])
@login_required
def get_instance(instance_id):
    """Get instance details"""
    instance = Instance.query.get_or_404(instance_id)

    if instance.user_id != current_user.id:
        return jsonify({'error': 'Permission denied'}), 403

    return jsonify({
        'id': instance.id,
        'instance_id': instance.instance_id,
        'name': instance.name,
        'subdomain': instance.subdomain,
        'description': instance.description,
        'status': instance.status,
        'url': instance.get_url(),
        'config': instance.config,
        'features': {
            'calendar': instance.enable_google_calendar,
            'gmail': instance.enable_gmail,
            'canvas': instance.enable_canvas,
            '3d_ui': instance.enable_3d_ui,
            'music': instance.enable_music_generation
        },
        'created_at': instance.created_at.isoformat()
    })


@instances_bp.route('/<int:instance_id>/start', methods=['POST'])
@login_required
def start_instance(instance_id):
    """Start a stopped instance"""
    instance = Instance.query.get_or_404(instance_id)

    if instance.user_id != current_user.id:
        return jsonify({'error': 'Permission denied'}), 403

    if instance.status == 'running':
        return jsonify({'error': 'Instance is already running'}), 400

    try:
        manager = get_instance_manager()
        manager.start_instance(instance)

        return jsonify({
            'status': 'success',
            'instance_url': instance.get_url()
        })

    except Exception as e:
        logger.error(f"Failed to start instance {instance_id}: {e}")
        return jsonify({'error': str(e)}), 500


@instances_bp.route('/<int:instance_id>/stop', methods=['POST'])
@login_required
def stop_instance(instance_id):
    """Stop a running instance"""
    instance = Instance.query.get_or_404(instance_id)

    if instance.user_id != current_user.id:
        return jsonify({'error': 'Permission denied'}), 403

    if instance.status == 'stopped':
        return jsonify({'error': 'Instance is already stopped'}), 400

    try:
        manager = get_instance_manager()
        manager.stop_instance(instance)

        return jsonify({'status': 'success'})

    except Exception as e:
        logger.error(f"Failed to stop instance {instance_id}: {e}")
        return jsonify({'error': str(e)}), 500


@instances_bp.route('/<int:instance_id>/restart', methods=['POST'])
@login_required
def restart_instance(instance_id):
    """Restart an instance"""
    instance = Instance.query.get_or_404(instance_id)

    if instance.user_id != current_user.id:
        return jsonify({'error': 'Permission denied'}), 403

    try:
        manager = get_instance_manager()
        manager.restart_instance(instance)

        return jsonify({
            'status': 'success',
            'instance_url': instance.get_url()
        })

    except Exception as e:
        logger.error(f"Failed to restart instance {instance_id}: {e}")
        return jsonify({'error': str(e)}), 500


@instances_bp.route('/<int:instance_id>/config', methods=['PUT'])
@login_required
def update_config(instance_id):
    """Update instance configuration"""
    instance = Instance.query.get_or_404(instance_id)

    if instance.user_id != current_user.id:
        return jsonify({'error': 'Permission denied'}), 403

    data = request.get_json()

    # Update allowed fields
    allowed_fields = [
        'agent_persona', 'voice_provider', 'llm_provider',
        'enable_canvas', 'enable_3d_ui', 'enable_music_generation',
        'enable_google_calendar', 'enable_gmail'
    ]

    for field in allowed_fields:
        if field in data:
            setattr(instance, field, data[field])

    # Update config JSON if provided
    if 'config' in data:
        instance.config = data['config']

    db.session.commit()

    return jsonify({'status': 'success'})


@instances_bp.route('/<int:instance_id>/logs', methods=['GET'])
@login_required
def get_logs(instance_id):
    """Get instance logs"""
    instance = Instance.query.get_or_404(instance_id)

    if instance.user_id != current_user.id:
        return jsonify({'error': 'Permission denied'}), 403

    try:
        manager = get_instance_manager()
        logs = manager.get_instance_logs(instance, lines=request.args.get('lines', 100, type=int))

        return jsonify({'logs': logs})

    except Exception as e:
        logger.error(f"Failed to get logs for instance {instance_id}: {e}")
        return jsonify({'error': str(e)}), 500


@instances_bp.route('/<int:instance_id>/health', methods=['GET'])
@login_required
def health_check(instance_id):
    """Check instance health"""
    instance = Instance.query.get_or_404(instance_id)

    if instance.user_id != current_user.id:
        return jsonify({'error': 'Permission denied'}), 403

    try:
        manager = get_instance_manager()
        health = manager.check_health(instance)

        return jsonify(health)

    except Exception as e:
        logger.error(f"Failed to check health for instance {instance_id}: {e}")
        return jsonify({'error': str(e)}), 500
