import requests
import os
from dotenv import load_dotenv

# Ensure environment variables are loaded from root .env
basedir = os.path.abspath(os.path.join(os.path.dirname(__file__), '../../'))
load_dotenv(os.path.join(basedir, '.env'), override=True)

from flask import Blueprint, request, jsonify, current_app
from flask_jwt_extended import jwt_required, get_jwt_identity
from app.models.chat import ChatMessage
from app.models.user import User
from app.models.learning import LearningMaterial
from app import db

chat_bp = Blueprint('chat', __name__)

def call_gemini_api(prompt):
    api_key = current_app.config.get("GEMINI_API_KEY") or os.getenv("GEMINI_API_KEY") or os.getenv("GOOGLE_API_KEY")
    
    if not api_key:
        return "I'm sorry, but my Gemini AI core is currently offline (API Key Missing)."

    # Gemini 1.5 Flash Endpoint
    url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key={api_key}"
    
    payload = {
        "contents": [{
            "parts": [{"text": prompt}]
        }],
        "generationConfig": {
            "temperature": 0.3,
            "topP": 0.8,
            "topK": 40,
            "maxOutputTokens": 1024,
        }
    }
    
    headers = {'Content-Type': 'application/json'}
    
    try:
        response = requests.post(url, json=payload, headers=headers, timeout=30)
        print(f" * Gemini API Status: {response.status_code}")
        
        if response.status_code != 200:
            print(f"Gemini Error: {response.text}")
            # Fallback to Groq if Gemini fails
            return call_groq_fallback(prompt)

        result = response.json()
        if 'candidates' in result and len(result['candidates']) > 0:
            content = result['candidates'][0]['content']['parts'][0]['text']
            # Robust cleanup
            content = content.replace("```", "").replace("**", "").replace("__", "")
            content = content.replace("###", "").replace("##", "").replace("# ", "")
            content = content.replace("\\[", "$$ ").replace("\\]", " $$")
            content = content.replace("\\(", "$ ").replace("\\)", " $")
            return content.strip()
            
        return "I understood your question, but I'm having trouble generating a response."
    except Exception as e:
        print(f"Gemini Unexpected Error: {e}")
        return call_groq_fallback(prompt)

def call_groq_fallback(prompt):
    api_key = os.getenv("GROQ_API_KEY")
    if not api_key:
        return "I'm having a brief technical moment. Please try again in a few seconds!"
        
    url = "https://api.groq.com/openai/v1/chat/completions"
    payload = {
        "model": "llama-3.1-8b-instant",
        "messages": [{"role": "user", "content": prompt}],
        "temperature": 0.3,
        "max_completion_tokens": 1024
    }
    headers = {'Authorization': f'Bearer {api_key}', 'Content-Type': 'application/json'}
    
    try:
        response = requests.post(url, json=payload, headers=headers, timeout=15)
        if response.status_code == 200:
            content = response.json()['choices'][0]['message']['content']
            return content.strip()
    except:
        pass
    return "I'm having a brief technical moment. Please try again later!"

@chat_bp.route('/send', methods=['POST'])
@jwt_required()
def send_message():
    try:
        user_id = int(get_jwt_identity())
        data = request.get_json()
        
        if not data or not data.get('message'):
            return jsonify({"success": False, "message": "Missing message content"}), 400
            
        user_msg = ChatMessage(user_id=user_id, message=data.get('message'), is_bot=False)
        db.session.add(user_msg)
        
        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_map = {'en': 'English', 'ha': 'Hausa', 'yo': 'Yoruba', 'ig': 'Igbo', 'pi': 'Nigerian Pidgin'}
        lang_name = lang_map.get(user_lang, 'English')

        if user_lvl == 'Vocational':
            persona_name, persona_role = "Workshop Expert", "a master craftsman and professional vocational mentor"
            persona_goal = "provide expert-level technical guidance and career advice"
            persona_context = "Focus on practical skills and industrial standards."
            persona_feature = "Technical Guidance: Provide step-by-step practical instructions."
        else:
            persona_name, persona_role = "QualiLearn AI", "a professional academic mentor and expert tutor"
            persona_goal = f"provide expert-level academic guidance for a {user_lvl} student"
            persona_context = "Focus on academic excellence and exam preparation."
            persona_feature = "Math Formulas: Use professional LaTeX ($ for inline, $$ for block)."

        prompt = (
            f"You are {persona_name}, {persona_role}.\n"
            f"Your goal is to {persona_goal}.\n\n"
            f"IMPORTANT: Respond ONLY in {lang_name}.\n\n"
            "STRICT GUIDELINES:\n"
            "- DIRECT DEFINITIVE ANSWER: Start immediately with the correct answer. No filler.\n"
            "- NO MARKDOWN: ABSOLUTELY NO *, **, #, _ or backtick symbols. Use ONLY plain text.\n"
            "- MATH: Use ONLY LaTeX $ formula $ or $$ formula $$.\n"
            f"- {persona_feature}\n"
            f"- {persona_context}\n\n"
            f"Student Inquiry: {data.get('message', '')}"
        )
        
        bot_response = call_gemini_api(prompt)
        
        bot_msg = ChatMessage(user_id=user_id, message=bot_response, is_bot=True)
        db.session.add(bot_msg)
        
        if user:
            user.study_time = (user.study_time or 0) + 2
            user.overall_progress = min(100, (user.overall_progress or 0) + 0.05)
        
        db.session.commit()
        return jsonify({"success": True, "data": bot_msg.to_dict()})
    except Exception as e:
        return jsonify({"success": False, "message": str(e)}), 500

@chat_bp.route('/history', methods=['GET'])
@jwt_required()
def get_history():
    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():
    user_id = int(get_jwt_identity())
    ChatMessage.query.filter_by(user_id=user_id).delete()
    db.session.commit()
    return jsonify({"success": True, "message": "Chat history cleared"})
