"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.kimiOrchestrator = void 0;
const node_fs_1 = __importDefault(require("node:fs"));
const node_os_1 = __importDefault(require("node:os"));
const node_path_1 = __importDefault(require("node:path"));
const shared_js_1 = require("./shared.js");
const KIMI_CONFIG_DIR = node_path_1.default.join(node_os_1.default.homedir(), '.kimi');
const KIMI_MCP_PATH = node_path_1.default.join(KIMI_CONFIG_DIR, 'mcp.json');
function getKimiStatus() {
    const detected = node_fs_1.default.existsSync(KIMI_CONFIG_DIR);
    const connected = detected && hasKimiMcpServer();
    return {
        name: 'kimi',
        label: 'Kimi CLI',
        connected,
        approvedTools: connected ? 1 : 0,
        totalTools: 1,
        note: 'Registers Chorus as an MCP server in ~/.kimi/mcp.json. Kimi may show a one-time prompt before the first tool call — click Always allow.',
        supported: detected,
        firstCallBehavior: 'prompts_once',
    };
}
function hasKimiMcpServer(expectedBinPath) {
    if (!node_fs_1.default.existsSync(KIMI_MCP_PATH))
        return false;
    try {
        const body = JSON.parse(node_fs_1.default.readFileSync(KIMI_MCP_PATH, 'utf-8'));
        const servers = body.mcpServers;
        const chorus = servers?.chorus;
        if (!chorus)
            return false;
        if (!expectedBinPath)
            return true;
        return Array.isArray(chorus.args) && chorus.args.includes(expectedBinPath);
    }
    catch {
        return false;
    }
}
/**
 * Register Chorus with Kimi CLI via `kimi mcp add`. Same JSON shape as
 * Gemini (mcpServers.<name>) but stored in ~/.kimi/mcp.json. Idempotent
 * + path-aware: re-registers if binPath drifted.
 */
async function connectKimi(opts) {
    if (hasKimiMcpServer(opts.binPath)) {
        return {
            added: [],
            alreadyPresent: ['mcpServers.chorus'],
            configPath: KIMI_MCP_PATH,
            slashCommand: 'skipped',
            slashCommandPath: '',
        };
    }
    if (hasKimiMcpServer()) {
        try {
            await (0, shared_js_1.execFileAsync)('kimi', ['mcp', 'remove', 'chorus'], {
                timeout: 30_000,
                shell: process.platform === 'win32',
            });
        }
        catch {
            /* best-effort */
        }
    }
    const daemonUrl = opts.daemonUrl ?? shared_js_1.DEFAULT_DAEMON_URL;
    try {
        await (0, shared_js_1.execFileAsync)('kimi', [
            'mcp',
            'add',
            '--transport',
            'stdio',
            'chorus',
            '-e',
            `CHORUS_DAEMON_URL=${daemonUrl}`,
            '--',
            'node',
            opts.binPath,
            'mcp',
        ], {
            timeout: 30_000,
            shell: process.platform === 'win32',
        });
    }
    catch (err) {
        const msg = err instanceof Error ? err.message : String(err);
        throw new Error(`kimi mcp add failed: ${msg}`);
    }
    return {
        added: ['mcpServers.chorus'],
        alreadyPresent: [],
        configPath: KIMI_MCP_PATH,
        slashCommand: 'skipped',
        slashCommandPath: '',
    };
}
exports.kimiOrchestrator = {
    name: 'kimi',
    label: 'Kimi CLI',
    getStatus: getKimiStatus,
    detect: () => node_fs_1.default.existsSync(KIMI_CONFIG_DIR),
    connect: async (opts) => {
        const before = hasKimiMcpServer(opts.binPath);
        const full = await connectKimi(opts);
        return { registered: !before, toolsAdded: 0, full };
    },
};
//# sourceMappingURL=kimi.js.map