"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.geminiOrchestrator = 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 GEMINI_SETTINGS_PATH = node_path_1.default.join(node_os_1.default.homedir(), '.gemini', 'settings.json');
function getGeminiStatus() {
    const detected = node_fs_1.default.existsSync(GEMINI_SETTINGS_PATH);
    const connected = detected && hasGeminiMcpServer();
    return {
        name: 'gemini',
        label: 'Gemini CLI',
        connected,
        approvedTools: connected ? 1 : 0,
        totalTools: 1,
        note: "Registers Chorus as a user-scope MCP server in ~/.gemini/settings.json with --trust set so calls don't prompt.",
        supported: detected,
        firstCallBehavior: 'auto',
    };
}
function hasGeminiMcpServer(expectedBinPath) {
    if (!node_fs_1.default.existsSync(GEMINI_SETTINGS_PATH))
        return false;
    try {
        const body = JSON.parse(node_fs_1.default.readFileSync(GEMINI_SETTINGS_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 Gemini CLI. `gemini mcp add` writes to
 * ~/.gemini/settings.json (or per-project) for us — we use --scope user
 * to make it global. Idempotent: skips when already present.
 */
async function connectGemini(opts) {
    if (hasGeminiMcpServer(opts.binPath)) {
        return {
            added: [],
            alreadyPresent: ['mcpServers.chorus'],
            configPath: GEMINI_SETTINGS_PATH,
            slashCommand: 'skipped',
            slashCommandPath: '',
        };
    }
    // Stale entry with different binPath — remove (user-scope) before re-add.
    if (hasGeminiMcpServer()) {
        try {
            await (0, shared_js_1.execFileAsync)('gemini', ['mcp', 'remove', 'chorus', '-s', 'user'], {
                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)('gemini', [
            'mcp',
            'add',
            'chorus',
            'node',
            opts.binPath,
            'mcp',
            '-e',
            `CHORUS_DAEMON_URL=${daemonUrl}`,
            '-s',
            'user',
            '-t',
            'stdio',
            '--trust',
        ], {
            timeout: 30_000,
            shell: process.platform === 'win32',
        });
    }
    catch (err) {
        const msg = err instanceof Error ? err.message : String(err);
        throw new Error(`gemini mcp add failed: ${msg}`);
    }
    return {
        added: ['mcpServers.chorus'],
        alreadyPresent: [],
        configPath: GEMINI_SETTINGS_PATH,
        slashCommand: 'skipped',
        slashCommandPath: '',
    };
}
exports.geminiOrchestrator = {
    name: 'gemini',
    label: 'Gemini CLI',
    getStatus: getGeminiStatus,
    detect: () => node_fs_1.default.existsSync(GEMINI_SETTINGS_PATH),
    connect: async (opts) => {
        const before = hasGeminiMcpServer();
        const full = await connectGemini(opts);
        return { registered: !before, toolsAdded: 0, full };
    },
};
//# sourceMappingURL=gemini.js.map