import logging
import json
from flask import Blueprint, request, jsonify
from utils.decorators import token_required
from config import db
from models.ai import AIModel
import g4f
from aimodel_selector.models_config import get_model_config, get_default_model, get_all_models

logger = logging.getLogger(__name__)

ai_bp = Blueprint('ai_routes', __name__, url_prefix='/api/ai')

def create_error_response(message, status_code=400):
    return jsonify({"status": "error", "message": message}), status_code

def format_api_response(data):
    return jsonify({"status": "success", "data": data})

def get_default_model_config():
    """Get the active AI model configuration from aimodel_selector."""
    try:
        default_model_name = get_default_model()
        model_config = get_model_config(default_model_name)
        return {
            'provider': model_config.get('provider', 'PollinationsAI'),
            'model': model_config.get('model', 'geminisearch')
        }
    except Exception as e:
        logger.error(f"Error fetching model config: {str(e)}")
        return {
            'provider': 'AnyProvider',
            'model': 'gpt-4'
        }

@ai_bp.route('/models', methods=['GET'])
@token_required
def get_ai_models(current_user, user_role):
    """Get available AI models (alias for existing route but scoped to /api/ai)"""
    try:
        models = AIModel.query.order_by(AIModel.name.asc()).all()
        return jsonify({
            'status': 'success',
            'models': [model.to_dict() for model in models]
        }), 200
    except Exception as e:
        return create_error_response(f"Error fetching models: {str(e)}", 500)

@ai_bp.route('/generate', methods=['POST'])
@token_required
def generate_content(current_user, user_role, institute_id=None, instructor_id=None):
    """Generate, enhance, or optimize content for a specific field."""
    try:
        data = request.get_json()
        if not data:
            return create_error_response("No data provided", 400)
        
        action = data.get('action', 'write') # write|enhance|optimize|expand|shorten|translate
        content = data.get('content', '')
        field_name = data.get('field_name', '')
        context = data.get('context', '')
        tone = data.get('tone', 'professional')
        language = data.get('language', 'English')
        
        # Build prompt based on action
        system_prompt = f"You are a professional content assistant helping an admin write content for an educational institute platform. You MUST output ONLY the final content. NEVER output your thought process, conversational text, or any introduction/conclusion like 'Here is the content'."
        
        user_prompt = ""
        if action == 'write':
            user_prompt = f"Task: WRITE content for the field '{field_name}'.\nTone: {tone.upper()}\n"
            if context:
                user_prompt += f"\nContext/Background info:\n{context}\n"
            user_prompt += f"\nPlease write new, high-quality content for this field based on the context."
        elif action in ['enhance', 'optimize']:
            user_prompt = f"Task: ENHANCE AND OPTIMIZE the following content for the field '{field_name}'.\nTone: {tone.upper()}\n"
            if context:
                user_prompt += f"\nContext/Background info:\n{context}\n"
            user_prompt += f"\n\nContent to enhance:\n{content}"
        elif action == 'expand':
            user_prompt = f"Task: EXPAND the following content for the field '{field_name}'.\nTone: {tone.upper()}\n"
            user_prompt += f"\nPlease expand on the following content, adding more detail and making it longer while keeping the core message:\n\n{content}"
        elif action == 'shorten':
            user_prompt = f"Task: SHORTEN the following content for the field '{field_name}'.\nTone: {tone.upper()}\n"
            user_prompt += f"\nPlease condense and shorten the following content to be more concise:\n\n{content}"
        elif action == 'translate':
            user_prompt = f"Task: TRANSLATE the following content perfectly into {language} for the field '{field_name}'.\n"
            user_prompt += f"\n\nContent to translate:\n{content}"
        else:
            # Fallback
            user_prompt = f"Task: {action.upper()} content for the field '{field_name}'.\nTone: {tone.upper()}\n\n{content}"
            
        if language != 'English' and action != 'translate':
             user_prompt += f"\n\nIMPORTANT: Your final output MUST be exactly translated into {language}."
            
        user_prompt += "\n\nIMPORTANT RULES:\n"
        user_prompt += "1. Output ONLY the final requested content.\n"
        user_prompt += "2. Do NOT wrap the output in quotes unless quoting someone.\n"
        user_prompt += "3. Do NOT include phrases like 'Here is the enhanced content:' or 'Certainly!'. Just provide the raw text.\n"
        user_prompt += "4. Do NOT include your chain of thought or reasoning (e.g., 'Okay, I need to...'). Start directly with the final content.\n"
        
        # Get model config
        model_config = get_default_model_config()
        
        provider_name = model_config.get('provider', 'PollinationsAI')
        model_name = model_config.get('model', 'gpt-4')
        
        # Try to dynamically load provider class, fallback to PollinationsAI which is most stable
        provider_class = getattr(g4f.Provider, provider_name, g4f.Provider.PollinationsAI)
        
        messages = [
            {"role": "system", "content": system_prompt},
            {"role": "user", "content": user_prompt}
        ]
        
        logger.info(f"Generating AI content (action: {action}, field: {field_name}) via provider {provider_name} model {model_name}")
        
        response = g4f.ChatCompletion.create(
            model=model_name,
            provider=provider_class,
            messages=messages,
            stream=False
        )
        
        result = response if isinstance(response, str) else str(response)
        
        return format_api_response({"generated_text": result.strip()})
        
    except Exception as e:
        logger.error(f"Error generating AI content: {str(e)}")
        return create_error_response(f"AI Generation failed: {str(e)}", 500)

@ai_bp.route('/fill-form', methods=['POST'])
@token_required
def autofill_form(current_user, user_role, institute_id=None, instructor_id=None):
    """Auto-fill an entire form based on a natural language description."""
    try:
        data = request.get_json()
        if not data:
            return create_error_response("No data provided", 400)
            
        description = data.get('description', '')
        form_type = data.get('form_type', 'generic')
        fields = data.get('fields', []) # List of dicts: [{'name': 'title', 'type': 'text'}, ...]
        
        if not description or not fields:
            return create_error_response("description and fields list are required", 400)
            
        field_names = [f.get('name') if isinstance(f, dict) else str(f) for f in fields]
        
        system_prompt = "You are an expert form-filling AI assistant. Your job is to take a user's natural language request and extract/generate the appropriate content for specific form fields."
        
        user_prompt = f"I need to fill out a {form_type} form.\n\n"
        user_prompt += f"USER REQUEST / DESCRIPTION:\n\"{description}\"\n\n"
        user_prompt += f"Please generate content for the following fields:\n"
        for field in field_names:
            user_prompt += f"- {field}\n"
            
        user_prompt += "\nIMPORTANT: You MUST return your response as a valid JSON object. Every field requested above must be a key in the JSON object. Do not include any markdown format tags like ```json. Just raw valid JSON. Do not include any explanations."
        
        # Get model config
        model_config = get_default_model_config()
        
        provider_name = model_config.get('provider', 'PollinationsAI')
        model_name = model_config.get('model', 'gpt-4')
        
        provider_class = getattr(g4f.Provider, provider_name, g4f.Provider.PollinationsAI)
        
        messages = [
            {"role": "system", "content": system_prompt},
            {"role": "user", "content": user_prompt}
        ]
        
        logger.info(f"Auto-filling form (type: {form_type}) via provider {provider_name} model {model_name}")
        
        response = g4f.ChatCompletion.create(
            model=model_name,
            provider=provider_class,
            messages=messages,
            stream=False
        )
        
        result_text = response if isinstance(response, str) else str(response)
        
        # Clean up response if it has markdown formatting
        if result_text.startswith("```json"):
            result_text = result_text[7:]
        if result_text.startswith("```"):
            result_text = result_text[3:]
        if result_text.endswith("```"):
            result_text = result_text[:-3]
            
        result_text = result_text.strip()
        
        try:
            parsed_json = json.loads(result_text)
            return format_api_response({"form_data": parsed_json})
        except json.JSONDecodeError:
            logger.error(f"Failed to parse AI JSON response: {result_text}")
            return create_error_response("AI failed to output valid JSON", 500)
            
    except Exception as e:
        logger.error(f"Error auto-filling form: {str(e)}")
        return create_error_response(f"AI Form Fill failed: {str(e)}", 500)
