using System;
using System.IO;
using Newtonsoft.Json;
using System.Diagnostics;

namespace GTPCorrgir
{
    public class MenuSettings
    {
        private static readonly string SettingsPath =
            Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "menusettings.json");

        private static MenuSettings instance;
        private static readonly object lockObject = new object();

        public class DefaultOptions
        {
            public Opciones.modoDeUso LastUsedMode { get; set; } = Opciones.modoDeUso.Corregir;
            public Opciones.LLM_a_Usar LastUsedLLM { get; set; } = Opciones.LLM_a_Usar.OpenAI;
        }

        public DefaultOptions Options { get; set; }

        public MenuSettings()
        {
            Options = new DefaultOptions();
        }

        public static MenuSettings Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (lockObject)
                    {
                        instance ??= Load();
                    }
                }
                return instance;
            }
        }

        private static MenuSettings Load()
        {
            try
            {
                if (File.Exists(SettingsPath))
                {
                    string json = File.ReadAllText(SettingsPath);
                    var settings = JsonConvert.DeserializeObject<MenuSettings>(json);
                    if (settings != null)
                    {
                        return settings;
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Error loading menu settings: {ex.Message}");
            }
            return new MenuSettings();
        }

        public void Save()
        {
            try
            {
                string json = JsonConvert.SerializeObject(this, Formatting.Indented);
                File.WriteAllText(SettingsPath, json);
                Debug.WriteLine("Menu settings saved successfully");
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Error saving menu settings: {ex.Message}");
            }
        }

        public void UpdateLastUsedOptions(Opciones.modoDeUso mode, Opciones.LLM_a_Usar llm)
        {
            Options.LastUsedMode = mode;
            Options.LastUsedLLM = llm;
            Save();
        }
    }
}