/**
 * SF-TUI — Unified TUI enhancements for Singularity Forge
 *
 * Features:
 * - Powerline footer: git branch, diff stats, last commit, model, cost, context
 * - Header: project name + branch + model
 * - Prompt history: Ctrl+Alt+H overlay
 * - Mode cycling: Ctrl+Shift+M, Ctrl+Shift+R, Ctrl+Shift+A, Ctrl+Shift+S
 */
import { randomUUID } from "node:crypto";
import { Key } from "@singularity-forge/pi-tui";
import { getAutoSession } from "../sf/auto/session.js";
import { isAutoActive } from "../sf/auto.js";
import { projectRoot } from "../sf/commands/context.js";
import { registerSessionColor } from "./color-band.js";
import { registerSessionEmoji } from "./emoji.js";
import { renderAutoFooter, renderFooter } from "./footer.js";
import { invalidateGitStatus } from "./git.js";
import { renderAutoHeader, renderHeader } from "./header.js";
import { openMarketplaceOverlay } from "./marketplace.js";
import {
	appendPromptHistory,
	openPromptHistoryOverlay,
	pushPromptHistory,
	readPromptHistory,
} from "./prompt-history.js";

const WORK_MODE_CYCLE = [
	"chat",
	"plan",
	"build",
	"review",
	"repair",
	"research",
];
const PERMISSION_PROFILE_CYCLE = [
	"restricted",
	"normal",
	"trusted",
	"unrestricted",
];

function cycleWorkMode(ctx) {
	const session = getAutoSession();
	const current = session.getMode().workMode;
	const idx = WORK_MODE_CYCLE.indexOf(current);
	const next = WORK_MODE_CYCLE[(idx + 1) % WORK_MODE_CYCLE.length];
	const transition = session.setMode({ workMode: next });
	ctx.ui.notify(
		`Mode: ${transition.from.workMode} → ${transition.to.workMode}`,
		"info",
	);
}

function setWorkMode(ctx, mode) {
	const session = getAutoSession();
	const transition = session.setMode({ workMode: mode });
	ctx.ui.notify(
		`Mode: ${transition.from.workMode} → ${transition.to.workMode}`,
		"info",
	);
}

function setRunControl(ctx, rc) {
	const session = getAutoSession();
	const transition = session.setMode({ runControl: rc });
	ctx.ui.notify(
		`Run control: ${transition.from.runControl} → ${transition.to.runControl}`,
		"info",
	);
}

function cyclePermissionProfile(ctx) {
	const session = getAutoSession();
	const current = session.getMode().permissionProfile;
	const idx = PERMISSION_PROFILE_CYCLE.indexOf(current);
	const next =
		PERMISSION_PROFILE_CYCLE[(idx + 1) % PERMISSION_PROFILE_CYCLE.length];
	const transition = session.setMode({ permissionProfile: next });
	ctx.ui.notify(
		`Trust: ${transition.from.permissionProfile} → ${transition.to.permissionProfile}`,
		"info",
	);
}

function installHeader(ctx) {
	if (!ctx.hasUI) return;
	ctx.ui.setHeader((_tui, theme) => {
		return {
			render: (width) => {
				if (isAutoActive()) {
					return renderAutoHeader(theme, ctx, width);
				}
				return renderHeader(theme, ctx, width);
			},
			invalidate: () => {},
			dispose: () => {},
		};
	});
}
function installFooter(ctx) {
	if (!ctx.hasUI) return;
	ctx.ui.setFooter((_tui, theme, footerData) => {
		return {
			render: (width) => {
				if (isAutoActive()) {
					return renderAutoFooter(theme, footerData, ctx, width);
				}
				return renderFooter(theme, footerData, ctx, width);
			},
			invalidate: () => {},
			dispose: () => {},
		};
	});
}
export default function sfTui(pi) {
	registerSessionEmoji(pi);
	registerSessionColor(pi);
	const promptHistory = readPromptHistory();
	let promptHistorySessionId = randomUUID();
	let projectBasePath = null;
	let wasAutoActive = false;
	pi.on("session_start", async (_event, ctx) => {
		if (!ctx.hasUI) return;
		promptHistorySessionId =
			ctx.sessionManager?.getSessionId?.() ?? promptHistorySessionId;
		try {
			projectBasePath = projectRoot();
			const projectPromptHistory = readPromptHistory(projectBasePath);
			promptHistory.splice(0, promptHistory.length, ...projectPromptHistory);
		} catch {
			projectBasePath = null;
		}
		installHeader(ctx);
		installFooter(ctx);
		const openProjectPromptHistory = (overlayCtx) =>
			openPromptHistoryOverlay(overlayCtx, projectBasePath ?? undefined);
		pi.registerShortcut(Key.ctrlAlt("h"), {
			description: "Open prompt history",
			handler: openProjectPromptHistory,
		});
		pi.registerShortcut(Key.ctrlShift("h"), {
			description: "Open prompt history (fallback)",
			handler: openProjectPromptHistory,
		});
		pi.registerShortcut(Key.ctrlAlt("m"), {
			description: "Open marketplace browser",
			handler: openMarketplaceOverlay,
		});
		// Mode cycling shortcuts
		pi.registerShortcut(Key.ctrlShift("m"), {
			description: "Cycle work mode (chat→plan→build→review→repair→research)",
			handler: () => cycleWorkMode(ctx),
		});
		pi.registerShortcut(Key.ctrlShift("r"), {
			description: "Set work mode to repair",
			handler: () => setWorkMode(ctx, "repair"),
		});
		pi.registerShortcut(Key.ctrlShift("a"), {
			description: "Set run control to autonomous",
			handler: () => setRunControl(ctx, "autonomous"),
		});
		pi.registerShortcut(Key.ctrlShift("s"), {
			description: "Set run control to assisted (step)",
			handler: () => setRunControl(ctx, "assisted"),
		});
		pi.registerShortcut(Key.ctrlShift("p"), {
			description:
				"Cycle permission profile (restricted→normal→trusted→unrestricted)",
			handler: () => cyclePermissionProfile(ctx),
		});
		wasAutoActive = isAutoActive();
	});
	pi.on("before_agent_start", async (event) => {
		const prompt = event.prompt?.trim();
		if (prompt) {
			pushPromptHistory(promptHistory, prompt);
			appendPromptHistory(
				prompt,
				projectBasePath ?? undefined,
				promptHistorySessionId,
			);
			pi.appendEntry("sf-prompt-history", {
				prompt,
				projectRoot: projectBasePath,
				sessionId: promptHistorySessionId,
				timestamp: Date.now(),
			});
		}
	});
	pi.on("tool_result", async (_event, ctx) => {
		invalidateGitStatus();
		const autoNow = isAutoActive();
		if (!autoNow && wasAutoActive) {
			installHeader(ctx);
			installFooter(ctx);
		}
		wasAutoActive = autoNow;
	});
	pi.on("agent_end", async (_event, ctx) => {
		const autoNow = isAutoActive();
		if (!autoNow) {
			installHeader(ctx);
			installFooter(ctx);
		}
		wasAutoActive = autoNow;
	});
}
