from app import mysql
import uuid
import requests
from flask import session, jsonify
from app.config import Config

class ChatService:
    @staticmethod
    def handle_chat(data):
        try:
            user_message = data.get('message', '')
            chat_id = data.get('chat_id')
            user_id = session['user_id']
            
            if not chat_id:
                return jsonify({"success": False, "error": "No chat ID provided"}), 400
            
            cursor = mysql.connection.cursor()
            
            # Verify chat belongs to user
            cursor.execute("""
                SELECT id, title FROM chats 
                WHERE id = %s AND user_id = %s
            """, (chat_id, user_id))
            
            chat = cursor.fetchone()
            if not chat:
                return jsonify({"success": False, "error": "Chat not found"}), 404

            # Update chat title if it's the first message
            if chat[1] is None or chat[1] == "New Chat":
                # Use the first 50 characters of user message as title
                new_title = user_message[:50] + ("..." if len(user_message) > 50 else "")
                cursor.execute(
                    "UPDATE chats SET title = %s WHERE id = %s",
                    (new_title, chat_id)
                )

            # Store user message
            cursor.execute(
                "INSERT INTO messages (chat_id, user_id, role, content) VALUES (%s, %s, %s, %s)",
                (chat_id, user_id, "user", user_message)
            )
            
            # Get chat history
            cursor.execute(
                "SELECT role, content FROM messages WHERE chat_id = %s ORDER BY created_at ASC",
                (chat_id,)
            )
            messages = [{"role": role, "content": content} for role, content in cursor.fetchall()]
            
            # Call Groq API
            response = requests.post(
                Config.GROQ_API_URL,
                headers={
                    "Authorization": f"Bearer {Config.GROQ_API_KEY}",
                    "Content-Type": "application/json"
                },
                json={
                    "model": "llama-3.2-90b-vision-preview",
                    "messages": messages,
                    "temperature": 0.7,
                    "max_tokens": 1000,
                    "top_p": 1,
                    "stream": False
                }
            )

            if response.status_code == 200:
                assistant_message = response.json()["choices"][0]["message"]["content"]
                
                # Store assistant response
                cursor.execute(
                    "INSERT INTO messages (chat_id, user_id, role, content) VALUES (%s, %s, %s, %s)",
                    (chat_id, user_id, "assistant", assistant_message)
                )
                
                mysql.connection.commit()
                return jsonify({
                    "success": True,
                    "message": assistant_message,
                    "chat_id": chat_id
                })
            else:
                mysql.connection.rollback()
                return jsonify({
                    "success": False,
                    "error": f"API Error: {response.status_code}"
                }), 500

        except Exception as e:
            mysql.connection.rollback()
            return jsonify({"success": False, "error": str(e)}), 500

    @staticmethod
    def get_chat_history(chat_id, user_id):
        try:
            if not chat_id:
                return jsonify({"success": False, "error": "No chat ID provided"}), 400
            
            cursor = mysql.connection.cursor()
            
            # Verify chat belongs to user
            cursor.execute("""
                SELECT id FROM chats 
                WHERE id = %s AND user_id = %s
            """, (chat_id, user_id))
            
            if not cursor.fetchone():
                return jsonify({"success": False, "error": "Chat not found"}), 404
            
            # Get all messages for this chat
            cursor.execute("""
                SELECT role, content, created_at 
                FROM messages 
                WHERE chat_id = %s 
                ORDER BY created_at ASC
            """, (chat_id,))
            
            messages = []
            for role, content, created_at in cursor.fetchall():
                messages.append({
                    "role": role,
                    "content": content,
                    "timestamp": created_at.strftime('%Y-%m-%d %H:%M:%S')
                })
            
            return jsonify({
                "success": True,
                "history": messages
            })
        except Exception as e:
            return jsonify({
                "success": False,
                "error": str(e)
            }), 500

    @staticmethod
    def delete_chat(chat_id, user_id):
        try:
            cursor = mysql.connection.cursor()
            
            # Verify ownership
            cursor.execute("""
                SELECT id FROM chats 
                WHERE id = %s AND user_id = %s
            """, (chat_id, user_id))
            
            if not cursor.fetchone():
                return jsonify({"success": False, "error": "Chat not found"}), 404
            
            # Delete messages first
            cursor.execute("DELETE FROM messages WHERE chat_id = %s", (chat_id,))
            
            # Then delete chat
            cursor.execute("DELETE FROM chats WHERE id = %s", (chat_id,))
            
            mysql.connection.commit()
            return jsonify({"success": True})
            
        except Exception as e:
            mysql.connection.rollback()
            return jsonify({
                "success": False,
                "error": str(e)
            }), 500

    @staticmethod
    def create_new_chat(user_id):
        try:
            cursor = mysql.connection.cursor()
            chat_id = str(uuid.uuid4())
            
            cursor.execute(
                "INSERT INTO chats (id, user_id, title) VALUES (%s, %s, %s)",
                (chat_id, user_id, "New Chat")
            )
            
            mysql.connection.commit()
            return jsonify({
                "success": True,
                "chat_id": chat_id
            })
        except Exception as e:
            mysql.connection.rollback()
            return jsonify({
                "success": False,
                "error": str(e)
            }), 500