// engine/claude-setup/keybindings-configurator.ts — SPEC-566
// Merges Planu's preferred keybindings into ~/.claude/keybindings.json.
// Pure file I/O — no storage dependency. Callers own the idempotency flag.
import { homedir } from 'node:os';
import { join } from 'node:path';
import { readFile, writeFile, mkdir } from 'node:fs/promises';
// shift+enter to submit, enter to newline — zero-friction for multi-line input
const PLANU_CHAT_BINDINGS = {
    enter: 'chat:newline',
    'shift+enter': 'chat:submit',
};
function claudeKeybindingsPath() {
    return join(homedir(), '.claude', 'keybindings.json');
}
async function readKeybindingsFile() {
    try {
        const raw = await readFile(claudeKeybindingsPath(), 'utf-8');
        return JSON.parse(raw);
    }
    catch {
        return { bindings: [] };
    }
}
function mergeIntoChat(bindings) {
    const result = [...bindings];
    const chatIdx = result.findIndex((b) => b.context === 'Chat');
    if (chatIdx === -1) {
        result.push({ context: 'Chat', bindings: { ...PLANU_CHAT_BINDINGS } });
        return result;
    }
    const chat = result[chatIdx];
    if (!chat) {
        return result;
    }
    const merged = { ...chat.bindings };
    for (const [key, value] of Object.entries(PLANU_CHAT_BINDINGS)) {
        if (!(key in merged)) {
            merged[key] = value;
        }
    }
    result[chatIdx] = { ...chat, bindings: merged };
    return result;
}
/**
 * Merge Planu keybindings into ~/.claude/keybindings.json.
 * Only adds keys that are not already explicitly set — never overwrites user customizations.
 * Returns true when the file was written, false when already fully configured.
 */
export async function configureClaudeKeybindings() {
    const existing = await readKeybindingsFile();
    const before = existing.bindings ?? [];
    const after = mergeIntoChat(before);
    const changed = JSON.stringify(before) !== JSON.stringify(after);
    if (!changed) {
        return false;
    }
    const keybindingsPath = claudeKeybindingsPath();
    await mkdir(join(homedir(), '.claude'), { recursive: true });
    await writeFile(keybindingsPath, JSON.stringify({ bindings: after }, null, 2), 'utf-8');
    return true;
}
/**
 * Check whether Planu's keybindings are already present in ~/.claude/keybindings.json.
 */
export async function arePlanuKeybindingsConfigured() {
    const existing = await readKeybindingsFile();
    const chat = (existing.bindings ?? []).find((b) => b.context === 'Chat');
    if (!chat) {
        return false;
    }
    return Object.entries(PLANU_CHAT_BINDINGS).every(([k, v]) => chat.bindings[k] === v);
}
//# sourceMappingURL=keybindings-configurator.js.map