import * as crypto from "node:crypto";
import { theme } from "../interactive/theme/theme.js";
function createDialogPromise({ output, pendingExtensionRequests, dialogOptions, defaultValue, request, parseResponse, }) {
    if (dialogOptions?.signal?.aborted)
        return Promise.resolve(defaultValue);
    const id = crypto.randomUUID();
    return new Promise((resolve, reject) => {
        let timeoutId;
        const cleanup = () => {
            if (timeoutId)
                clearTimeout(timeoutId);
            dialogOptions?.signal?.removeEventListener("abort", onAbort);
            pendingExtensionRequests.delete(id);
        };
        const onAbort = () => {
            cleanup();
            resolve(defaultValue);
        };
        dialogOptions?.signal?.addEventListener("abort", onAbort, { once: true });
        if (dialogOptions?.timeout) {
            timeoutId = setTimeout(() => {
                cleanup();
                resolve(defaultValue);
            }, dialogOptions.timeout);
        }
        pendingExtensionRequests.set(id, {
            resolve: (response) => {
                cleanup();
                resolve(parseResponse(response));
            },
            reject,
        });
        output({ type: "extension_ui_request", id, ...request });
    });
}
function emitExtensionUIRequest(output, request) {
    output({ type: "extension_ui_request", id: crypto.randomUUID(), ...request });
}
export function createRpcExtensionUIContext({ output, pendingExtensionRequests, }) {
    return {
        select: (title, options, opts) => createDialogPromise({
            output,
            pendingExtensionRequests,
            dialogOptions: opts,
            defaultValue: undefined,
            request: { method: "select", title, options, timeout: opts?.timeout },
            parseResponse: (response) => "cancelled" in response && response.cancelled ? undefined : "value" in response ? response.value : undefined,
        }),
        confirm: (title, message, opts) => createDialogPromise({
            output,
            pendingExtensionRequests,
            dialogOptions: opts,
            defaultValue: false,
            request: { method: "confirm", title, message, timeout: opts?.timeout },
            parseResponse: (response) => "cancelled" in response && response.cancelled ? false : "confirmed" in response ? response.confirmed : false,
        }),
        input: (title, placeholder, opts) => createDialogPromise({
            output,
            pendingExtensionRequests,
            dialogOptions: opts,
            defaultValue: undefined,
            request: { method: "input", title, placeholder, timeout: opts?.timeout },
            parseResponse: (response) => "cancelled" in response && response.cancelled ? undefined : "value" in response ? response.value : undefined,
        }),
        notify(message, type) {
            emitExtensionUIRequest(output, { method: "notify", message, notifyType: type });
        },
        requestRender() {
            // RPC mode does not own a local TUI renderer.
        },
        onTerminalInput() {
            // Raw terminal input not supported in RPC mode
            return () => { };
        },
        setStatus(key, text) {
            emitExtensionUIRequest(output, { method: "setStatus", statusKey: key, statusText: text });
        },
        setWorkingMessage(_message) {
            // Working message not supported in RPC mode - requires TUI loader access
        },
        setWorkingVisible(_visible) {
            // Working visibility not supported in RPC mode - requires TUI loader access
        },
        setWorkingIndicator(_options) {
            // Working indicator customization not supported in RPC mode - requires TUI loader access
        },
        setHiddenThinkingLabel(_label) {
            // Hidden thinking label not supported in RPC mode - requires TUI message rendering access
        },
        setWidget(key, content, options) {
            // Only support string arrays in RPC mode - factory functions are ignored
            if (content === undefined || Array.isArray(content)) {
                emitExtensionUIRequest(output, {
                    method: "setWidget",
                    widgetKey: key,
                    widgetLines: content,
                    widgetPlacement: options?.placement,
                });
            }
        },
        setFooter(_factory) {
            // Custom footer not supported in RPC mode - requires TUI access
        },
        setHeader(_factory) {
            // Custom header not supported in RPC mode - requires TUI access
        },
        setTitle(title) {
            emitExtensionUIRequest(output, { method: "setTitle", title });
        },
        async custom() {
            // Custom UI not supported in RPC mode
            return undefined;
        },
        pasteToEditor(text) {
            // Paste handling not supported in RPC mode - falls back to setEditorText
            this.setEditorText(text);
        },
        setEditorText(text) {
            emitExtensionUIRequest(output, { method: "set_editor_text", text });
        },
        getEditorText() {
            // Synchronous method can't wait for RPC response; host should track editor state locally if needed.
            return "";
        },
        async editor(title, prefill) {
            const id = crypto.randomUUID();
            return new Promise((resolve, reject) => {
                pendingExtensionRequests.set(id, {
                    resolve: (response) => {
                        if ("cancelled" in response && response.cancelled) {
                            resolve(undefined);
                        }
                        else if ("value" in response) {
                            resolve(response.value);
                        }
                        else {
                            resolve(undefined);
                        }
                    },
                    reject,
                });
                output({ type: "extension_ui_request", id, method: "editor", title, prefill });
            });
        },
        addAutocompleteProvider() {
            // Autocomplete provider composition is not supported in RPC mode
        },
        setEditorComponent() {
            // Custom editor components not supported in RPC mode
        },
        getEditorComponent() {
            // Custom editor components not supported in RPC mode
            return undefined;
        },
        getFooterDataProvider() {
            return {
                getGitBranch: () => null,
                getExtensionStatuses: () => new Map(),
                getAvailableProviderCount: () => 1,
                onBranchChange: () => () => { },
            };
        },
        get theme() {
            return theme;
        },
        getAllThemes() {
            return [];
        },
        getTheme(_name) {
            return undefined;
        },
        setTheme(_theme) {
            // Theme switching not supported in RPC mode
            return { success: false, error: "Theme switching not supported in RPC mode" };
        },
        getToolsExpanded() {
            // Tool expansion not supported in RPC mode - no TUI
            return false;
        },
        setToolsExpanded(_expanded) {
            // Tool expansion not supported in RPC mode - no TUI
        },
        getChatRenderSettings() {
            return {
                hideThinkingBlock: false,
                hiddenThinkingLabel: "Thinking...",
                toolOutputExpanded: false,
                showImages: false,
                imageWidthCells: 60,
                getToolDefinition: () => undefined,
                getCustomMessageRenderer: () => undefined,
            };
        },
    };
}
//# sourceMappingURL=rpc-extension-ui.js.map