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;

        public static ILlmApiClient GetClient()
        {
            if (_clientInstance == null)
            {
                var settings = LoadSettings();
                if (settings == null) return null;
                
                _clientInstance = settings.useDummyClient ? new DummyApiClient() : new GeminiApiClient();
                
                // Initialize the client after creating it.
                // We don't need to wait for the result here, but we fire it off.
                _ = _clientInstance.Initialize();
            }
            return _clientInstance;
        }

        private static Settings.MCPSettings LoadSettings()
        {
            var guids = AssetDatabase.FindAssets("t:MCPSettings");
            if (guids.Length == 0)
            {
                Debug.LogError("Could not find MCPSettings asset. Please create one.");
                return null;
            }
            var path = AssetDatabase.GUIDToAssetPath(guids[0]);
            return 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;
        }
    }
}