// packages/plugin-awf/src/commands/config.ts
// AWF Config Command - Manage configuration
import * as fs from "node:fs";
import * as path from "node:path";
import pc from "picocolors";
export const configFlags = {
    get: {
        type: "string",
        description: "Get a config value",
        alias: "g",
    },
    set: {
        type: "string",
        description: "Set a config value (key=value)",
        alias: "s",
    },
    list: {
        type: "boolean",
        description: "List all config values",
        alias: "l",
        default: false,
    },
};
export async function configCommand(args, flags) {
    const cwd = process.cwd();
    const stateFile = path.join(cwd, ".agent/memory/state.json");
    // Check if initialized
    if (!fs.existsSync(stateFile)) {
        console.log(pc.yellow("DOMYH not initialized. Run: nock awf init"));
        return;
    }
    // Read current config
    let config;
    try {
        config = JSON.parse(fs.readFileSync(stateFile, "utf-8"));
    }
    catch {
        console.log(pc.red("Failed to read configuration"));
        return;
    }
    const [subcommand, ...restArgs] = args;
    switch (subcommand) {
        case "get":
            handleGet(config, restArgs[0] || flags.get);
            break;
        case "set":
            await handleSet(stateFile, config, restArgs.join("=") || flags.set);
            break;
        case "list":
        case undefined:
            handleList(config);
            break;
        default:
            // Assume it's a key to get
            handleGet(config, subcommand);
    }
}
function handleGet(config, key) {
    if (!key) {
        console.log(pc.yellow("Specify a key to get"));
        console.log(pc.dim("Example: nock awf config get language"));
        return;
    }
    const value = getNestedValue(config, key);
    if (value === undefined) {
        console.log(pc.yellow(`Key not found: ${key}`));
    }
    else {
        console.log(typeof value === "object" ? JSON.stringify(value, null, 2) : String(value));
    }
}
async function handleSet(stateFile, config, keyValue) {
    if (!keyValue || !keyValue.includes("=")) {
        console.log(pc.yellow("Specify key=value"));
        console.log(pc.dim("Example: nock awf config set language=vi"));
        return;
    }
    const [key, ...valueParts] = keyValue.split("=");
    const value = valueParts.join("=");
    // Handle common settings — redirect shorthand keys to preferences
    if (key === "language" || key === "agent") {
        // Shorthand: `config set language=vi` → sets preferences.language
        if (key === "language" && !["en", "vi"].includes(value)) {
            console.log(pc.yellow('Language must be "en" or "vi"'));
            return;
        }
        setNestedValue(config, `preferences.${key}`, value);
        try {
            fs.writeFileSync(stateFile, JSON.stringify(config, null, 2));
            console.log(pc.green(`✔ Set preferences.${key} = ${value}`));
        }
        catch {
            console.log(pc.red("Failed to save configuration"));
        }
        return;
    }
    // Set value
    setNestedValue(config, key, value);
    // Save
    try {
        fs.writeFileSync(stateFile, JSON.stringify(config, null, 2));
        console.log(pc.green(`✔ Set ${key} = ${value}`));
    }
    catch {
        console.log(pc.red("Failed to save configuration"));
    }
}
function handleList(config) {
    console.log(pc.bold("\n📋 DOMYH Configuration"));
    console.log(pc.gray("─".repeat(40)));
    const display = (key, value) => {
        const formatted = Array.isArray(value)
            ? value.length > 3
                ? `[${value.slice(0, 3).join(", ")}... +${value.length - 3}]`
                : `[${value.join(", ")}]`
            : typeof value === "object"
                ? JSON.stringify(value)
                : String(value);
        console.log(`  ${pc.cyan(key)}: ${formatted}`);
    };
    // Core settings (nested under preferences since init.ts saves them there)
    const prefs = config.preferences || {};
    display("language", prefs.language || "en");
    display("agent", prefs.agent || "auto");
    if (Array.isArray(prefs.agents) && prefs.agents.length > 1) {
        display("agents", prefs.agents);
    }
    display("skills", config.skills || []);
    display("version", config.version || "unknown");
    // Other settings
    const coreKeys = ["preferences", "skills", "initialized", "version"];
    const otherKeys = Object.keys(config).filter((k) => !coreKeys.includes(k));
    if (otherKeys.length > 0) {
        console.log();
        console.log(pc.dim("Other:"));
        for (const key of otherKeys) {
            display(key, config[key]);
        }
    }
    console.log();
    console.log(pc.dim(`File: .agent/memory/state.json`));
}
function getNestedValue(obj, key) {
    const parts = key.split(".");
    let current = obj;
    for (const part of parts) {
        if (current && typeof current === "object" && part in current) {
            current = current[part];
        }
        else {
            return undefined;
        }
    }
    return current;
}
function setNestedValue(obj, key, value) {
    const parts = key.split(".");
    let current = obj;
    for (let i = 0; i < parts.length - 1; i++) {
        const part = parts[i];
        if (!(part in current) || typeof current[part] !== "object") {
            current[part] = {};
        }
        current = current[part];
    }
    current[parts[parts.length - 1]] = value;
}
