using LLM.Editor.Client;
using UnityEditor;
using UnityEngine;

namespace LLM.Editor.Settings
{
    /// <summary>
    /// Creates the "MCP Assistant" entry in Unity's Project Settings window,
    /// allowing for project-wide configuration of the LLM client.
    /// </summary>
    internal static class MCPSettingsProvider
    {
        private static SerializedObject _settings;

        [SettingsProvider]
        public static SettingsProvider CreateMCPSettingsProvider()
        {
            var provider = new SettingsProvider("Project/MCP Assistant", SettingsScope.Project)
            {
                label = "MCP Assistant",
                guiHandler = OnGUI,
            };
            return provider;
        }

        private static void OnGUI(string searchContext)
        {
            if (_settings == null)
            {
                var settingsAsset = FindSettingsAsset();
                if (settingsAsset != null)
                {
                    _settings = new SerializedObject(settingsAsset);
                }
            }

            if (_settings == null)
            {
                EditorGUILayout.HelpBox("MCPSettings asset not found. Please create one via 'Assets > Create > LLM > MCP Settings'.", MessageType.Error);
                return;
            }

            _settings.Update();

            EditorGUILayout.LabelField("Client Configuration", EditorStyles.boldLabel);
            var useDummyClientProp = _settings.FindProperty("useDummyClient");
            
            EditorGUI.BeginChangeCheck();
            EditorGUILayout.PropertyField(useDummyClientProp, new GUIContent("Use Dummy Client", "Bypass the real LLM API and use a local, mock client for testing."));
            if (EditorGUI.EndChangeCheck())
            {
                // When the value changes, invalidate the cached client in the factory.
                ApiClientFactory.InvalidateClient();
            }
            
            var useRagMemoryProp = _settings.FindProperty("useRagMemory");
            EditorGUILayout.PropertyField(useRagMemoryProp, new GUIContent("Use RAG Memory", "Enable the Retrieval-Augmented Generation memory system for in-context learning."));

            EditorGUILayout.HelpBox("Toggling these will switch between the live Gemini API, a local dummy client, and control the agent's memory system.", MessageType.Info);
            
            EditorGUILayout.Space();

            EditorGUILayout.LabelField("Gemini API Configuration", EditorStyles.boldLabel);
            EditorGUILayout.PropertyField(_settings.FindProperty("gcpProjectId"));
            EditorGUILayout.PropertyField(_settings.FindProperty("gcpRegion"));
            EditorGUILayout.PropertyField(_settings.FindProperty("modelName"));
            EditorGUILayout.PropertyField(_settings.FindProperty("embeddingModelName"));
            EditorGUILayout.PropertyField(_settings.FindProperty("gcloudPath"));

            _settings.ApplyModifiedProperties();
        }

        private static MCPSettings FindSettingsAsset()
        {
            var guids = AssetDatabase.FindAssets($"t:{nameof(MCPSettings)}");
            if (guids.Length <= 0) return null;
            var path = AssetDatabase.GUIDToAssetPath(guids[0]);
            return AssetDatabase.LoadAssetAtPath<MCPSettings>(path);
        }
    }
}