using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using UnityEngine;

namespace RedCircuit.AIAssistant
{
    /// <summary>
    /// AI 助搭核心协调器，管理 AI 会话生命周期，协调各子系统。
    /// </summary>
    public class AIAssistantManager : MonoBehaviour
    {
        public static AIAssistantManager Instance { get; private set; }

        /// <summary>当前会话 ID</summary>
        public string SessionId { get; private set; } = Guid.NewGuid().ToString("N")[..16];

        /// <summary>AI 是否就绪</summary>
        public bool IsReady { get; private set; }

        /// <summary>聊天历史记录</summary>
        public List<ChatMessage> History { get; } = new();

        private AIChatController _chatController;
        private AICircuitAdvisor _advisor;
        private AIActionExecutor _executor;
        private AIContextProvider _contextProvider;

        private void Awake()
        {
            if (Instance != null) { Destroy(gameObject); return; }
            Instance = this;
        }

        private void Start()
        {
            _chatController = GetComponent<AIChatController>() ?? gameObject.AddComponent<AIChatController>();
            _advisor = GetComponent<AICircuitAdvisor>() ?? gameObject.AddComponent<AICircuitAdvisor>();
            _executor = GetComponent<AIActionExecutor>() ?? gameObject.AddComponent<AIActionExecutor>();
            _contextProvider = GetComponent<AIContextProvider>() ?? gameObject.AddComponent<AIContextProvider>();

            IsReady = true;
            Debug.Log("[AIAssistant] Manager initialized");
        }

        /// <summary>
        /// 处理用户输入的消息。
        /// </summary>
        public async void HandleUserMessage(string message)
        {
            if (!IsReady)
            {
                _chatController.AppendSystemMessage("AI 助手尚未就绪，请稍候...");
                return;
            }

            // 记录用户消息
            History.Add(new ChatMessage { Role = MessageRole.User, Content = message, Timestamp = DateTime.Now });
            _chatController.AppendUserMessage(message);

            // 采集上下文
            var context = _contextProvider.CollectContext();

            // 发送到服务端 (TODO: 实现网络请求)
            var response = await RequestAIChat(message, context);

            // 处理响应
            ProcessAIResponse(response);
        }

        private async Task<AIResponse> RequestAIChat(string message, GameContext context)
        {
            // TODO: 调用 ai-service POST /api/ai/chat
            // 使用 SSE 流式接收响应
            await Task.Delay(100); // 模拟网络延迟
            return new AIResponse
            {
                Type = ResponseType.Text,
                Content = "AI 助搭功能正在开发中，敬请期待！",
                Actions = new List<AIAction>(),
                RequiresConfirmation = false
            };
        }

        private void ProcessAIResponse(AIResponse response)
        {
            // 记录 AI 消息
            History.Add(new ChatMessage { Role = MessageRole.Assistant, Content = response.Content, Timestamp = DateTime.Now });

            switch (response.Type)
            {
                case ResponseType.Text:
                    _chatController.AppendAIMessage(response.Content);
                    break;

                case ResponseType.Analysis:
                    _chatController.AppendAIMessage(response.Content);
                    _advisor.ShowReport(response.Analysis);
                    break;

                case ResponseType.Action:
                    _chatController.AppendAIMessage(response.Content);
                    if (response.RequiresConfirmation && response.Actions.Count > 0)
                    {
                        _executor.QueueActions(response.Actions);
                        _chatController.ShowConfirmationPrompt(response.Actions.Count);
                    }
                    break;

                case ResponseType.Error:
                    _chatController.AppendErrorMessage(response.Content);
                    break;
            }
        }

        /// <summary>用户确认执行 AI 操作</summary>
        public void ConfirmActions()
        {
            _executor.ExecuteQueuedActions();
        }

        /// <summary>用户拒绝执行 AI 操作</summary>
        public void RejectActions()
        {
            _executor.CancelQueuedActions();
        }

        /// <summary>撤销上一次 AI 操作</summary>
        public void UndoLastAIAction()
        {
            _executor.UndoLastBatch();
        }
    }
}
