/**
 * config command — manage the user-global ("prefs") config tier.
 *
 * `ailf init` scaffolds a *project* under .ailf/; `ailf config` manages the
 * *user* — per-developer defaults read on every run when the project and env
 * are silent (cascade: flag > env > project > user > default). Prefs-only:
 * the API key is never stored here. See
 * docs/design-docs/cli-user-config-tier.md.
 */
import { isKnownOwnerTeam, normalizeOwnerTeam } from "../_vendor/ailf-shared/index.js";
import { Command } from "commander";
import { SETTABLE_KEYS, getUserConfigValue, loadUserConfig, setUserConfigKey, unsetUserConfigKey, userConfigFilePath, } from "../adapters/config-sources/user-config.js";
import { validateIndividual } from "./init-config-injection.js";
/** Narrow a raw string to a whitelisted key, or null. */
export function parseSettableKey(raw) {
    return SETTABLE_KEYS.includes(raw)
        ? raw
        : null;
}
/** Validate + normalize a value for a key (pure; no process exit). */
export function validateConfigValue(key, raw) {
    const value = raw.trim();
    switch (key) {
        case "owner.team": {
            if (!value)
                return { ok: false, message: "Team slug must not be empty." };
            const normalized = normalizeOwnerTeam(value);
            if (!isKnownOwnerTeam(normalized)) {
                console.warn(`  ⚠ "${normalized}" is not a known team slug — using it anyway.`);
            }
            return { ok: true, value: normalized };
        }
        case "owner.individual": {
            if (!value)
                return { ok: false, message: "Individual must not be empty." };
            const verdict = validateIndividual(value);
            return verdict === true
                ? { ok: true, value }
                : { ok: false, message: verdict };
        }
        case "execution.apiUrl": {
            try {
                new URL(value);
            }
            catch {
                return { ok: false, message: `"${value}" is not a valid URL.` };
            }
            return { ok: true, value };
        }
    }
}
function fail(message) {
    console.error(`❌ ${message}`);
    process.exit(1);
}
function requireKey(raw) {
    const key = parseSettableKey(raw);
    if (!key) {
        fail(`Unknown config key "${raw}". Valid keys: ${SETTABLE_KEYS.join(", ")}`);
    }
    return key;
}
export function createConfigCommand() {
    const config = new Command("config").description("Manage user-global CLI settings (per-developer defaults)");
    config
        .command("set <key> <value>")
        .description(`Set a user setting. Keys: ${SETTABLE_KEYS.join(", ")}`)
        .action((rawKey, rawValue) => {
        const key = requireKey(rawKey);
        const verdict = validateConfigValue(key, rawValue);
        if (!verdict.ok)
            fail(verdict.message);
        setUserConfigKey(key, verdict.value);
        console.log(`  ✓ Set ${key} = ${verdict.value}`);
        console.log(`    ${userConfigFilePath()}`);
    });
    config
        .command("get <key>")
        .description("Print the user-tier value for a key")
        .action(async (rawKey) => {
        const key = requireKey(rawKey);
        const value = getUserConfigValue(await loadUserConfig(), key);
        if (value === undefined) {
            console.log(`(unset) ${key}`);
            return;
        }
        console.log(value);
    });
    config
        .command("list")
        .description("Print all user-tier settings")
        .action(async () => {
        const cfg = await loadUserConfig();
        const rows = SETTABLE_KEYS.map((key) => {
            const value = getUserConfigValue(cfg, key);
            return `  ${key} = ${value ?? "(unset)"}`;
        });
        console.log(`User config: ${userConfigFilePath()}`);
        console.log(rows.join("\n"));
    });
    config
        .command("unset <key>")
        .description("Remove a user setting")
        .action((rawKey) => {
        const key = requireKey(rawKey);
        unsetUserConfigKey(key);
        console.log(`  ✓ Unset ${key}`);
    });
    config
        .command("path")
        .description("Print the resolved user-config file path")
        .action(() => {
        console.log(userConfigFilePath());
    });
    return config;
}
