import { getDefaultConfigPath, getNested, setNested, deleteNested } from "./config.js"; import { createFileConfigStore, type ConfigStore } from "./dashboard/config-store.js"; function coerceValue(raw: string): unknown { const trimmed = raw.trim(); if (trimmed === "true") return true; if (trimmed === "false") return false; if (trimmed === "null") return null; if (trimmed !== "" && /^-?(?:\d+\.?\d*|\.\d+)$/.test(trimmed)) return Number(trimmed); return raw; } function formatOutput(value: unknown): string { if (value === undefined) return ""; if (value === null || typeof value === "boolean" || typeof value === "number") { return String(value); } if (typeof value === "string") return value; return JSON.stringify(value, null, 2); } export interface CliContext { configStore: ConfigStore; log: (message: string) => void; error: (message: string) => void; } function printUsage(ctx: CliContext) { ctx.log("Usage:"); ctx.log(" config set Set a config value"); ctx.log(" config get Get a config value"); ctx.log(" config list Show full config"); ctx.log(" config delete Delete a config key"); } export function runConfigCommand(args: string[], ctx: CliContext): boolean { if (args[0] !== "config") return false; const subcommand = args[1]; if (!subcommand) { printUsage(ctx); return true; } switch (subcommand) { case "set": { const keyPath = args[2]; const rawValue = args[3]; if (!keyPath || rawValue === undefined) { ctx.error("Usage: config set "); return true; } const store = ctx.configStore; const root = store.read(); const value = coerceValue(rawValue); setNested(root, keyPath.split("."), value); store.write(root); ctx.log(`Set ${keyPath} = ${formatOutput(value)}`); return true; } case "get": { const keyPath = args[2]; if (!keyPath) { ctx.error("Usage: config get "); return true; } const root = ctx.configStore.read(); const value = getNested(root, keyPath.split(".")); if (value === undefined) { ctx.error(`Key "${keyPath}" not found.`); } else { ctx.log(formatOutput(value)); } return true; } case "list": { const root = ctx.configStore.read(); ctx.log(JSON.stringify(root, null, 2)); return true; } case "delete": { const keyPath = args[2]; if (!keyPath) { ctx.error("Usage: config delete "); return true; } const store = ctx.configStore; const root = store.read(); const deleted = deleteNested(root, keyPath.split(".")); if (deleted) { store.write(root); ctx.log(`Deleted ${keyPath}`); } else { ctx.error(`Key "${keyPath}" not found.`); } return true; } default: ctx.error(`Unknown config subcommand: ${subcommand}`); printUsage(ctx); return true; } } export function runCli(args: string[]): boolean { if (args[0] !== "config") return false; const configPath = getDefaultConfigPath(); const configStore = createFileConfigStore(configPath); return runConfigCommand(args, { configStore, log: (message) => console.log(message), error: (message) => console.error(message), }); }