import { formatAge } from "../infra/channel-summary.js";
import { formatTokenCount } from "../utils/usage-format.js";
import { formatContextUsageLine } from "./tui-formatters.js";
import type { GatewayStatusSummary } from "./tui-types.js";

export function formatStatusSummary(summary: GatewayStatusSummary) {
  const lines: string[] = [];
  lines.push("Gateway status");

  if (!summary.linkProvider) {
    lines.push("Link provider: unknown");
  } else {
    const linkLabel = summary.linkProvider.label ?? "Link provider";
    const linked = summary.linkProvider.linked === true;
    const authAge =
      linked && typeof summary.linkProvider.authAgeMs === "number"
        ? ` (last refreshed ${formatAge(summary.linkProvider.authAgeMs)})`
        : "";
    lines.push(`${linkLabel}: ${linked ? "linked" : "not linked"}${authAge}`);
  }

  const providerSummary = Array.isArray(summary.providerSummary) ? summary.providerSummary : [];
  if (providerSummary.length > 0) {
    lines.push("");
    lines.push("System:");
    for (const line of providerSummary) {
      lines.push(`  ${line}`);
    }
  }

  if (typeof summary.heartbeatSeconds === "number") {
    lines.push("");
    lines.push(`Heartbeat: ${summary.heartbeatSeconds}s`);
  }

  const sessionPath = summary.sessions?.path;
  if (sessionPath) lines.push(`Session store: ${sessionPath}`);

  const defaults = summary.sessions?.defaults;
  const defaultModel = defaults?.model ?? "unknown";
  const defaultCtx =
    typeof defaults?.contextTokens === "number"
      ? ` (${formatTokenCount(defaults.contextTokens)} ctx)`
      : "";
  lines.push(`Default model: ${defaultModel}${defaultCtx}`);

  const sessionCount = summary.sessions?.count ?? 0;
  lines.push(`Active sessions: ${sessionCount}`);

  const recent = Array.isArray(summary.sessions?.recent) ? summary.sessions?.recent : [];
  if (recent.length > 0) {
    lines.push("Recent sessions:");
    for (const entry of recent) {
      const ageLabel = typeof entry.age === "number" ? formatAge(entry.age) : "no activity";
      const model = entry.model ?? "unknown";
      const usage = formatContextUsageLine({
        total: entry.totalTokens ?? null,
        context: entry.contextTokens ?? null,
        remaining: entry.remainingTokens ?? null,
        percent: entry.percentUsed ?? null,
      });
      const flags = entry.flags?.length ? ` | flags: ${entry.flags.join(", ")}` : "";
      lines.push(
        `- ${entry.key}${entry.kind ? ` [${entry.kind}]` : ""} | ${ageLabel} | model ${model} | ${usage}${flags}`,
      );
    }
  }

  const queued = Array.isArray(summary.queuedSystemEvents) ? summary.queuedSystemEvents : [];
  if (queued.length > 0) {
    const preview = queued.slice(0, 3).join(" | ");
    lines.push(`Queued system events (${queued.length}): ${preview}`);
  }

  return lines;
}
