/**
 * Steerable Autonomous Extension - Copilot Auto-style controls
 *
 * Purpose: provide Shift+Tab for run-control cycling (manual → assisted →
 * autonomous) when the session is idle, and for steering/asking questions
 * during autonomous execution (Copilot Auto style). Also integrates Ctrl+Y
 * for YOLO mode (bypass git prompts).
 *
 * Consumer: index.js → steerableAutonomousExtension(pi) on every startup.
 */

import { getAutoSession } from "./auto/session.js";
import { isAutoActive, startAutoDetached } from "./auto.js";
import { projectRoot } from "./commands/context.js";
import {
	inferPresetName,
	resolvePreset,
	SF_MODE_PRESET_NAMES,
} from "./operating-model.js";
import { SteerableAutonomousPanel } from "./steerable-autonomous-panel.js";

export default function steerableAutonomousExtension(api) {
	let panel = null;
	let isAutonomousActive = false;

	// Track autonomous mode state
	api.on("session_start", async (_, _ctx) => {
		isAutonomousActive = false;
		if (panel) {
			panel.hide();
			panel = null;
		}
	});

	// Handle key events - Shift+Tab and Ctrl+Y
	api.registerShortcut("shift+tab", {
		description:
			"Cycle mode (Ask ↔ Build) or open steerable panel during autonomous",
		handler: async (ctx) => {
			if (isAutonomousActive) {
				// During autonomous execution: toggle steering panel
				if (panel) {
					panel.hide();
					panel = null;
				} else {
					panel = new SteerableAutonomousPanel(ctx);
					await panel.show();
				}
				return;
			}

			// Outside autonomous: cycle through Ask → Plan → Build presets
			try {
				const s = getAutoSession();
				// If YOLO is active, exit it first so status and git bypass stay consistent
				if (s.isYolo()) {
					s.toggleYolo();
					if (ctx.settingsManager && ctx.settingsManager.toggleYOLO) {
						ctx.settingsManager.toggleYOLO();
					}
				}
				const current = inferPresetName(s.getMode()) ?? SF_MODE_PRESET_NAMES[0];
				const idx = SF_MODE_PRESET_NAMES.indexOf(current);
				const nextName =
					SF_MODE_PRESET_NAMES[(idx + 1) % SF_MODE_PRESET_NAMES.length];
				const preset = resolvePreset(nextName);
				s.setMode({
					workMode: preset.workMode,
					runControl: preset.runControl,
					modelMode: preset.modelMode,
					permissionProfile: preset.permissionProfile,
				});
				ctx.ui.notify(`Mode → ${nextName}  (${preset.description})`, "info");
			} catch {
				ctx.ui.notify("Mode: use /mode ask|plan|build", "info");
			}
		},
	});

	api.registerShortcut("ctrl+y", {
		description:
			"Toggle YOLO mode (build + autonomous + deep + unrestricted; bypass git prompts). If not running, starts the autonomous loop immediately.",
		handler: async (ctx) => {
			const session = getAutoSession();
			// Toggle full-autonomy preset in AutoSession (handles mode slam + restore)
			const wasAsk = session.getMode().workMode !== "build";
			const enabled = session.toggleYolo();
			// Also toggle settingsManager for safe-git prompt bypass
			if (ctx.settingsManager && ctx.settingsManager.toggleYOLO) {
				ctx.settingsManager.toggleYOLO();
			}
			if (enabled) {
				const msg = wasAsk
					? "🚀 YOLO — Build mode · no git prompts · no confirmation dialogs"
					: "🚀 YOLO — no git prompts · no confirmation dialogs · deep model";
				ctx.ui.notify(msg, "success");
				// Start autonomous loop immediately if not already running
				if (!isAutoActive()) {
					startAutoDetached(ctx, api, projectRoot(), false, {
						canAskUser: false,
						skipModeGate: true,
					});
				}
			} else {
				ctx.ui.notify("YOLO OFF — Build mode (git prompts restored)", "info");
			}
		},
	});

	// Handle slash command for panel
	api.registerCommand("steer", {
		description:
			"Open steerable autonomous panel (Shift+Tab during autonomous)",
		handler: async (_, ctx) => {
			if (!isAutonomousActive) {
				ctx.ui.notify(
					"Autonomous mode not active - use /autonomous to start",
					"info",
				);
				return;
			}

			if (panel) {
				panel.hide();
				panel = null;
			} else {
				panel = new SteerableAutonomousPanel(ctx);
				await panel.show();
			}
		},
	});

	// Listen for autonomous mode changes
	api.on("autonomous_start", async (_, ctx) => {
		isAutonomousActive = true;
		ctx.ui.notify("🤖 Autonomous mode active — Shift+Tab to steer", "info");
	});

	api.on("autonomous_stop", async (_, ctx) => {
		isAutonomousActive = false;
		if (panel) {
			panel.hide();
			panel = null;
		}
		ctx.ui.notify("⏹️ Autonomous mode stopped", "info");
	});

	// Show current autonomous status
	api.registerCommand("autonomous-status", {
		description: "Show current autonomous mode status and retry attempts",
		handler: async (_, ctx) => {
			if (!isAutonomousActive) {
				ctx.ui.notify("Autonomous mode not active", "info");
				return;
			}

			// Would get current status from autonomous system
			const status = {
				currentPhase: "research",
				attempts: 3,
				status: "working on current task",
				retryHistory: ["approach A", "approach B", "approach C"],
			};

			const lines = [
				"🤖 Autonomous Mode Status",
				"",
				`Current Phase: ${status.currentPhase}`,
				`Status: ${status.status}`,
				`Attempts: ${status.attempts}`,
				"",
				"Recent Attempts:",
				...status.retryHistory.map((attempt, i) => `  ${i + 1}. ${attempt}`),
				"",
				"Use Shift+Tab or /steer to control",
			];

			ctx.ui.notify(lines.join("\n"), "info");
		},
	});
}
