import requests
import os
import json
from dotenv import load_dotenv
from flask import Blueprint, request, jsonify, current_app
from flask_jwt_extended import jwt_required, get_jwt_identity

# Model & Core Configuration
# We use Gemini 2.5 Flash as requested for peak performance.
GEMINI_MODEL = "gemini-2.5-flash"
GEMINI_BASE_URL = "https://generativelanguage.googleapis.com/v1"

chat_bp = Blueprint('chat', __name__)

def get_gemini_response(prompt):
    """
    Core AI Integration: Communicates directly with Google Gemini API.
    """
    # Key Retrieval Logic (Checks Environment -> Config -> Fallback)
    api_key = os.getenv("GEMINI_API_KEY") or os.getenv("GOOGLE_API_KEY") or current_app.config.get("GEMINI_API_KEY")
    
    if not api_key:
        return {
            "error": True,
            "message": "AI Core Offline: GEMINI_API_KEY is not set in cPanel environment settings. Please add it and RESTART the app."
        }

    endpoint = f"{GEMINI_BASE_URL}/{GEMINI_MODEL}:generateContent?key={api_key}"
    
    payload = {
        "contents": [{"parts": [{"text": prompt}]}],
        "generationConfig": {
            "temperature": 0.4,
            "maxOutputTokens": 1024,
            "topP": 0.8,
            "topK": 40
        }
    }
    
    headers = {'Content-Type': 'application/json'}
    
    try:
        response = requests.post(endpoint, json=payload, headers=headers, timeout=30)
        
        if response.status_code != 200:
            return {
                "error": True, 
                "message": f"Gemini Error ({response.status_code}): Please check your API key and network connection."
            }

        data = response.json()
        if 'candidates' in data and len(data['candidates']) > 0:
            text = data['candidates'][0]['content']['parts'][0]['text']
            
            # Post-Process Cleanup: Remove all markdown symbols for the QualiLearn UI
            # We preserve $ and $$ for LaTeX math formulas.
            clean_text = text.replace("```", "").replace("**", "").replace("__", "")
            clean_text = clean_text.replace("###", "").replace("##", "").replace("# ", "")
            clean_text = clean_text.replace("\\[", "$$ ").replace("\\]", " $$")
            clean_text = clean_text.replace("\\(", "$ ").replace("\\)", " $")
            
            # Final scrub of common markdown artifacts
            for char in ['*', '_', '`', '#']:
                clean_text = clean_text.replace(char, '')
                
            return {"error": False, "text": clean_text.strip()}
            
        return {"error": True, "message": "Gemini returned an empty response."}
        
    except Exception as e:
        return {"error": True, "message": f"Unexpected Connection Error: {str(e)}"}

@chat_bp.route('/send', methods=['POST'])
@jwt_required()
def send_message():
    """
    Primary endpoint for the AI Chat UI.
    """
    from app import db
    from app.models.chat import ChatMessage
    from app.models.user import User
    from app.models.learning import LearningMaterial

    try:
        user_id = int(get_jwt_identity())
        data = request.get_json()
        
        if not data or not data.get('message'):
            return jsonify({"success": False, "message": "No message provided"}), 400
            
        # 1. Save User Message
        user_msg = ChatMessage(user_id=user_id, message=data.get('message'), is_bot=False)
        db.session.add(user_msg)
        
        # 2. Prepare Context & Persona
        user = db.session.get(User, user_id)
        user_lang = user.language if user else 'en'
        user_lvl = user.education_level if user else 'Secondary'
        
        lang_names = {'en': 'English', 'ha': 'Hausa', 'yo': 'Yoruba', 'ig': 'Igbo', 'pi': 'Pidgin'}
        target_lang = lang_names.get(user_lang, 'English')

        if user_lvl == 'Vocational':
            persona = "You are the QualiLearn Workshop Mentor, a professional master craftsman."
            goal = "Provide practical, step-by-step technical guidance and trade advice."
        else:
            persona = f"You are the QualiLearn Academic Tutor, a professional mentor for {user_lvl} students."
            goal = "Explain academic concepts clearly and help with exam preparation."

        # Optional: Inject learning context
        context = ""
        materials = LearningMaterial.query.filter_by(language=user_lang, education_level=user_lvl).limit(2).all()
        if materials:
            context = "Reference this material if relevant: " + " | ".join([m.title for m in materials])

        # 3. Construct the Unified Prompt
        system_prompt = (
            f"{persona}\nGoal: {goal}\nLanguage: {target_lang}\n{context}\n\n"
            "STRICT FORMATTING RULES:\n"
            "- Start with the answer directly. No greetings like 'Hello student'.\n"
            "- DO NOT use any markdown symbols (no stars, no hashes, no backticks).\n"
            "- Use ONLY plain text and LaTeX math ($ for inline, $$ for block).\n"
            "- Be concise, accurate, and professional.\n\n"
            f"USER INQUIRY: {data.get('message')}"
        )

        # 4. Get Response from AI Core
        ai_result = get_gemini_response(system_prompt)
        
        if ai_result["error"]:
            bot_text = ai_result["message"]
        else:
            bot_text = ai_result["text"]

        # 5. Save Bot Response
        bot_msg = ChatMessage(user_id=user_id, message=bot_text, is_bot=True)
        db.session.add(bot_msg)
        
        # 6. Update Stats
        if user:
            user.study_time = (user.study_time or 0) + 2
            user.overall_progress = min(100, (user.overall_progress or 0) + 0.1)
            
        db.session.commit()
        return jsonify({"success": True, "data": bot_msg.to_dict()})

    except Exception as e:
        print(f"Chat API Error: {str(e)}")
        return jsonify({"success": False, "message": "Server Error: Could not process AI request."}), 500

@chat_bp.route('/history', methods=['GET'])
@jwt_required()
def get_history():
    from app.models.chat import ChatMessage
    user_id = int(get_jwt_identity())
    messages = ChatMessage.query.filter_by(user_id=user_id).order_by(ChatMessage.timestamp.asc()).all()
    return jsonify({"success": True, "data": [m.to_dict() for m in messages]})

@chat_bp.route('/clear', methods=['DELETE'])
@jwt_required()
def clear_history():
    from app import db
    from app.models.chat import ChatMessage
    user_id = int(get_jwt_identity())
    ChatMessage.query.filter_by(user_id=user_id).delete()
    db.session.commit()
    return jsonify({"success": True, "message": "History cleared"})
