import sys
import os
import json
import time
import logging

# Add the project root to the Python path to allow importing modules from the project
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

from chat import create_chat, save_message
from message_utils import get_last_messages
from deepseek_handler import get_llm_response_stream

# --- Configuration ---
# You can change these values for testing
USER_ID = 1          # A valid user ID from your 'users' table
SUBJECT_ID = 4       # 4 corresponds to Chemistry
MODE = "chat-model"  # Use "chat-model" for general chat or "reasoner-model" for complex problems

def main():
    """
    Main function to run the terminal-based chat client.
    """
    print("--- ClassGPT Terminal Client ---")
    print(f"User ID: {USER_ID}, Subject: Chemistry (ID: {SUBJECT_ID})")
    print("Type your message and press Enter. Type 'exit' to quit.")
    print("---------------------------------")

    # 1. Create a new chat session in the database
    try:
        # We pass the subject_id so the chat is correctly associated with Chemistry
        chat_id = create_chat(user_id=USER_ID, subject_id=SUBJECT_ID)
        print(f"New chat session created with ID: {chat_id}\n")
    except Exception as e:
        print(f"Error: Could not create a new chat session.")
        print(f"Details: {e}")
        return

    # 2. Start the main interaction loop
    while True:
        try:
            # Get input from the user in the terminal
            user_message = input("You: ")

            # Check if the user wants to exit
            if user_message.strip().lower() == 'exit':
                print("Ending chat session. Goodbye!")
                break
            
            if not user_message.strip():
                continue

            # Save the user's message to the database
            save_message(chat_id, user_message, author=1)

            # Retrieve the conversation history to provide context to the LLM
            messages = get_last_messages(chat_id)
            
            # Get the streaming response from the language model
            print("ClassGPT: ", end="", flush=True)
            
            full_response = []
            first_chunk_received = False
            start_time = time.time()
            # Call the function that communicates with the DeepSeek API
            stream = get_llm_response_stream(messages, MODE, SUBJECT_ID)
            
            # Process the stream chunk by chunk
            for chunk in stream:
                if not first_chunk_received:
                    end_time = time.time()
                    time_to_first_chunk = end_time - start_time
                    logging.info(f"Time to first chunk: {time_to_first_chunk:.2f} seconds")
                    first_chunk_received = True
                text_content = ""
                # The chunk can be a string or a dictionary, so we handle both
                if isinstance(chunk, str):
                    text_content = chunk
                elif hasattr(chunk, 'text'):
                    text_content = chunk.text
                elif isinstance(chunk, dict):
                    # Extract content from a dictionary, typical for some API responses
                    text_content = chunk.get('content') or chunk.get('text')
                
                if text_content:
                    # Print the content to the terminal immediately
                    print(text_content, end="", flush=True)
                    # Accumulate the parts of the response
                    full_response.append(text_content)
            
            print()  # Add a newline after the model's response is complete

            # Save the complete response from the model to the database
            if full_response:
                final_message = ''.join(full_response)
                save_message(chat_id, final_message, author=0)

        except KeyboardInterrupt:
            # Handle Ctrl+C to exit gracefully
            print("\n\nExiting chat session. Goodbye!")
            break
        except Exception as e:
            # Handle other potential errors during the chat
            print(f"\nAn error occurred: {e}")
            break

if __name__ == "__main__":
    main()
