import { openExternalEditorForText, pasteClipboardImageToEditor, } from "../chat-input-actions.js";
import { CustomEditor } from "./custom-editor.js";
import { isChatSessionBashRunning, isChatSessionStreaming, notifyChatSessionStatus, notifyChatSessionWarning, } from "./chat-session-host-runtime.js";
import { matchesKey } from "./chat-session-host-utils.js";
export function createChatSessionEditor(state, tui, keybindings, editorTheme, editorFactory, callbacks) {
    if (!tui || !keybindings)
        return undefined;
    const editor = createInheritedEditor(tui, editorTheme, keybindings, editorFactory) ??
        new CustomEditor(tui, editorTheme, keybindings, { paddingX: 0, autocompleteMaxVisible: 5 });
    editor.onChange = (text) => {
        state.inputBuffer = text;
        state.isBashMode = text.trimStart().startsWith("!");
    };
    editor.onSubmit = (text) => {
        void callbacks.submit("auto", text);
    };
    const actionEditor = editor;
    actionEditor.onAction?.("app.message.followUp", () => {
        void callbacks.submit("followUp");
    });
    actionEditor.onAction?.("app.message.dequeue", () => {
        callbacks.restoreQueuedMessagesToEditor();
    });
    actionEditor.onAction?.("app.editor.external", () => {
        openChatSessionExternalEditor(state);
    });
    if (state.actions) {
        for (const [action, handler] of Object.entries(state.actions)) {
            actionEditor.onAction?.(action, () => {
                void handler();
            });
        }
    }
    const previousPasteImage = actionEditor.onPasteImage;
    actionEditor.onPasteImage = () => {
        previousPasteImage?.();
        void pasteClipboardImageToEditor(chatSessionEditorAccess(state), () => state.requestRender?.(), { showWarning: (message) => notifyChatSessionWarning(state, message) });
    };
    const previousEscape = actionEditor.onEscape;
    actionEditor.onEscape = () => {
        if (state.compacting) {
            void callbacks.abortCompaction();
            return;
        }
        if (isChatSessionStreaming(state)) {
            void callbacks.interrupt();
            return;
        }
        if (isChatSessionBashRunning(state)) {
            void callbacks.abortBash();
            return;
        }
        if (state.isBashMode) {
            setChatSessionEditorText(state, "");
            notifyChatSessionStatus(state, "Bash mode cleared");
            return;
        }
        previousEscape?.();
    };
    return editor;
}
export function handleChatSessionInput(state, data, callbacks) {
    if (state.bodyViewport.handleInput(data))
        return true;
    if (matchesKey(data, "alt+up")) {
        callbacks.restoreQueuedMessagesToEditor();
        return true;
    }
    if (matchesKey(data, "ctrl+f")) {
        void callbacks.submit("followUp");
        return true;
    }
    if (matchesKey(data, "escape")) {
        if (state.compacting) {
            void callbacks.abortCompaction();
            return true;
        }
        if (isChatSessionStreaming(state)) {
            void callbacks.interrupt();
            return true;
        }
        if (isChatSessionBashRunning(state)) {
            void callbacks.abortBash();
            return true;
        }
        if (state.isBashMode) {
            setChatSessionEditorText(state, "");
            notifyChatSessionStatus(state, "Bash mode cleared");
            return true;
        }
    }
    if (state.editor) {
        state.editor.handleInput(data);
        return true;
    }
    if (matchesKey(data, "enter")) {
        void callbacks.submit("auto");
        return true;
    }
    if (matchesKey(data, "backspace")) {
        setChatSessionEditorText(state, state.inputBuffer.slice(0, -1));
        return true;
    }
    if (data.length === 1 && data >= " " && data <= "~") {
        setChatSessionEditorText(state, `${state.inputBuffer}${data}`);
        return true;
    }
    return false;
}
export function setChatSessionEditorText(state, text) {
    state.inputBuffer = text;
    state.isBashMode = text.trimStart().startsWith("!");
    state.editor?.setText(text);
}
export function setEditorPlaceholder(editor, placeholder) {
    const candidate = editor;
    candidate.setPlaceholder?.(placeholder);
}
export function setEditorBorderColor(editor, borderColor) {
    const candidate = editor;
    if (candidate.borderColor !== undefined)
        candidate.borderColor = borderColor;
}
export function setEditorFocused(editor, focused) {
    const candidate = editor;
    if ("focused" in candidate)
        candidate.focused = focused;
}
function createInheritedEditor(tui, editorTheme, keybindings, editorFactory) {
    if (!editorFactory)
        return undefined;
    try {
        return editorFactory(tui, editorTheme, keybindings);
    }
    catch {
        return undefined;
    }
}
function chatSessionEditorAccess(state) {
    return {
        insertTextAtCursor: (text) => {
            if (state.editor?.insertTextAtCursor) {
                state.editor.insertTextAtCursor(text);
                return;
            }
            setChatSessionEditorText(state, `${state.inputBuffer}${text}`);
        },
        getText: () => state.inputBuffer,
        setText: (text) => setChatSessionEditorText(state, text),
    };
}
function openChatSessionExternalEditor(state) {
    if (!state.editor)
        return;
    const host = state.tui;
    if (!host)
        return;
    const currentText = state.editor.getExpandedText?.() ?? state.editor.getText();
    const updated = openExternalEditorForText(currentText, host, {
        showWarning: (message) => notifyChatSessionWarning(state, message),
    });
    if (updated !== undefined)
        setChatSessionEditorText(state, updated);
}
//# sourceMappingURL=chat-session-host-editor.js.map