import { basename } from "node:path";
import type {
	ExtensionContext,
	Theme,
} from "@singularity-forge/pi-coding-agent";
import { truncateToWidth, visibleWidth } from "@singularity-forge/pi-tui";
import { refreshGitStatus } from "./git.js";

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

export function renderHeader(
	theme: Theme,
	ctx: ExtensionContext,
	width: number,
): string[] {
	const th = theme;
	const git = refreshGitStatus(process.cwd());

	const projectName = basename(process.cwd());

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

	const topLeft = [
		th.fg("accent", "╭─"),
		th.bold(th.fg("accent", "SF")),
		th.fg("dim", "▸"),
		th.fg("text", projectName),
	].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: string[] = [];
	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];
}
