'use strict';

var YNMZEV5X_cjs = require('./YNMZEV5X.cjs');
var ACDTMA6Q_cjs = require('./ACDTMA6Q.cjs');
var _6NIOUVPA_cjs = require('./6NIOUVPA.cjs');
var _36UU6CJU_cjs = require('./36UU6CJU.cjs');
var FOFSZBOK_cjs = require('./FOFSZBOK.cjs');
var U7VZULNU_cjs = require('./U7VZULNU.cjs');
var path = require('path');
var process = require('process');
var zx = require('zx');
var commonNodeUtils = require('@layerzerolabs/common-node-utils');

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

var path__default = /*#__PURE__*/_interopDefault(path);
var process__default = /*#__PURE__*/_interopDefault(process);

// src/core/tool-executor.ts
U7VZULNU_cjs.init_cjs_shims();
zx.$.verbose = true;
zx.$.stdio = [
  "inherit",
  "pipe",
  process__default.default.stderr
];
var mergeVolumes = /* @__PURE__ */ U7VZULNU_cjs.__name((defaultVolumes, userVolumes) => {
  const paths = new Set(userVolumes.map((volume) => volume.containerPath));
  return [
    ...userVolumes,
    ...defaultVolumes.filter((volume) => !paths.has(volume.containerPath))
  ];
}, "mergeVolumes");
async function ensureDockerImage(imageUri) {
  let output;
  try {
    output = await zx.$`docker image ls ${imageUri}`.nothrow();
    if (output.stdout.includes(imageUri)) {
      console.info(`\u2705 Using cached Docker image: ${imageUri}`);
      return;
    }
    console.info("\u{1F4E5} Pulling Docker image from ECR:", imageUri);
    output = await zx.$`docker pull ${imageUri}`.nothrow();
  } catch (error) {
    throw new Error(`Failed to pull Docker image ${imageUri}: ${YNMZEV5X_cjs.stringifyError(error)}`);
  }
  if (output.exitCode) {
    throw new Error([
      "Docker image not available:",
      `  - ECR image: ${imageUri} (pull failed)`,
      "",
      "\u{1F4A1} Solutions:",
      `  1. Authenticate with ECR: aws ecr get-login-password --region ${FOFSZBOK_cjs.AWS_REGION} | docker login --username AWS --password-stdin ${FOFSZBOK_cjs.AWS_ACCOUNT_ID}.dkr.ecr.${FOFSZBOK_cjs.AWS_REGION}.amazonaws.com`,
      "  2. Check if the image tag exists in ECR."
    ].join("\n"));
  }
  console.info(`\u2705 Successfully pulled: ${imageUri}`);
}
U7VZULNU_cjs.__name(ensureDockerImage, "ensureDockerImage");
async function executeToolCommand(command, args, { cwd, volumes: userVolumes, customEntrypoint: entrypoint, env: customEnvVars, script, publish, versions = {} }) {
  const tool = FOFSZBOK_cjs.findToolByName(command);
  const type = FOFSZBOK_cjs.getChainTypeForTool(command);
  if (!type) {
    throw new Error([
      `Tool '${command}' not found or no type configuration available.`,
      `Available tools: ${FOFSZBOK_cjs.tools.map(({ name }) => name).join(", ")}`,
      `Try: lz-tool --list-versions to see all available tools`
    ].join("\n"));
  }
  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 ${command}`);
    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 = ACDTMA6Q_cjs.resolveTypeVersions(type, versions)[command];
  if (!resolvedVersion) {
    throw new Error(`No version resolved for tool ${command}`);
  }
  console.info(`\u{1F527} ${command} version: ${resolvedVersion}`);
  if (tool.getSecondaryVersion) {
    try {
      const secondaryVersion = tool.getSecondaryVersion({
        cwd
      });
      if (!FOFSZBOK_cjs.versionsSatisfied(secondaryVersion, resolvedVersion)) {
        console.warn(`Warning: Local configuration version (${secondaryVersion}) differs from resolved version (${resolvedVersion})`);
      }
    } catch (error) {
      console.warn("Could not validate secondary version:", YNMZEV5X_cjs.stringifyError(error));
    }
  }
  const imageURI = _36UU6CJU_cjs.getImageUriForTool(tool.name, resolvedVersion);
  const workspaceRoot = await commonNodeUtils.getFullyQualifiedRepoRootPath();
  const relativePath = path__default.default.relative(workspaceRoot, cwd);
  await ensureDockerImage(imageURI);
  if (entrypoint?.trim()) {
    console.info(`\u{1F527} Using custom entrypoint: ${entrypoint}`);
  }
  const envArgs = customEnvVars.map((envVar) => [
    "-e",
    `${envVar.name}=${envVar.value}`
  ]).flat();
  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",
    ...envArgs,
    "-v",
    `${workspaceRoot}:/workspace`,
    "-w",
    `/workspace/${relativePath}`,
    ...publish ? [
      "-p",
      publish.trim()
    ] : [],
    ...volumes.map(_36UU6CJU_cjs.getVolumeName).flatMap((volume) => [
      "-v",
      volume
    ]),
    ...entrypoint ? [
      "--entrypoint",
      entrypoint
    ] : [],
    imageURI,
    ...finalArgs
  ];
  const output = await _6NIOUVPA_cjs.lockMany(volumes.flatMap((volume) => volume.type === "isolate" && volume.locked ? [
    volume.name
  ] : []), () => zx.$`docker ${dockerArgs}`.nothrow());
  if (output.exitCode) {
    throw new Error(`Failed to run Docker container (exit code: ${output.exitCode})`);
  }
  return output;
}
U7VZULNU_cjs.__name(executeToolCommand, "executeToolCommand");

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