import { spawn } from 'node:child_process';
import path from 'node:path';

// src/features/sh/infrastructure/runtime.ts
function resolveShellPath() {
  return process.env.SHELL?.trim() || "/bin/zsh";
}
function createShExecutionSpec(rawCommand) {
  const normalizedRawCommand = rawCommand.trim();
  const shellPath = resolveShellPath();
  const shellName = path.basename(shellPath);
  if (!normalizedRawCommand) {
    return {
      mode: "interactive",
      previewCommand: `${shellName} -i`,
      rawCommand: "",
      shellPath
    };
  }
  return {
    mode: "command",
    previewCommand: normalizedRawCommand,
    rawCommand: normalizedRawCommand,
    shellPath
  };
}
async function withTemporarySigintGuard(task) {
  const handleSigint = () => void 0;
  process.on("SIGINT", handleSigint);
  try {
    return await task();
  } finally {
    process.off("SIGINT", handleSigint);
  }
}
async function executeShCommand(spec, cwd) {
  return withTemporarySigintGuard(
    () => new Promise((resolve, reject) => {
      const args = spec.mode === "interactive" ? ["-i"] : ["-lc", spec.rawCommand];
      const child = spawn(spec.shellPath, args, {
        cwd,
        stdio: "inherit"
      });
      child.once("error", reject);
      child.once("close", (exitCode, signal) => {
        resolve({
          exitCode,
          liveOnly: true,
          signal
        });
      });
    })
  );
}
function formatShExitLabel(result) {
  return result.signal ? `signal=${result.signal}` : `exitCode=${result.exitCode ?? "null"}`;
}
function formatShExecutionOutput(spec, result) {
  return [
    spec.mode === "interactive" ? "\uC778\uD130\uB799\uD2F0\uBE0C shell \uC138\uC158\uC774 \uC885\uB8CC\uB418\uC5C8\uC2B5\uB2C8\uB2E4." : "shell \uBA85\uB839 \uC2E4\uD589\uC774 \uC885\uB8CC\uB418\uC5C8\uC2B5\uB2C8\uB2E4.",
    "\uCD9C\uB825\uC740 \uD130\uBBF8\uB110\uC5D0 \uC9C1\uC811 \uD45C\uC2DC\uB418\uC5C8\uACE0, history\uC5D0\uB294 \uC804\uCCB4 transcript\uB97C \uC800\uC7A5\uD558\uC9C0 \uC54A\uC558\uC2B5\uB2C8\uB2E4.",
    `\uC885\uB8CC \uC0C1\uD0DC: ${formatShExitLabel(result)}`
  ].join("\n");
}

export { createShExecutionSpec, executeShCommand, formatShExecutionOutput, formatShExitLabel };
