import { waitForRawStdoutBackpressure } from "../../core/output-guard.js";
import { createRpcErrorResponse, formatRpcErrorMessage } from "./rpc-responses.js";
function isRpcExtensionUIResponse(value) {
    return (typeof value === "object" &&
        value !== null &&
        "type" in value &&
        value.type === "extension_ui_response" &&
        "id" in value &&
        typeof value.id === "string");
}
function getCommandIdentity(command) {
    if (typeof command !== "object" || command === null) {
        return { id: undefined, type: "unknown" };
    }
    const id = "id" in command && typeof command.id === "string" ? command.id : undefined;
    const type = "type" in command && typeof command.type === "string" ? command.type : "unknown";
    return { id, type };
}
export function createRpcInputLineHandler({ output, pendingExtensionRequests, handleCommand, checkShutdownRequested, }) {
    return async (line) => {
        let parsed;
        try {
            parsed = JSON.parse(line);
        }
        catch (parseError) {
            output(createRpcErrorResponse(undefined, "parse", `Failed to parse command: ${formatRpcErrorMessage(parseError)}`));
            await waitForRawStdoutBackpressure();
            return;
        }
        if (isRpcExtensionUIResponse(parsed)) {
            const pending = pendingExtensionRequests.get(parsed.id);
            if (pending) {
                pendingExtensionRequests.delete(parsed.id);
                pending.resolve(parsed);
            }
            return;
        }
        const command = parsed;
        try {
            const response = await handleCommand(command);
            if (response) {
                output(response);
                await waitForRawStdoutBackpressure();
            }
            await checkShutdownRequested();
        }
        catch (commandError) {
            const identity = getCommandIdentity(command);
            output(createRpcErrorResponse(identity.id, identity.type, formatRpcErrorMessage(commandError)));
            await waitForRawStdoutBackpressure();
        }
    };
}
//# sourceMappingURL=rpc-input.js.map