import type { ExtensionContext, Theme, ReadonlyFooterDataProvider } from "@singularity-forge/pi-coding-agent";
import { truncateToWidth, visibleWidth } from "@singularity-forge/pi-tui";
import { refreshGitStatus } from "./git.js";
import { renderPowerline, renderPowerlineRight, type Segment } from "./powerline.js";

function getSessionStats(ctx: ExtensionContext) {
  let cost = 0;
  let tokens = 0;
  let cxPct = 0;

  try {
    for (const entry of ctx.sessionManager.getEntries()) {
      if (entry.type === "message") {
        const msg = (entry as any).message;
        if (msg?.role === "assistant" && msg.usage) {
          cost += msg.usage.cost?.total || 0;
          tokens += (msg.usage.input || 0) + (msg.usage.output || 0);
        }
      }
    }
    const cx = ctx.getContextUsage?.();
    if (cx?.percent != null) cxPct = cx.percent;
  } catch {
    /* ignore */
  }

  return { cost, tokens, cxPct };
}

export function renderFooter(
  theme: Theme,
  footerData: ReadonlyFooterDataProvider,
  ctx: ExtensionContext,
  width: number,
): string[] {
  const git = refreshGitStatus(process.cwd());
  const { cost, cxPct } = getSessionStats(ctx);

  const leftSegments: Segment[] = [];

  if (git.branch) {
    const dirtyIcon = git.dirty ? "✗" : git.untracked ? "?" : "✓";
    const branchText = `${git.branch} ${dirtyIcon}`;
    leftSegments.push({ text: `⎇ ${branchText}`, fg: "white", bg: "blue", bold: true });

    if (git.added || git.deleted) {
      const diffText = `+${git.added}/-${git.deleted}`;
      leftSegments.push({ text: diffText, fg: "white", bg: "brightBlack" });
    }

    if (git.lastCommit) {
      const msg = git.lastCommit.message.length > 20
        ? git.lastCommit.message.slice(0, 19) + "…"
        : git.lastCommit.message;
      leftSegments.push({ text: `${git.lastCommit.timeAgo} · ${msg}`, fg: "white", bg: "brightBlack" });
    }
  } else {
    leftSegments.push({ text: "SF", fg: "white", bg: "blue", bold: true });
  }

  // Extension statuses
  const statuses = Array.from(footerData.getExtensionStatuses().entries())
    .sort(([a], [b]) => a.localeCompare(b))
    .map(([, text]) => text.trim())
    .filter(Boolean);
  if (statuses.length) {
    leftSegments.push({ text: statuses.join(" "), fg: "white", bg: "magenta" });
  }

  const rightSegments: Segment[] = [];

  if (ctx.model) {
    rightSegments.push({ text: `${ctx.model.provider}/${ctx.model.id}`, fg: "white", bg: "cyan" });
  }

  if (cost > 0) {
    rightSegments.push({ text: `$${cost.toFixed(2)}`, fg: "black", bg: "yellow" });
  }

  const cxColor = cxPct >= 85 ? "red" : cxPct >= 60 ? "yellow" : "green";
  rightSegments.push({ text: `${Math.round(cxPct)}%ctx`, fg: cxPct >= 85 ? "white" : "black", bg: cxColor });

  // Reserve space for right side
  const rightLine = renderPowerlineRight(rightSegments, width, theme);
  const rightWidth = visibleWidth(rightLine);

  const leftLine = renderPowerline(leftSegments, Math.max(1, width - rightWidth), theme);
  const leftWidth = visibleWidth(leftLine);

  // Compose: left powerline + spaces to align + right powerline
  const gap = Math.max(0, width - leftWidth - rightWidth);
  const line = leftLine + " ".repeat(gap) + rightLine;

  return [truncateToWidth(line, width, theme.fg("dim", "…"))];
}
