using System;
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;

namespace GTPCorrgir
{
    public class ChatMessage
    {
        public string Content { get; set; }
        public DateTime Timestamp { get; set; }
        public bool IsUser { get; set; }
        public string ModelUsed { get; set; }
    }

    public class ChatHistory
    {
        private const string HISTORY_FOLDER = "ChatHistory";
        private const int MAX_HISTORY_FILES = 10;
        private readonly string historyPath;
        private List<ChatMessage> currentSession;

        public ChatHistory()
        {
            historyPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, HISTORY_FOLDER);
            currentSession = new List<ChatMessage>();
            EnsureHistoryFolderExists();
            CleanupOldHistories();
        }

        private void EnsureHistoryFolderExists()
        {
            if (!Directory.Exists(historyPath))
            {
                Directory.CreateDirectory(historyPath);
            }
        }

        private void CleanupOldHistories()
        {
            var files = Directory.GetFiles(historyPath, "*.json")
                .OrderByDescending(f => File.GetLastWriteTime(f));

            int count = 0;
            foreach (var file in files)
            {
                count++;
                if (count > MAX_HISTORY_FILES)
                {
                    try
                    {
                        File.Delete(file);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"Error deleting old history: {ex.Message}");
                    }
                }
            }
        }

        public void AddMessage(string content, bool isUser, string modelUsed)
        {
            var message = new ChatMessage
            {
                Content = content,
                Timestamp = DateTime.Now,
                IsUser = isUser,
                ModelUsed = modelUsed
            };
            currentSession.Add(message);
        }

        public void SaveSession()
        {
            if (currentSession.Any())
            {
                string filename = $"chat_history_{DateTime.Now:yyyyMMdd_HHmmss}.json";
                string fullPath = Path.Combine(historyPath, filename);

                try
                {
                    string json = JsonConvert.SerializeObject(currentSession, Formatting.Indented);
                    File.WriteAllText(fullPath, json);
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error saving chat history: {ex.Message}");
                }
            }
        }

        public List<ChatMessage> LoadLastSession()
        {
            try
            {
                var files = Directory.GetFiles(historyPath, "*.json")
                    .OrderByDescending(f => File.GetLastWriteTime(f))
                    .FirstOrDefault();

                if (files != null)
                {
                    string json = File.ReadAllText(files);
                    return JsonConvert.DeserializeObject<List<ChatMessage>>(json);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error loading chat history: {ex.Message}");
            }

            return new List<ChatMessage>();
        }
    }
}