"use strict";

const os = require("os");
const path = require("path");
const { USE_COLOR } = require("./color-system");

// ─── Helpers ───────────────────────────────────────────────────────────────

/** Strip ANSI escape sequences from a string. */
function stripAnsi(str) {
  return str.replace(/\x1b\[[0-9;]*[a-zA-Z]/g, "");
}

/** Get the visible width of a string (excluding ANSI codes). */
function visWidth(str) {
  return stripAnsi(str).length;
}

/** Pad a string with trailing spaces to reach target visible width. */
function padToWidth(str, target) {
  const pad = target - visWidth(str);
  return pad > 0 ? str + " ".repeat(pad) : str;
}

/** Format a token count as human-readable (e.g., 1.2k, 3.5M). */
function formatTokens(n) {
  if (n == null || n === "null") return "0";
  n = Number(n);
  if (isNaN(n) || n === 0) return "0";
  if (n >= 1000000) {
    const k = Math.floor(n / 1000);
    return `${Math.floor(k / 1000)}.${Math.floor((k % 1000) / 100)}M`;
  }
  if (n >= 1000) {
    const whole = Math.floor(n / 1000);
    const frac = Math.floor((n % 1000) / 100);
    return frac > 0 ? `${whole}.${frac}k` : `${whole}k`;
  }
  return String(n);
}

/** Shorten a path for display (replace $HOME with ~, truncate if needed). */
function shortenPath(p, max = 40) {
  const home = os.homedir();
  const isHome = p.startsWith(home);
  if (isHome) {
    p = "~" + p.slice(home.length);
  }
  if (p.length > max) {
    const last = path.basename(p);
    const parent = path.basename(path.dirname(p));
    p = isHome ? `~/${parent}/${last}` : `.../${parent}/${last}`;
  }
  return p;
}

module.exports = {
  stripAnsi,
  visWidth,
  padToWidth,
  formatTokens,
  shortenPath,
};
