import { join } from "node:path";
import { homedir } from "node:os";
import { getConfig } from "../config.js";
const CONFIG_USAGE = [
  "Usage: wigolo config [options]",
  "",
  "Opens the interactive settings shell. On first run (or when required fields",
  "are missing), automatically launches the setup wizard.",
  "",
  "Options:",
  "  --force-wizard           Always launch the setup wizard (alias: wigolo init).",
  "                           Use the bare flag; --force-wizard=true is not accepted.",
  "  --plain, -p              Print current settings and exit (non-interactive)",
  "  --storage                Print storage usage map",
  "  --cache-stats            Print cache statistics",
  "  --export [path]          Export config to file (secrets excluded)",
  "  --import <path>          Import config from file",
  "  --cleanup <component>    Free storage for: cache|embeddings|models|browser|searxng",
  "  --set <key>=<value>      Update a single non-secret setting headlessly",
  "  --uninstall              Full uninstall (requires --yes)",
  "  --yes                    Skip interactive confirmation (use with --uninstall)",
  "  --help, -h               Show this message",
  ""
].join("\n");
const CLEANABLE = /* @__PURE__ */ new Set(["cache", "embeddings", "models", "browser", "searxng"]);
function parseConfigFlags(args) {
  const flags = {
    plain: false,
    help: false,
    forceWizard: false,
    storage: false,
    cacheStats: false,
    export: null,
    exportRequested: false,
    import: null,
    cleanup: null,
    set: null,
    uninstall: false,
    yes: false
  };
  let i = 0;
  while (i < args.length) {
    const arg = args[i];
    if (!arg) {
      i++;
      continue;
    }
    if (arg === "--plain" || arg === "-p") {
      flags.plain = true;
      i++;
      continue;
    }
    if (arg === "--help" || arg === "-h") {
      flags.help = true;
      i++;
      continue;
    }
    if (arg === "--force-wizard") {
      flags.forceWizard = true;
      i++;
      continue;
    }
    if (arg === "--storage") {
      flags.storage = true;
      i++;
      continue;
    }
    if (arg === "--cache-stats") {
      flags.cacheStats = true;
      i++;
      continue;
    }
    if (arg === "--yes" || arg === "-y") {
      flags.yes = true;
      i++;
      continue;
    }
    if (arg === "--uninstall") {
      flags.uninstall = true;
      i++;
      continue;
    }
    if (arg === "--export") {
      flags.exportRequested = true;
      const next = args[i + 1];
      if (next && !next.startsWith("-")) {
        flags.export = next;
        i += 2;
      } else {
        i++;
      }
      continue;
    }
    if (arg.startsWith("--export=")) {
      flags.exportRequested = true;
      flags.export = arg.slice("--export=".length) || null;
      i++;
      continue;
    }
    if (arg === "--import") {
      const next = args[i + 1];
      if (!next || next.startsWith("-")) {
        process.stderr.write("--import requires a path argument\n");
        process.exit(1);
      }
      flags.import = next;
      i += 2;
      continue;
    }
    if (arg.startsWith("--import=")) {
      flags.import = arg.slice("--import=".length);
      i++;
      continue;
    }
    if (arg === "--cleanup") {
      const next = args[i + 1];
      if (!next || next.startsWith("-")) {
        process.stderr.write(`--cleanup requires a component: ${[...CLEANABLE].join("|")}
`);
        process.exit(1);
      }
      flags.cleanup = next;
      i += 2;
      continue;
    }
    if (arg.startsWith("--cleanup=")) {
      flags.cleanup = arg.slice("--cleanup=".length);
      i++;
      continue;
    }
    if (arg === "--set") {
      const next = args[i + 1];
      if (!next || next.startsWith("-") || !next.includes("=")) {
        process.stderr.write("--set requires <key>=<value> (e.g. --set WIGOLO_SEARCH=hybrid)\n");
        process.exit(1);
      }
      flags.set = next;
      i += 2;
      continue;
    }
    if (arg.startsWith("--set=")) {
      const payload = arg.slice("--set=".length);
      if (!payload.includes("=")) {
        process.stderr.write("--set requires <key>=<value> (e.g. --set=WIGOLO_SEARCH=hybrid)\n");
        process.exit(1);
      }
      flags.set = payload;
      i++;
      continue;
    }
    i++;
  }
  return flags;
}
async function runConfig(args) {
  const flags = parseConfigFlags(args);
  if (flags.help) {
    process.stderr.write(CONFIG_USAGE);
    return 0;
  }
  if (flags.storage) {
    const { computeStorage } = await import("./tui/actions/index.js");
    const config2 = getConfig();
    const result = await computeStorage(config2.dataDir);
    process.stdout.write("Storage usage\n");
    process.stdout.write("=============\n");
    for (const item of result.items) {
      const mb = (item.bytes / (1024 * 1024)).toFixed(2);
      process.stdout.write(`  ${item.label.padEnd(24)} ${mb} MB
`);
    }
    process.stdout.write(`
  ${"Total".padEnd(24)} ${(result.totalBytes / (1024 * 1024)).toFixed(2)} MB
`);
    return 0;
  }
  if (flags.cacheStats) {
    const { getCacheStatsAction } = await import("./tui/actions/index.js");
    const stats = await getCacheStatsAction();
    if (stats.error) {
      process.stderr.write(`Cache stats error: ${stats.error}
`);
      return 1;
    }
    process.stdout.write("Cache statistics\n");
    process.stdout.write("================\n");
    process.stdout.write(`  Entries: ${stats.totalEntries}
`);
    process.stdout.write(`  Size:    ${stats.sizeMb.toFixed(2)} MB
`);
    if (stats.oldest) process.stdout.write(`  Oldest:  ${stats.oldest}
`);
    if (stats.newest) process.stdout.write(`  Newest:  ${stats.newest}
`);
    return 0;
  }
  if (flags.exportRequested) {
    const { exportConfig } = await import("./tui/actions/index.js");
    const defaultPath = join(homedir(), "wigolo-config-export.json");
    const exportPath = flags.export ?? defaultPath;
    const configPath2 = process.env.WIGOLO_CONFIG_PATH ?? join(homedir(), ".wigolo", "config.json");
    const result = await exportConfig(exportPath, configPath2);
    if (result.ok) {
      process.stdout.write(`Config exported to ${exportPath} (secrets excluded)
`);
      return 0;
    }
    process.stderr.write(`Export failed: ${result.error}
`);
    return 1;
  }
  if (flags.import !== null) {
    const { importConfig } = await import("./tui/actions/index.js");
    const configPath2 = process.env.WIGOLO_CONFIG_PATH ?? join(homedir(), ".wigolo", "config.json");
    const result = await importConfig(flags.import, configPath2);
    if (result.ok) {
      process.stdout.write(`Config imported from ${flags.import}
`);
      return 0;
    }
    process.stderr.write(`Import failed: ${result.error}
`);
    return 1;
  }
  if (flags.cleanup !== null) {
    const component = flags.cleanup;
    if (!CLEANABLE.has(component)) {
      process.stderr.write(`Unknown component: ${component}. Valid: ${[...CLEANABLE].join(", ")}
`);
      return 1;
    }
    const { cleanupComponent } = await import("./tui/actions/index.js");
    const config2 = getConfig();
    const result = await cleanupComponent(
      component,
      config2.dataDir
    );
    if (result.ok) {
      const mb = (result.freedBytes / (1024 * 1024)).toFixed(2);
      process.stdout.write(`Cleaned ${component}: freed ${mb} MB
`);
      return 0;
    }
    process.stderr.write(`Cleanup failed: ${result.error}
`);
    return 1;
  }
  if (flags.set !== null) {
    const eqIdx = flags.set.indexOf("=");
    const key = flags.set.slice(0, eqIdx);
    const value = flags.set.slice(eqIdx + 1);
    const { applyHeadlessSet } = await import("./tui/actions/index.js");
    const { CATALOG: CATALOG2 } = await import("./tui/schema/catalog.js");
    const { defaultAgentTargets } = await import("./tui/state/agent-targets.js");
    const { defaultSecretStore } = await import("./tui/state/secret-store.js");
    const config2 = getConfig();
    const configPath2 = process.env.WIGOLO_CONFIG_PATH ?? join(homedir(), ".wigolo", "config.json");
    const agents = defaultAgentTargets({ dataDir: config2.dataDir });
    const secretStore = defaultSecretStore({ dataDir: config2.dataDir });
    const result = await applyHeadlessSet({
      key,
      value,
      configPath: configPath2,
      catalog: CATALOG2,
      agents,
      secretStore
    });
    if (result.status === "ok") {
      process.stdout.write(`${result.message}
`);
      return 0;
    }
    process.stderr.write(`${result.message}
`);
    return 1;
  }
  if (flags.uninstall) {
    if (!flags.yes) {
      process.stderr.write(
        "Uninstall requires confirmation. Use --uninstall --yes to proceed.\n"
      );
      return 1;
    }
    const { uninstall } = await import("./tui/actions/index.js");
    const config2 = getConfig();
    const result = await uninstall({ dataDir: config2.dataDir, confirmed: true });
    if (result.dataDirRemoved) {
      process.stdout.write(`Removed data directory: ${config2.dataDir}
`);
    }
    for (const ar of result.agentResults) {
      if (ar.error) {
        process.stderr.write(`${ar.displayName}: error \u2014 ${ar.error}
`);
      } else if (ar.removed.length > 0) {
        process.stdout.write(`${ar.displayName}: removed ${ar.removed.join(", ")}
`);
      }
    }
    if (!result.ok) {
      process.stderr.write(`Uninstall error: ${result.error}
`);
      return 1;
    }
    process.stdout.write("Wigolo uninstalled.\n");
    return 0;
  }
  const isTTY = Boolean(process.stdout.isTTY);
  const isCI = process.env.CI === "true" || process.env.CI === "1" || process.env.GITHUB_ACTIONS === "true";
  const useInk = !flags.plain && isTTY && !isCI;
  if (useInk) {
    return runInkConfig({
      isTTY,
      ci: isCI,
      plain: flags.plain,
      forceWizard: flags.forceWizard
    });
  }
  const { CATALOG } = await import("./tui/schema/catalog.js");
  const { readPersistedConfig } = await import("../persisted-config.js");
  const config = getConfig();
  const configPath = process.env.WIGOLO_CONFIG_PATH ?? join(homedir(), ".wigolo", "config.json");
  const persisted = readPersistedConfig(configPath);
  process.stdout.write("Wigolo current settings\n");
  process.stdout.write("=======================\n\n");
  for (const category of CATALOG) {
    printCategory(category, persisted.settings);
  }
  process.stdout.write(`
Data directory: ${config.dataDir}
`);
  process.stdout.write("\nRun `wigolo config` in an interactive terminal to change settings.\n");
  process.stdout.write("\nHeadless commands:\n");
  process.stdout.write("  wigolo config --storage          Show storage usage\n");
  process.stdout.write("  wigolo config --cache-stats      Show cache statistics\n");
  process.stdout.write("  wigolo config --export           Export settings to file\n");
  process.stdout.write("  wigolo config --import <path>    Import settings from file\n");
  process.stdout.write("  wigolo config --cleanup <comp>   Free storage per component\n");
  process.stdout.write("  wigolo config --set k=v          Update a single non-secret setting\n");
  process.stdout.write("  wigolo config --uninstall --yes  Full uninstall\n");
  return 0;
}
function formatFieldValue(field, raw) {
  if (field.kind === "masked" || field.secret === true) {
    return raw === void 0 || raw === "" ? "(unset)" : "****";
  }
  if (raw === void 0 || raw === null) {
    return field.default === void 0 ? "(unset)" : `${String(field.default)} (default)`;
  }
  if (Array.isArray(raw)) return raw.join(", ");
  return String(raw);
}
function printCategory(category, settings) {
  process.stdout.write(`[${category.label}]
`);
  for (const field of category.fields) {
    if (field.kind === "readonly") continue;
    const raw = settings[field.settingsPath];
    const display = formatFieldValue(field, raw);
    process.stdout.write(`  ${field.key.padEnd(30)} ${display}
`);
  }
  process.stdout.write("\n");
}
async function runInkConfig(opts) {
  const { runEntry } = await import("./tui/entry.js");
  const { createSettingsStore } = await import("./tui/state/settings-store.js");
  const { CATALOG } = await import("./tui/schema/catalog.js");
  const { defaultAgentTargets } = await import("./tui/state/agent-targets.js");
  const { defaultSecretStore } = await import("./tui/state/secret-store.js");
  const { enableTuiMode } = await import("./tui/utils/suppress-logs.js");
  const { getPackageVersion } = await import("./tui/version.js");
  const { defaultConfigPath, readPersistedConfig } = await import("../persisted-config.js");
  const { toastStore } = await import("./tui/state/toast-store-instance.js");
  const { activityStore } = await import("./tui/state/activity-store-instance.js");
  enableTuiMode();
  const configPath = defaultConfigPath();
  const persisted = readPersistedConfig(configPath);
  const store = createSettingsStore(persisted.settings, toastStore, activityStore);
  const config = getConfig();
  const agents = defaultAgentTargets({ dataDir: config.dataDir });
  const secretStore = defaultSecretStore({ dataDir: config.dataDir });
  const result = await runEntry({
    mode: opts.forceWizard ? "wizard" : "auto",
    configPath,
    isTTY: opts.isTTY,
    ci: opts.ci,
    plain: opts.plain,
    store,
    catalog: CATALOG,
    agents,
    secretStore,
    version: getPackageVersion(),
    productName: "wigolo"
  });
  if (!result.mounted) {
    process.stderr.write("Interactive config requires a terminal. Use --plain to see settings.\n");
    return 1;
  }
  return 0;
}
export {
  runConfig
};
//# sourceMappingURL=config.js.map