import { FreestyleApiError } from "../errors.js";
import { apiKeyInShellEnvironment } from "./env.js";

export type OutputFormat = "pretty" | "json";

export interface OutputArgv {
  output?: OutputFormat;
}

/** Print a value as pretty JSON to stdout. */
export function printJson(value: unknown): void {
  console.log(JSON.stringify(value, null, 2));
}

/**
 * Print a command's result: human-readable by default, raw JSON under
 * `--output=json`. `render` receives the value and returns the pretty text.
 */
export function printResult<T>(argv: OutputArgv, value: T, render: (value: T) => string): void {
  if (argv.output === "json") printJson(value);
  else console.log(render(value));
}

/** Print a short human confirmation line, for commands with no interesting return value. */
export function printLine(message: string): void {
  console.log(message);
}

/** Where the API key on this invocation came from, for credential errors. */
function apiKeySource(argv: unknown): string {
  const flag = (argv as { apiKey?: string }).apiKey;
  if (!flag) return "no API key";
  if (flag !== process.env.FREESTYLE_API_KEY) return "the --api-key flag";
  return apiKeyInShellEnvironment
    ? "FREESTYLE_API_KEY in your environment"
    : `FREESTYLE_API_KEY in the .env file in ${process.cwd()}`;
}

/**
 * A failed WebSocket upgrade (`vm ssh`) carries no error body — the status
 * line is everything the client is given, so turn it into the same guidance
 * a REST failure would have printed.
 */
export function describeUpgradeFailure(error: unknown, argv: unknown): string {
  const message = error instanceof Error ? error.message : String(error);
  const status = Number(
    /Unexpected server response:\s*(\d{3})/.exec(message)?.[1],
  );
  const hint = Number.isNaN(status) ? undefined : statusHint(status, argv);
  return hint ? `${message}\n${dim(hint)}` : message;
}

function statusHint(status: number, argv: unknown): string | undefined {
  switch (status) {
    case 401:
      return (argv as { apiKey?: string }).apiKey
        ? `The API key was rejected. It came from ${apiKeySource(argv)}.`
        : "Your login was rejected or has expired. Run `freestyle login` again.";
    case 403:
      return "You do not have access to this VM's team. Check `freestyle whoami`, or pass --team.";
    case 404:
      return "No such VM in this team. Check the id, and which team you are on with `freestyle whoami`.";
    case 503:
      return "Freestyle cannot serve this right now — retry shortly. This is not your credentials.";
    default:
      return undefined;
  }
}

/**
 * The next step for the failures a caller can actually act on. The gateway
 * says what went wrong; only the CLI knows which of several credentials it
 * just sent, and where that credential came from.
 */
function nextStep(error: FreestyleApiError, argv: unknown): string | undefined {
  switch (error.code) {
    case "INVALID_API_KEY":
      return `The key came from ${apiKeySource(argv)}. It takes precedence over \`freestyle login\` — clear it to use your login instead.`;
    case "MISSING_CREDENTIALS":
      return "Run `freestyle login`, or pass --api-key / set FREESTYLE_API_KEY.";
    case "INVALID_CLI_CREDENTIAL":
      return "Your login is expired or invalid. Run `freestyle login` again.";
    case "CLI_TEAM_ACCESS_DENIED":
      return "Pick a team you belong to with `freestyle team list`, then pass --team or run `freestyle team use`.";
    case "INVALID_CLI_TEAM_HEADER":
      return "Pass --team <name-or-id>, or run `freestyle team use <name-or-id>`.";
    case "NOT_FOUND":
      return "If the id is right, check which team you are on with `freestyle whoami` — resources are per-team.";
    case "CLI_TEAM_RESOLVER_UNAVAILABLE":
    case "KEY_RESOLVER_UNAVAILABLE":
      return "This is a Freestyle-side outage, not your credentials. Retry shortly.";
    default:
      return undefined;
  }
}

/**
 * Wrap a command handler so a {@link FreestyleApiError} (or any error) prints
 * cleanly and exits non-zero, instead of a raw stack trace.
 */
export function handle<Argv>(fn: (argv: Argv) => Promise<void>): (argv: Argv) => Promise<void> {
  return async (argv) => {
    try {
      await fn(argv);
    } catch (error) {
      if (error instanceof FreestyleApiError) {
        console.error(`Error: ${error.code} — ${error.message}`);
        const step = nextStep(error, argv);
        if (step) console.error(dim(step));
      } else if (error instanceof Error) {
        console.error(`Error: ${error.message}`);
      } else {
        console.error("Error:", error);
      }
      process.exitCode = 1;
    }
  };
}

/** Parse `key=value` pairs (e.g. repeated `--metadata env=prod --metadata team=x`) into an object. */
export function parseKeyValuePairs(pairs: string[] | undefined): Record<string, string> {
  const result: Record<string, string> = {};
  for (const pair of pairs ?? []) {
    const eq = pair.indexOf("=");
    if (eq === -1) throw new Error(`Expected key=value, got "${pair}"`);
    result[pair.slice(0, eq)] = pair.slice(eq + 1);
  }
  return result;
}

// ── ANSI styling ────────────────────────────────────────────────────────────

const useColor = Boolean(process.stdout.isTTY) && !process.env.NO_COLOR;

function style(open: number, close: number): (text: string) => string {
  return (text) => (useColor ? `\x1b[${open}m${text}\x1b[${close}m` : text);
}

export const bold = style(1, 22);
export const dim = style(2, 22);
export const red = style(31, 39);
export const green = style(32, 39);
export const yellow = style(33, 39);
export const cyan = style(36, 39);

const ANSI_PATTERN = /\x1b\[[0-9;]*m/g;

/** Visible width of a string, ignoring ANSI escapes. */
function width(text: string): number {
  return text.replace(ANSI_PATTERN, "").length;
}

function pad(text: string, target: number): string {
  return text + " ".repeat(Math.max(0, target - width(text)));
}

// ── Layout helpers ──────────────────────────────────────────────────────────

/** A column-aligned table with a dim header row. */
export function table(headers: string[], rows: string[][]): string {
  const widths = headers.map((h, i) => Math.max(width(h), ...rows.map((r) => width(r[i] ?? ""))));
  const line = (cells: string[]) => cells.map((c, i) => pad(c ?? "", widths[i] as number)).join("  ").trimEnd();
  return [line(headers.map((h) => dim(h))), ...rows.map(line)].join("\n");
}

/**
 * Things the reader is going to copy — a command, a DNS record value, a key —
 * each alone on its line under a dim label.
 *
 * Nothing shares the line and nothing is indented, so a triple-click takes the
 * whole payload and only the payload. The color of the label, not the layout,
 * is what keeps the two apart; an id nobody can retype is the whole reason
 * these lines exist, so the line must not carry anything else.
 */
export function copyable(pairs: Array<[string, string]>): string {
  return pairs.map(([label, value]) => `${dim(`${label}:`)}\n${value}`).join("\n\n");
}

/** An aligned key/value block. Pairs with a nullish or empty value are skipped. */
export function details(pairs: Array<[string, string | number | null | undefined]>): string {
  const present = pairs.filter(([, v]) => v !== null && v !== undefined && v !== "");
  const keyWidth = Math.max(0, ...present.map(([k]) => k.length));
  return present.map(([k, v]) => `${dim(pad(`${k}:`, keyWidth + 1))}  ${v}`).join("\n");
}

// ── Value formatters ────────────────────────────────────────────────────────

/** `2026-07-30T18:04:05Z` → `2026-07-30 11:04` (local time), with a relative hint. */
export function formatDate(iso: string | null | undefined): string | undefined {
  if (!iso) return undefined;
  const date = new Date(iso);
  if (Number.isNaN(date.getTime())) return iso;
  const p = (n: number) => String(n).padStart(2, "0");
  const stamp = `${date.getFullYear()}-${p(date.getMonth() + 1)}-${p(date.getDate())} ${p(date.getHours())}:${p(date.getMinutes())}`;
  const rel = relative(date);
  return rel ? `${stamp} ${dim(`(${rel})`)}` : stamp;
}

/** Compact relative time for tables, e.g. `4h ago`. */
export function relative(from: Date | string): string | undefined {
  const date = typeof from === "string" ? new Date(from) : from;
  const seconds = Math.round((Date.now() - date.getTime()) / 1000);
  if (Number.isNaN(seconds) || seconds < 0) return undefined;
  if (seconds < 60) return `${seconds}s ago`;
  if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`;
  if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`;
  return `${Math.floor(seconds / 86400)}d ago`;
}

/** Memory in MiB → `512 MiB` / `4 GiB`. */
export function formatMiB(mib: number): string {
  return mib >= 1024 && mib % 1024 === 0 ? `${mib / 1024} GiB` : `${mib} MiB`;
}

/** Disk in MB → `750 MB` / `16 GB`. */
export function formatMB(mb: number): string {
  return mb >= 1000 && mb % 1000 === 0 ? `${mb / 1000} GB` : `${mb} MB`;
}

/** Bytes → `1.4 KiB`, `3.2 MiB`, … */
export function formatBytes(bytes: number): string {
  if (bytes < 1024) return `${bytes} B`;
  const units = ["KiB", "MiB", "GiB", "TiB"];
  let value = bytes;
  let unit = "B";
  for (const next of units) {
    if (value < 1024) break;
    value /= 1024;
    unit = next;
  }
  return `${value >= 10 ? Math.round(value) : value.toFixed(1)} ${unit}`;
}

/** `{env: "prod"}` → `env=prod`, comma-separated. */
export function formatMetadata(metadata: Record<string, string> | undefined): string | undefined {
  const entries = Object.entries(metadata ?? {});
  if (entries.length === 0) return undefined;
  return entries.map(([k, v]) => `${k}=${v}`).join(", ");
}
