using UnityEditor;
using UnityEngine;

namespace LLM.Editor.Client
{
    /// <summary>
    /// Responsible for creating and providing the correct instance of an ILlmApiClient
    /// based on the project's settings (real or dummy).
    /// </summary>
    public static class ApiClientFactory
    {
        private static ILlmApiClient _clientInstance;
        private static Settings.MCPSettings _settings;

        public static ILlmApiClient GetClient()
        {
            if (_clientInstance == null)
            {
                LoadSettings();
                _clientInstance = _settings.useDummyClient ? new DummyApiClient() : new GeminiApiClient();
            }
            return _clientInstance;
        }

        private static void LoadSettings()
        {
            if (_settings) return;
            var guids = AssetDatabase.FindAssets("t:MCPSettings");
            if (guids.Length == 0)
            {
                Debug.LogError("Could not find MCPSettings asset. Please create one.");
                return;
            }
            var path = AssetDatabase.GUIDToAssetPath(guids[0]);
            _settings = AssetDatabase.LoadAssetAtPath<Settings.MCPSettings>(path);
        }

        // Call this if settings are changed to force the factory to create a new client on next request.
        public static void InvalidateClient()
        {
            _clientInstance = null;
        }
    }
}