using UnityEditor;
using UnityEngine;

namespace AIRuntime.Editor
{
    /// <summary>View onto the service-owned Kanban session. Closing it never stops work.</summary>
    public sealed class AIRuntimeKanbanWindow : EditorWindow
    {
        // Retain the serialized field so existing layouts can reconnect their board.
        [SerializeField] private string _boardFilePath;
        private AIRuntimeKanbanSession _session;

        [MenuItem("Window/AIRuntime/Kanban")]
        public static void Open()
        {
            var window = GetWindow<AIRuntimeKanbanWindow>();
            window.titleContent = new GUIContent("AI Kanban");
            window.minSize = new Vector2(760, 520);
            window.Show();
        }

        private void OnEnable()
        {
            _session = AIRuntimeKanbanScheduler.GetSession(_boardFilePath);
            _session.Changed -= Repaint;
            _session.Changed += Repaint;
        }

        private void OnDisable()
        {
            if (_session != null)
            {
                _boardFilePath = _session.BoardPath;
                _session.Changed -= Repaint;
            }
        }

        private void OnGUI()
        {
            if (_session == null) OnEnable();
            _session.DrawBoard(position);
            _boardFilePath = _session.BoardPath;
        }

        private void OnFocus() { if (_session != null) _session.RefreshView(); }

        public static void OpenAndRunAgentsForCommandLine() => AIRuntimeKanbanSession.OpenAndRunAgentsForCommandLine();
        public static void OpenAndRunSingleAgentStepForCommandLine() => AIRuntimeKanbanSession.OpenAndRunSingleAgentStepForCommandLine();
        public static void MigrateDefaultBoardForCommandLine() => AIRuntimeKanbanSession.MigrateDefaultBoardForCommandLine();
        public static void RequeueNamedTaskReviewForCommandLine() => AIRuntimeKanbanSession.RequeueNamedTaskReviewForCommandLine();
        public static void RequestNamedTaskReworkForCommandLine() => AIRuntimeKanbanSession.RequestNamedTaskReworkForCommandLine();
        public static void ResumeNamedTaskForCommandLine() => AIRuntimeKanbanSession.ResumeNamedTaskForCommandLine();
        public static void ExpandNamedTaskArtifactContractForCommandLine() => AIRuntimeKanbanSession.ExpandNamedTaskArtifactContractForCommandLine();
        public static void ExpandNamedTaskMutationContractForCommandLine() => AIRuntimeKanbanSession.ExpandNamedTaskMutationContractForCommandLine();
        public static void RepairResetRootInputsForCommandLine() => AIRuntimeKanbanSession.RepairResetRootInputsForCommandLine();
    }
}
