using UnityEditor;
using UnityEngine;
using UnityEngine.Networking;
using System;
using System.IO;
using System.Text;
using SimpleJSON;

namespace ISVREditor_Utility
{
    /// <summary>
    /// SpacePlayer 帮助菜单：功能咨询（AI 问答）、打开帮助文档。
    /// </summary>
    public class SPEditorHelp : EditorWindow
    {
        const string HelpDocUrl = "http://is.teachf.com/spaceplayer";

        const string PrefApiKey = "SpacePlayer.Help.AiApiKey";
        const string PrefApiUrl = "SpacePlayer.Help.AiApiUrl";
        const string PrefModel = "SpacePlayer.Help.AiModel";

        const string DefaultApiUrl = "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions";
        const string DefaultModel = "qwen-plus";

        const string SystemPrompt =
            "你是 SpacePlayer（空间播放器）产品的功能咨询助手，面向编辑器用户解答功能用法、配置与排查问题。" +
            "请用简洁、准确的中文回答；不确定时说明不确定，并给出可操作的排查建议。";

        static SPEditorHelp window;

        string question = "";
        string submittedQuestion = "";
        string answer = "";
        string status = "";

        Vector2 questionScroll;
        Vector2 answerScroll;

        bool showApiSettings;
        string apiKey;
        string apiUrl;
        string model;

        bool isRequesting;
        UnityWebRequest activeRequest;

        // [MenuItem("SpacePlayer/帮助/AI小助手", false, 9903)]
        // public static void OpenConsultWindow()
        // {
        //     if (window == null)
        //     {
        //         window = GetWindow<SPEditorHelp>(false, "AI小助手", true);
        //         window.minSize = new Vector2(480, 520);
        //     }
        //     window.Show();
        //     window.Focus();
        // }

        [MenuItem("SpacePlayer/帮助/打开帮助文档", false, 9902)]
        public static void OpenHelpDocument()
        {
            Application.OpenURL(HelpDocUrl);
        }

        void OnEnable()
        {
            apiKey = EditorPrefs.GetString(PrefApiKey, "");
            apiUrl = EditorPrefs.GetString(PrefApiUrl, DefaultApiUrl);
            model = EditorPrefs.GetString(PrefModel, DefaultModel);
            if (string.IsNullOrEmpty(apiUrl))
                apiUrl = DefaultApiUrl;
            if (string.IsNullOrEmpty(model))
                model = DefaultModel;
        }

        void OnDisable()
        {
            AbortRequest();
        }

        void OnGUI()
        {
            GUILayout.Space(8);
            GUILayout.Label("AI小助手", EditorStyles.boldLabel);
            EditorGUILayout.HelpBox("输入关于 SpacePlayer 功能的问题，提交后由 AI 回答（每次一问一答）。", MessageType.Info);

            DrawApiSettings();

            GUILayout.Space(6);
            GUILayout.Label("提问内容");
            questionScroll = EditorGUILayout.BeginScrollView(questionScroll, GUILayout.Height(120));
            question = EditorGUILayout.TextArea(question, GUILayout.ExpandHeight(true));
            EditorGUILayout.EndScrollView();

            EditorGUI.BeginDisabledGroup(isRequesting || string.IsNullOrWhiteSpace(question));
            if (GUILayout.Button(isRequesting ? "正在请求 AI…" : "提交给 AI 进行回答", GUILayout.Height(28)))
            {
                SubmitQuestion();
            }
            EditorGUI.EndDisabledGroup();

            if (!string.IsNullOrEmpty(status))
            {
                GUILayout.Space(4);
                EditorGUILayout.HelpBox(status, isRequesting ? MessageType.None : MessageType.Warning);
            }

            GUILayout.Space(8);
            GUILayout.Label("AI 回答");
            if (!string.IsNullOrEmpty(submittedQuestion))
            {
                EditorGUILayout.LabelField("问：", EditorStyles.miniBoldLabel);
                EditorGUILayout.SelectableLabel(submittedQuestion, EditorStyles.wordWrappedLabel, GUILayout.MinHeight(36));
            }

            answerScroll = EditorGUILayout.BeginScrollView(answerScroll, GUILayout.ExpandHeight(true));
            EditorGUILayout.LabelField("答：", EditorStyles.miniBoldLabel);
            EditorGUILayout.TextArea(string.IsNullOrEmpty(answer) ? "（暂无回答）" : answer, GUILayout.ExpandHeight(true));
            EditorGUILayout.EndScrollView();

            GUILayout.Space(6);
            EditorGUILayout.BeginHorizontal();
            EditorGUI.BeginDisabledGroup(string.IsNullOrEmpty(answer) && string.IsNullOrEmpty(submittedQuestion));
            if (GUILayout.Button("复制到剪贴板", GUILayout.Height(24)))
            {
                CopyQaToClipboard();
            }
            if (GUILayout.Button("保存到本地", GUILayout.Height(24)))
            {
                SaveQaToLocal();
            }
            EditorGUI.EndDisabledGroup();
            EditorGUILayout.EndHorizontal();

            GUILayout.Space(8);
        }

        void DrawApiSettings()
        {
            showApiSettings = EditorGUILayout.Foldout(showApiSettings, "AI 接口设置", true);
            if (!showApiSettings)
                return;

            EditorGUI.BeginChangeCheck();
            apiUrl = EditorGUILayout.TextField("接口地址", apiUrl);
            model = EditorGUILayout.TextField("模型", model);
            apiKey = EditorGUILayout.PasswordField("API Key", apiKey);
            if (EditorGUI.EndChangeCheck())
            {
                EditorPrefs.SetString(PrefApiUrl, apiUrl ?? "");
                EditorPrefs.SetString(PrefModel, model ?? "");
                EditorPrefs.SetString(PrefApiKey, apiKey ?? "");
            }
        }

        void SubmitQuestion()
        {
            if (string.IsNullOrWhiteSpace(apiKey))
            {
                status = "请先在「AI 接口设置」中填写 API Key（DashScope）。";
                showApiSettings = true;
                return;
            }

            AbortRequest();

            submittedQuestion = question.Trim();
            answer = "";
            status = "正在请求 AI…";
            isRequesting = true;

            string bodyJson = BuildChatRequestJson(submittedQuestion);
            byte[] bodyRaw = Encoding.UTF8.GetBytes(bodyJson);

            activeRequest = new UnityWebRequest(apiUrl, UnityWebRequest.kHttpVerbPOST);
            activeRequest.uploadHandler = new UploadHandlerRaw(bodyRaw);
            activeRequest.downloadHandler = new DownloadHandlerBuffer();
            activeRequest.SetRequestHeader("Content-Type", "application/json");
            activeRequest.SetRequestHeader("Authorization", "Bearer " + apiKey);

            activeRequest.SendWebRequest();
            EditorApplication.update += PollRequest;
            Repaint();
        }

        void PollRequest()
        {
            if (activeRequest == null)
            {
                EditorApplication.update -= PollRequest;
                return;
            }

            if (!activeRequest.isDone)
                return;

            EditorApplication.update -= PollRequest;
            isRequesting = false;

            try
            {
                if (activeRequest.result != UnityWebRequest.Result.Success)
                {
                    status = "请求失败：" + activeRequest.error + "\n" + activeRequest.downloadHandler.text;
                    answer = "";
                }
                else
                {
                    string responseText = activeRequest.downloadHandler.text;
                    string content;
                    if (TryParseAnswer(responseText, out content))
                    {
                        answer = content;
                        status = "";
                    }
                    else
                    {
                        answer = "";
                        status = "解析 AI 回答失败，原始返回：\n" + responseText;
                    }
                }
            }
            finally
            {
                activeRequest.Dispose();
                activeRequest = null;
                Repaint();
            }
        }

        void AbortRequest()
        {
            EditorApplication.update -= PollRequest;
            if (activeRequest != null)
            {
                activeRequest.Abort();
                activeRequest.Dispose();
                activeRequest = null;
            }
            isRequesting = false;
        }

        string BuildChatRequestJson(string userQuestion)
        {
            // 手动拼 JSON，避免对复杂序列化库的依赖，并正确转义。
            var sb = new StringBuilder(512);
            sb.Append("{\"model\":\"").Append(EscapeJson(model)).Append("\",");
            sb.Append("\"messages\":[");
            sb.Append("{\"role\":\"system\",\"content\":\"").Append(EscapeJson(SystemPrompt)).Append("\"},");
            sb.Append("{\"role\":\"user\",\"content\":\"").Append(EscapeJson(userQuestion)).Append("\"}");
            sb.Append("]}");
            return sb.ToString();
        }

        static string EscapeJson(string value)
        {
            if (string.IsNullOrEmpty(value))
                return "";
            return value
                .Replace("\\", "\\\\")
                .Replace("\"", "\\\"")
                .Replace("\r", "\\r")
                .Replace("\n", "\\n")
                .Replace("\t", "\\t");
        }

        static bool TryParseAnswer(string json, out string content)
        {
            content = null;
            if (string.IsNullOrEmpty(json))
                return false;

            try
            {
                JSONNode root = JSON.Parse(json);
                if (root == null)
                    return false;

                JSONNode choices = root["choices"];
                if (choices == null || choices.Count == 0)
                    return false;

                JSONNode message = choices[0]["message"];
                if (message == null)
                    return false;

                content = message["content"].Value;
                return !string.IsNullOrEmpty(content);
            }
            catch (Exception e)
            {
                Debug.LogWarning("SPEditorHelp 解析回答异常: " + e.Message);
                return false;
            }
        }

        string BuildQaText()
        {
            return "【问】\n" + submittedQuestion + "\n\n【答】\n" + answer;
        }

        void CopyQaToClipboard()
        {
            EditorGUIUtility.systemCopyBuffer = BuildQaText();
            status = "已复制到剪贴板。";
        }

        void SaveQaToLocal()
        {
            string defaultName = "SpacePlayer_功能咨询_" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".txt";
            string path = EditorUtility.SaveFilePanel("保存咨询内容", Application.dataPath, defaultName, "txt");
            if (string.IsNullOrEmpty(path))
                return;

            try
            {
                File.WriteAllText(path, BuildQaText(), Encoding.UTF8);
                status = "已保存：" + path;
            }
            catch (Exception e)
            {
                status = "保存失败：" + e.Message;
            }
        }
    }
}
