import { isAbsolute, join } from "node:path";

/**
 * Compute the directory where llm-inspector stores its on-disk state
 * (runtime config, providers config, log chunks, etc.). Centralised here
 * so every store agrees on the same path.
 *
 * Resolution order (first match wins):
 *   1. `LLM_INSPECTOR_DATA_DIR` env var — absolute path used as-is,
 *      relative path joined to the OS-specific base below.
 *   2. `LLM_INSPECTOR_CONFIG_DIR` env var — kept for backward compat
 *      with the runtime config; treated as a directory *name* (relative
 *      to the OS-specific base) when not absolute.
 *   3. Windows: `%APPDATA%\.llm-inspector` (falls back to
 *      `%USERPROFILE%\.llm-inspector` if APPDATA is unset, then to
 *      `C:\.llm-inspector` as a last resort).
 *      macOS / Linux: `$HOME/.llm-inspector` (falls back to `/tmp`).
 *
 * The env var is re-read on every call so tests and the CLI can swap the
 * directory after this module has been imported.
 */
export function getDataDir(): string {
  const isWindows = process.platform === "win32";
  const base = isWindows
    ? (process.env["USERPROFILE"] ?? join(process.env["APPDATA"] ?? "C:\\", ".llm-inspector"))
    : (process.env["HOME"] ?? "/tmp");

  const dirEnv = process.env["LLM_INSPECTOR_DATA_DIR"];
  if (dirEnv !== undefined && dirEnv !== "") {
    return isAbsolute(dirEnv) ? dirEnv : join(base, dirEnv);
  }

  // Backward-compat: the runtime config historically read
  // `LLM_INSPECTOR_CONFIG_DIR` as a directory *name* (relative to base).
  // Honour it so existing CLI scripts keep working.
  const legacyDirEnv = process.env["LLM_INSPECTOR_CONFIG_DIR"];
  if (legacyDirEnv !== undefined && legacyDirEnv !== "") {
    return isAbsolute(legacyDirEnv) ? legacyDirEnv : join(base, legacyDirEnv);
  }

  return join(base, ".llm-inspector");
}

/**
 * `true` when the user has explicitly asked for a non-default data
 * directory. Used to skip the one-time legacy migration so we don't
 * write to a path the user didn't choose.
 */
export function hasExplicitDataDir(): boolean {
  return (
    (process.env["LLM_INSPECTOR_DATA_DIR"] !== undefined &&
      process.env["LLM_INSPECTOR_DATA_DIR"] !== "") ||
    (process.env["LLM_INSPECTOR_CONFIG_DIR"] !== undefined &&
      process.env["LLM_INSPECTOR_CONFIG_DIR"] !== "")
  );
}
