'use strict';

var T3GK7LED_cjs = require('./T3GK7LED.cjs');
var A5X4BLYY_cjs = require('./A5X4BLYY.cjs');
var _533SFXIE_cjs = require('./533SFXIE.cjs');
var _2Z4Y2ZR3_cjs = require('./2Z4Y2ZR3.cjs');
var _5GPMTH2I_cjs = require('./5GPMTH2I.cjs');
var XFDJEDQJ_cjs = require('./XFDJEDQJ.cjs');
var _24WEKBY3_cjs = require('./24WEKBY3.cjs');
var esToolkit = require('es-toolkit');
var os = require('os');
var path = require('path');
var process = require('process');
var semver = require('semver');
var zx = require('zx');

function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

function _interopNamespace(e) {
  if (e && e.__esModule) return e;
  var n = Object.create(null);
  if (e) {
    Object.keys(e).forEach(function (k) {
      if (k !== 'default') {
        var d = Object.getOwnPropertyDescriptor(e, k);
        Object.defineProperty(n, k, d.get ? d : {
          enumerable: true,
          get: function () { return e[k]; }
        });
      }
    });
  }
  n.default = e;
  return Object.freeze(n);
}

var os__default = /*#__PURE__*/_interopDefault(os);
var path__default = /*#__PURE__*/_interopDefault(path);
var process__default = /*#__PURE__*/_interopDefault(process);
var semver__namespace = /*#__PURE__*/_interopNamespace(semver);

// src/core/tool-executor.ts
_24WEKBY3_cjs.init_cjs_shims();
var getHostUserIds = /* @__PURE__ */ _24WEKBY3_cjs.__name(() => {
  const userInfo = os__default.default.userInfo();
  if (userInfo.uid === -1 || userInfo.gid === -1) {
    return void 0;
  }
  return {
    uid: userInfo.uid,
    gid: userInfo.gid
  };
}, "getHostUserIds");
zx.$.verbose = true;
zx.$.stdio = [
  "inherit",
  "pipe",
  process__default.default.stderr
];
var mergeVolumes = /* @__PURE__ */ _24WEKBY3_cjs.__name((defaultVolumes, userVolumes) => esToolkit.uniqBy([
  ...userVolumes,
  ...defaultVolumes
], (volume) => volume.containerPath), "mergeVolumes");
var resolveVolumePaths = /* @__PURE__ */ _24WEKBY3_cjs.__name((volumes, workspaceRoot) => volumes.map((volume) => volume.type === "host" ? {
  ...volume,
  hostPath: path__default.default.resolve(workspaceRoot, volume.hostPath.replace(/^~/, os__default.default.homedir()))
} : volume), "resolveVolumePaths");
var ensureDockerImage = /* @__PURE__ */ _24WEKBY3_cjs.__name(async (imageUri) => {
  let output;
  try {
    output = await zx.$`docker image inspect --format {{.Id}} ${imageUri}`.nothrow().quiet();
    if (!output.exitCode) {
      console.info(`\u2705 Using cached Docker image: ${imageUri}`);
      return;
    }
    console.info("\u{1F4E5} Pulling Docker image from:", imageUri);
    output = await zx.$`docker pull ${imageUri}`.nothrow();
  } catch (error) {
    throw new Error(`Failed to pull Docker image ${imageUri}: ${T3GK7LED_cjs.stringifyError(error)}`);
  }
  if (output.exitCode) {
    throw new Error([
      "Docker image not available:",
      `  - Image: ${imageUri} (pull failed)`,
      "  - Check if the image tag exists in image registry."
    ].join("\n"));
  }
  console.info(`\u2705 Successfully pulled: ${imageUri}`);
}, "ensureDockerImage");
async function executeToolCommand(context, toolName, args, { cwd, volumes: userVolumes, customEntrypoint: entrypoint, env: customEnvVars, script, publish, versions = {} }) {
  const tool = _5GPMTH2I_cjs.findToolByName(context, toolName);
  if (tool.preExecute) {
    await tool.preExecute(context, {
      cwd,
      args,
      volumes: userVolumes,
      env: customEnvVars,
      script,
      publish,
      versions
    });
  }
  const defaultVolumes = tool.defaultVolumes ?? [];
  const volumes = mergeVolumes(defaultVolumes, userVolumes);
  if (defaultVolumes.length > 0) {
    console.info(`\u{1F4E6} Using ${defaultVolumes.length} default cache volume(s) for ${tool.name}`);
    if (userVolumes.length > 0) {
      const overrides = userVolumes.filter((uv) => defaultVolumes.some((dv) => dv.containerPath === uv.containerPath));
      if (overrides.length > 0) {
        console.info(`\u{1F527} User volumes override ${overrides.length} default volume(s)`);
      }
    }
  }
  const resolvedVersion = A5X4BLYY_cjs.resolveTypeVersions(context, versions)[tool.name];
  if (!resolvedVersion) {
    throw new Error(`No version resolved for tool ${tool.name}`);
  }
  console.info(`\u{1F527} ${tool.name} version: ${resolvedVersion}`);
  if (tool.getSecondaryVersion) {
    try {
      const secondaryVersion = await tool.getSecondaryVersion({
        cwd
      });
      if (!semver__namespace.satisfies(secondaryVersion, resolvedVersion)) {
        console.warn(`Warning: Local configuration version (${secondaryVersion}) differs from resolved version (${resolvedVersion})`);
      }
    } catch (error) {
      console.warn("Could not validate secondary version:", T3GK7LED_cjs.stringifyError(error));
    }
  }
  const imageUri = await _533SFXIE_cjs.getImageUriForTool(context, tool.name, resolvedVersion);
  const workspaceRoot = await _2Z4Y2ZR3_cjs.findWorkspaceRoot(cwd);
  const relativePath = path__default.default.relative(workspaceRoot, cwd);
  await ensureDockerImage(imageUri);
  if (entrypoint?.trim()) {
    console.info(`\u{1F527} Using custom entrypoint: ${entrypoint}`);
  }
  const defaultEnv = tool.defaultEnv ?? [];
  const hasDockerSocketMount = volumes.some((v) => v.type === "host" && v.containerPath === "/var/run/docker.sock");
  const dockerSocketEnv = hasDockerSocketMount ? [
    {
      name: "HOST_CWD",
      value: cwd
    },
    {
      name: "HOST_WORKSPACE_ROOT",
      value: workspaceRoot
    }
  ] : [];
  const envArgs = esToolkit.uniqBy([
    ...customEnvVars,
    ...dockerSocketEnv,
    ...defaultEnv
  ], ({ name }) => name).flatMap(({ name, value }) => [
    "-e",
    `${name}=${value}`
  ]);
  const hostUserIds = getHostUserIds();
  const userIdEnvArgs = hostUserIds ? [
    "-e",
    `LOCAL_UID=${hostUserIds.uid}`,
    "-e",
    `LOCAL_GID=${hostUserIds.gid}`
  ] : [];
  console.info(`\u{1F464} Running container as UID:GID ${hostUserIds?.uid}:${hostUserIds?.gid}`);
  if (defaultEnv.length > 0) {
    console.info(`\u{1F30D} Using ${defaultEnv.length} default environment variable(s) for ${tool.name}`);
  }
  if (customEnvVars.length > 0) {
    console.info(`\u{1F30D} Using ${customEnvVars.length} custom environment variable(s)`);
  }
  let finalArgs;
  if (script && script.trim() !== "") {
    console.info(`\u{1F4DC} Executing custom script: ${script}`);
    finalArgs = [
      "bash",
      "-c",
      script
    ];
  } else {
    finalArgs = entrypoint === void 0 ? [
      tool.name,
      ...args
    ] : args;
  }
  const dockerArgs = [
    "run",
    ...tool.privileged ? [
      "--privileged"
    ] : [],
    "--rm",
    "--add-host=host.docker.internal:host-gateway",
    ...envArgs,
    ...userIdEnvArgs,
    "-v",
    `${workspaceRoot}:/workspace`,
    "-w",
    `/workspace/${relativePath}`,
    ...(publish ?? []).flatMap((p) => [
      "-p",
      p.trim()
    ]),
    ...resolveVolumePaths(volumes, workspaceRoot).flatMap((volume) => [
      "-v",
      _533SFXIE_cjs.getVolumeName(volume)
    ]),
    ...entrypoint ? [
      "--entrypoint",
      entrypoint
    ] : [],
    imageUri,
    ...finalArgs
  ];
  const output = await XFDJEDQJ_cjs.lockMany(volumes.flatMap((volume) => volume.type === "isolate" && volume.locked ? [
    volume.name
  ] : []), async () => {
    const label = `\u23F1\uFE0F ${finalArgs.join(" ")}`;
    console.time(label);
    const result = await zx.$`docker ${dockerArgs}`.nothrow();
    console.timeEnd(label);
    return result;
  });
  if (output.exitCode) {
    const stdout = output.stdout.trim();
    throw new Error(`Failed to run Docker container (exit code: ${output.exitCode})${stdout ? `
${stdout}` : ""}`);
  }
  return output;
}
_24WEKBY3_cjs.__name(executeToolCommand, "executeToolCommand");

exports.executeToolCommand = executeToolCommand;
//# sourceMappingURL=YBZF5XJV.cjs.map
//# sourceMappingURL=YBZF5XJV.cjs.map