import { countOutputLines, LONG_COMMAND_LINE_LIMIT, toDisplayPath, writeCommandArtifactFile, } from "./commandArtifacts.js";
function quotePosixShellArg(value) {
    return `'${value.replace(/'/g, "'\\''")}'`;
}
function quoteWindowsCmdPath(value) {
    return `"${value.replace(/"/g, '""')}"`;
}
export function shellExecutable() {
    if (process.platform === "win32") {
        return {
            command: process.env.ComSpec || "cmd.exe",
            argsPrefix: ["/d", "/c"],
            scriptExtension: "cmd",
            scriptInvocation: (scriptPath) => `call ${quoteWindowsCmdPath(scriptPath)}`,
        };
    }
    return {
        command: process.env.SHELL || "/bin/sh",
        argsPrefix: ["-lc"],
        scriptExtension: "sh",
        scriptInvocation: (scriptPath) => `sh ${quotePosixShellArg(scriptPath)}`,
    };
}
function buildCommandFileContent(commandText, scriptExtension) {
    const commandWithTrailingLineBreak = commandText.endsWith("\n")
        ? commandText
        : `${commandText}\n`;
    return scriptExtension === "cmd"
        ? `@echo off\r\n${commandWithTrailingLineBreak}`
        : commandWithTrailingLineBreak;
}
export async function prepareShellCommand(commandText, workspaceRoot, shell) {
    const commandLineCount = countOutputLines(commandText);
    if (commandLineCount <= LONG_COMMAND_LINE_LIMIT) {
        return { commandText, originalCommandText: commandText, commandLineCount };
    }
    const commandFilePath = await writeCommandArtifactFile(workspaceRoot, "cmd", shell.scriptExtension, buildCommandFileContent(commandText, shell.scriptExtension));
    return {
        commandText: shell.scriptInvocation(commandFilePath),
        originalCommandText: commandText,
        commandLineCount,
        commandFilePath: toDisplayPath(commandFilePath),
    };
}
