using System.Collections.Generic;
using UnityEngine;

namespace RedCircuit.AIAssistant
{
    /// <summary>
    /// 操作执行器，将 AI 操作指令转换为游戏内动作。
    /// 所有操作必须经用户确认后才执行，支持撤销。
    /// </summary>
    public class AIActionExecutor : MonoBehaviour
    {
        /// <summary>待确认的操作队列</summary>
        private readonly Queue<AIAction> _pendingQueue = new();

        /// <summary>已执行的操作批次 (用于撤销)</summary>
        private readonly Stack<ActionBatch> _executedBatches = new();

        /// <summary>单次操作元件上限</summary>
        private const int MaxActionsPerBatch = 20;

        /// <summary>将 AI 操作加入待确认队列</summary>
        public void QueueActions(List<AIAction> actions)
        {
            if (actions.Count > MaxActionsPerBatch)
            {
                Debug.LogWarning($"[AIAction] 操作数 {actions.Count} 超过单批上限 {MaxActionsPerBatch}，将截断");
                actions = actions.GetRange(0, MaxActionsPerBatch);
            }

            foreach (var action in actions)
            {
                _pendingQueue.Enqueue(action);
            }

            // TODO: 在画布上预览待执行操作 (半透明高亮)
            PreviewActions(actions);
        }

        /// <summary>执行队列中所有待确认的操作</summary>
        public void ExecuteQueuedActions()
        {
            if (_pendingQueue.Count == 0) return;

            // 记录操作前快照 (用于撤销)
            var batch = new ActionBatch();
            batch.SnapshotBefore = CaptureCanvasSnapshot();

            while (_pendingQueue.TryDequeue(out var action))
            {
                ExecuteAction(action);
                batch.Actions.Add(action);
            }

            batch.SnapshotAfter = CaptureCanvasSnapshot();
            _executedBatches.Push(batch);

            Debug.Log($"[AIAction] 已执行 {batch.Actions.Count} 个操作");
            ClearPreviews();
        }

        /// <summary>取消所有待确认的操作</summary>
        public void CancelQueuedActions()
        {
            var count = _pendingQueue.Count;
            _pendingQueue.Clear();
            ClearPreviews();
            Debug.Log($"[AIAction] 已取消 {count} 个待确认操作");
        }

        /// <summary>撤销上一次 AI 操作批次</summary>
        public void UndoLastBatch()
        {
            if (!_executedBatches.TryPop(out var batch))
            {
                Debug.LogWarning("[AIAction] 没有可撤销的 AI 操作");
                return;
            }

            // 恢复操作前快照
            RestoreCanvasSnapshot(batch.SnapshotBefore);
            Debug.Log($"[AIAction] 已撤销 {batch.Actions.Count} 个操作");
        }

        private void ExecuteAction(AIAction action)
        {
            switch (action.Type)
            {
                case ActionType.Place:
                    Debug.Log($"[AIAction] 放置 {action.Component} 于 ({action.X},{action.Y}) 旋转={action.Rotation}");
                    // TODO: 调用 PlacementController.PlaceComponent()
                    break;

                case ActionType.Delete:
                    Debug.Log($"[AIAction] 删除 ({action.X},{action.Y})");
                    // TODO: 调用 PlacementController.DeleteComponent()
                    break;

                case ActionType.Move:
                    Debug.Log($"[AIAction] 移动 ({action.FromX},{action.FromY}) -> ({action.X},{action.Y})");
                    // TODO: 调用 PlacementController.MoveComponent()
                    break;

                case ActionType.Rotate:
                    Debug.Log($"[AIAction] 旋转 ({action.X},{action.Y}) -> {action.Rotation}");
                    // TODO: 调用 PlacementController.RotateComponent()
                    break;

                case ActionType.Wire:
                    Debug.Log($"[AIAction] 连线 ({action.FromX},{action.FromY}) -> ({action.X},{action.Y})");
                    // TODO: 调用 PlacementController.PlaceWire()
                    break;
            }
        }

        private void PreviewActions(List<AIAction> actions)
        {
            // TODO: 在画布上以半透明预览所有待执行操作
            foreach (var action in actions)
            {
                // 创建预览 Ghost 对象
            }
        }

        private void ClearPreviews()
        {
            // TODO: 清除所有预览 Ghost 对象
        }

        private string CaptureCanvasSnapshot()
        {
            // TODO: 序列化当前画布状态为 JSON
            return "{}";
        }

        private void RestoreCanvasSnapshot(string snapshot)
        {
            // TODO: 从 JSON 快照恢复画布状态
        }
    }
}
