import { existsSync, readFileSync } from "node:fs";
import { join } from "node:path";
import * as PiCodingAgent from "@sheason/pi-coding-agent";
import { isRecord } from "../../hub/utils.js";
const D_PI_KEYBINDINGS = {
    ...PiCodingAgent.KEYBINDINGS,
    "app.connection.retry": {
        defaultKeys: "ctrl+r",
        description: "Retry remote connection",
    },
};
function toKeybindingsConfig(value) {
    if (!isRecord(value)) {
        return {};
    }
    const config = {};
    for (const [key, binding] of Object.entries(value)) {
        if (typeof binding === "string") {
            config[key] = binding;
            continue;
        }
        if (Array.isArray(binding) && binding.every((entry) => typeof entry === "string")) {
            config[key] = binding;
        }
    }
    return config;
}
function loadRawConfig(path) {
    if (!existsSync(path)) {
        return undefined;
    }
    try {
        const parsed = JSON.parse(readFileSync(path, "utf-8"));
        return isRecord(parsed) ? parsed : undefined;
    }
    catch {
        return undefined;
    }
}
export class KeybindingsManager extends PiCodingAgent.KeybindingsManager {
    constructor(userBindings = {}, configPath) {
        super(userBindings, configPath);
        this.definitions = D_PI_KEYBINDINGS;
        this.setUserBindings(userBindings);
    }
    static create(agentDir = PiCodingAgent.getAgentDir()) {
        const configPath = join(agentDir, "keybindings.json");
        const userBindings = KeybindingsManager.loadDpiFromFile(configPath);
        return new KeybindingsManager(userBindings, configPath);
    }
    static loadDpiFromFile(path) {
        const rawConfig = loadRawConfig(path);
        if (!rawConfig) {
            return {};
        }
        return toKeybindingsConfig(PiCodingAgent.migrateKeybindingsConfig(rawConfig).config);
    }
}
//# sourceMappingURL=keybindings.js.map