/**
 * 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 stash: Ctrl+Alt+H overlay
 */

import type {
	ExtensionAPI,
	ExtensionContext,
} from "@singularity-forge/pi-coding-agent";
import { Key } from "@singularity-forge/pi-tui";
import { isAutoActive } from "../sf/auto.js";
import { registerSessionColor } from "./color-band.js";
import { registerSessionEmoji } from "./emoji.js";
import { renderFooter } from "./footer.js";
import { invalidateGitStatus } from "./git.js";
import { renderHeader } from "./header.js";
import { openMarketplaceOverlay } from "./marketplace.js";
import { openStashOverlay, pushStash, readStash, writeStash } from "./stash.js";

function installHeader(ctx: ExtensionContext): void {
	if (!ctx.hasUI) return;
	ctx.ui.setHeader((_tui, theme) => {
		return {
			render: (width: number) => {
				if (isAutoActive()) return [];
				return renderHeader(theme, ctx, width);
			},
			invalidate: () => {},
			dispose: () => {},
		};
	});
}

function installFooter(ctx: ExtensionContext): void {
	if (!ctx.hasUI) return;
	ctx.ui.setFooter((_tui, theme, footerData) => {
		return {
			render: (width: number) => {
				if (isAutoActive()) return [];
				return renderFooter(theme, footerData, ctx, width);
			},
			invalidate: () => {},
			dispose: () => {},
		};
	});
}

export default function sfTui(pi: ExtensionAPI): void {
	registerSessionEmoji(pi);
	registerSessionColor(pi);

	const stash = readStash();
	let wasAutoActive = false;

	pi.on("session_start", async (_event, ctx) => {
		if (!ctx.hasUI) return;

		installHeader(ctx);
		installFooter(ctx);

		pi.registerShortcut(Key.ctrlAlt("h"), {
			description: "Open prompt history stash",
			handler: openStashOverlay,
		});
		pi.registerShortcut(Key.ctrlShift("h"), {
			description: "Open prompt history stash (fallback)",
			handler: openStashOverlay,
		});
		pi.registerShortcut(Key.ctrlAlt("m"), {
			description: "Open marketplace browser",
			handler: openMarketplaceOverlay,
		});

		wasAutoActive = isAutoActive();
	});

	pi.on("before_agent_start", async (event) => {
		const prompt = event.prompt?.trim();
		if (prompt) {
			pushStash(stash, prompt);
			writeStash(stash);
		}
	});

	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;
	});
}
