import { basename } from "node:path";
import { truncateToWidth, visibleWidth } from "@singularity-forge/tui";
import { getAutoSession } from "../auto/session.js";
import { refreshGitStatus } from "./git.js";

function align(left, right, width, ellipsis) {
	const gap = Math.max(1, width - visibleWidth(left) - visibleWidth(right));
	return truncateToWidth(left + " ".repeat(gap) + right, width, ellipsis);
}

function compactModeBadge(mode) {
	const map = {
		chat: "C",
		plan: "P",
		build: "B",
		review: "R",
		repair: "F",
		research: "S",
	};
	return map[mode] ?? "?";
}

function compactRunControlBadge(rc) {
	const map = {
		manual: "M",
		assisted: "A",
		autonomous: "∞",
	};
	return map[rc] ?? "?";
}

function compactPermissionBadge(pp) {
	const map = {
		restricted: "R",
		normal: "N",
		trusted: "T",
		unrestricted: "U",
	};
	return map[pp] ?? "?";
}

function compactModelModeBadge(mm) {
	const map = {
		fast: "F",
		smart: "S",
		deep: "D",
	};
	return map[mm] ?? "?";
}

function renderModeBadge(theme, mode, compact) {
	if (!mode) return "";
	const th = theme;
	const paused = mode.paused === true;
	if (compact) {
		const badges = [
			paused ? th.fg("dim", "P!") : "",
			th.fg(paused ? "dim" : "accent", compactModeBadge(mode.workMode)),
			th.fg("dim", compactRunControlBadge(mode.runControl)),
			th.fg(
				paused ? "dim" : "warning",
				compactPermissionBadge(mode.permissionProfile),
			),
			th.fg(paused ? "dim" : "success", compactModelModeBadge(mode.modelMode)),
		].filter(Boolean);
		return `[${badges.join("")}]`;
	}
	const parts = [
		paused ? th.fg("dim", "paused") : "",
		paused ? th.fg("dim", "·") : "",
		th.fg(paused ? "dim" : "accent", mode.workMode),
		th.fg("dim", "·"),
		th.fg("dim", mode.runControl),
		th.fg("dim", "·"),
		th.fg(paused ? "dim" : "warning", mode.permissionProfile),
		th.fg("dim", "·"),
		th.fg(paused ? "dim" : "success", mode.modelMode),
	].filter(Boolean);
	return parts.join(" ");
}

export { renderModeBadge };

/**
 * Minimal auto-mode header — shows only mode badge + project name.
 * Keeps the user aware SF is running autonomously without full header noise.
 */
export function renderAutoHeader(theme, ctx, width) {
	const th = theme;
	const projectName = basename(process.cwd());
	const session = getAutoSession();
	const mode = session?.getMode?.() ?? {
		workMode: "build",
		runControl: "autonomous",
		permissionProfile: "normal",
		modelMode: "smart",
	};

	const modeBadge = renderModeBadge(th, mode, width < 80);
	const left = [
		th.bold(th.fg("accent", "SF")),
		th.fg("dim", "▸"),
		th.fg("text", projectName),
		modeBadge ? th.fg("dim", "·") : "",
		modeBadge,
	]
		.filter(Boolean)
		.join(" ");

	const model = ctx.model
		? `${ctx.model.provider}/${ctx.model.id}`.replace(/^\/+/, "")
		: "";
	const right = model ? th.fg("dim", model) : "";

	const ellipsis = th.fg("dim", "…");
	return [align(left, right, width, ellipsis)];
}

export function renderHeader(theme, ctx, width) {
	const th = theme;
	const git = refreshGitStatus(process.cwd());
	const projectName = basename(process.cwd());
	const mode = ctx.sessionManager?.getMode?.() ?? getAutoSession().getMode();
	const model = ctx.model
		? `${ctx.model.provider}/${ctx.model.id}`.replace(/^\/+/, "")
		: "";
	const modelLabel = model
		? `${th.fg("dim", "model ")}${th.fg("text", model)}`
		: "";
	const modeBadge = renderModeBadge(th, mode, width < 80);
	const topLeft = [
		th.fg("accent", "╭─"),
		th.bold(th.fg("accent", "SF")),
		th.fg("dim", "▸"),
		th.fg("text", projectName),
		modeBadge ? th.fg("dim", "·") : "",
		modeBadge,
	]
		.filter(Boolean)
		.join(" ");
	const branchState = git.branch
		? git.dirty
			? th.fg("warning", "modified")
			: git.untracked
				? th.fg("warning", "untracked")
				: th.fg("success", "clean")
		: th.fg("dim", "no git");
	const branchLabel = git.branch
		? `${th.fg("dim", "branch ")}${th.fg("accent", git.branch)} ${th.fg("dim", "·")} ${branchState}`
		: branchState;
	const sync = [];
	if (git.ahead) sync.push(th.fg("success", `↑${git.ahead}`));
	if (git.behind) sync.push(th.fg("warning", `↓${git.behind}`));
	if (git.added || git.deleted) {
		sync.push(th.fg("muted", `Δ +${git.added}/-${git.deleted}`));
	}
	const bottomRight = sync.join(th.fg("dim", " "));
	const ellipsis = th.fg("dim", "…");
	const top = align(topLeft, modelLabel, width, ellipsis);
	if (width < 64) return [top];
	const bottom = align(
		`${th.fg("accent", "╰─")} ${branchLabel}`,
		bottomRight,
		width,
		ellipsis,
	);
	return [top, bottom];
}
