from typing import List, Dict
from datetime import datetime
import os
import json
import sys

def log_request_response(model: str, messages: List[Dict[str, str]], mode: str, final_answer: str) -> None:
    """
    Logs the request and response information to a JSON lines file for later analysis.

    Parameters:
    - model (str): The name of the model used for generating responses.
    - messages (List[Dict[str, str]]): A list of message dictionaries exchanged during the conversation.
    - mode (str): The operational mode or context in which the model is running.
    - final_answer (str): The final response generated by the model.
    """
    # Define the logging directory in the user's home directory
    log_dir = os.path.expanduser("~/.eigengen")
    # Create the directory if it doesn't exist
    os.makedirs(log_dir, exist_ok=True)
    # Define the log file path
    log_file = os.path.join(log_dir, "log.jsonl")

    # Create a log entry containing all relevant information
    log_entry = {
        "timestamp": datetime.now().isoformat(),
        "current_dir": os.getcwd(),
        "request": {
            "model": model,
            "messages": messages,
            "mode": mode
        },
        "response": {
            "final_answer": final_answer
        }
    }

    try:
        # Append the log entry to the log file in JSON lines format
        with open(log_file, "a") as f:
            f.write(json.dumps(log_entry) + "\n")
    except Exception as e:
        # Print a warning message to stderr if logging fails
        print(f"Warning: Failed to log request/response: {str(e)}", file=sys.stderr)

def log_prompt(prompt: str) -> None:
    """
    Logs a single prompt to the prompt history file for tracking user inputs.

    Parameters:
    - prompt (str): The prompt text entered by the user.
    """
    # Define the logging directory in the user's home directory
    log_dir = os.path.expanduser("~/.eigengen")
    # Create the directory if it doesn't exist
    os.makedirs(log_dir, exist_ok=True)
    # Define the prompt history file path
    log_file = os.path.join(log_dir, "prompt_history.jsonl")

    # Create a log entry with the timestamp and prompt
    log_entry = {
        "timestamp": datetime.now().isoformat(),
        "prompt": prompt
    }

    try:
        # Append the log entry to the prompt history file in JSON lines format
        with open(log_file, "a") as f:
            f.write(json.dumps(log_entry) + "\n")
    except Exception as e:
        # Print a warning message to stderr if logging fails
        print(f"Warning: Failed to log prompt: {str(e)}", file=sys.stderr)

def list_prompt_history(n: int) -> None:
    """
    Lists the most recent prompts from the prompt history file.

    Parameters:
    - n (int): The number of recent prompts to display.
    """
    # Define the prompt history file path
    log_file = os.path.expanduser("~/.eigengen/prompt_history.jsonl")
    # Check if the prompt history file exists
    if not os.path.exists(log_file):
        print("No prompt history found.")
        return

    # Read all lines from the prompt history file
    with open(log_file, "r") as f:
        lines = f.readlines()

    # Parse the JSON lines and reverse the order to get the most recent prompts first
    prompts = [json.loads(line) for line in reversed(lines)]
    # Iterate over the most recent 'n' prompts and display them
    for i, entry in enumerate(prompts[:n], 1):
        # Format the timestamp for readability
        timestamp = datetime.fromisoformat(entry["timestamp"]).strftime("%Y-%m-%d %H:%M:%S")
        # Print the prompt with its timestamp and index
        print(f"{i}. [{timestamp}] {entry['prompt']}")
