'use strict';

var TYFYAP7W_cjs = require('./TYFYAP7W.cjs');
var DWHHPWIY_cjs = require('./DWHHPWIY.cjs');
var NSZHKDNY_cjs = require('./NSZHKDNY.cjs');
var VO65XOWD_cjs = require('./VO65XOWD.cjs');
var fs = require('fs');
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 fs__default = /*#__PURE__*/_interopDefault(fs);
var path__default = /*#__PURE__*/_interopDefault(path);
var process__default = /*#__PURE__*/_interopDefault(process);

// src/core/tool-executor.ts
VO65XOWD_cjs.init_cjs_shims();
zx.$.verbose = true;
zx.$.stdio = [
  "inherit",
  "pipe",
  process__default.default.stderr
];
function mergeVolumes(defaultVolumes, userVolumes) {
  const merged = [];
  const userPaths = new Set(userVolumes.map((v) => v.containerPath));
  merged.push(...userVolumes);
  for (const defaultVolume of defaultVolumes) {
    if (!userPaths.has(defaultVolume.containerPath)) {
      merged.push(defaultVolume);
    }
  }
  return merged;
}
VO65XOWD_cjs.__name(mergeVolumes, "mergeVolumes");
function getImageName(target, vmToolingName, version) {
  const repository = `${DWHHPWIY_cjs.AWS_ACCOUNT_ID}.dkr.ecr.${DWHHPWIY_cjs.AWS_REGION}.amazonaws.com/layerzerolabs`;
  const imageName = `${target}-tooling`;
  const tool = DWHHPWIY_cjs.findToolByName(vmToolingName);
  if (!tool) {
    throw new Error(`Tool '${vmToolingName}' not found`);
  }
  const matrix = DWHHPWIY_cjs.findMatrixByType(tool.toolType);
  if (!matrix) {
    throw new Error(`No version matrix found for tool type ${tool.toolType}`);
  }
  let foundCombination = null;
  let foundPatch;
  for (const combination of matrix.combinations) {
    const toolVersion = combination.versions[vmToolingName];
    if (toolVersion === version) {
      foundCombination = combination.versions;
      foundPatch = combination.patch;
      break;
    }
  }
  if (!foundCombination) {
    throw new Error(`No version combination found for tool ${vmToolingName} with version ${version}`);
  }
  const validVersions = {};
  for (const [toolName, toolVersion] of Object.entries(foundCombination)) {
    if (typeof toolVersion === "string" && toolVersion.length > 0) {
      validVersions[toolName] = toolVersion;
    }
  }
  const imageTag = getCombinationTag(validVersions, foundPatch);
  const imageURI = `${repository}/${imageName}:${imageTag}`;
  return {
    imageURI,
    imageTag
  };
}
VO65XOWD_cjs.__name(getImageName, "getImageName");
function getCombinationTag(input, patch, separator = "_") {
  return [
    ...Object.entries(input).filter(([_, value]) => value).sort().flat(),
    ...patch ? [
      "patch",
      patch
    ] : []
  ].join(separator);
}
VO65XOWD_cjs.__name(getCombinationTag, "getCombinationTag");
async function ensureDockerImage(imageURI, imageTag) {
  try {
    const checkResult = await zx.$`docker image ls ${imageURI}`.nothrow();
    if (checkResult.stdout.includes(imageTag)) {
      console.info(`\u2705 Using cached Docker image: ${imageURI}`);
      return;
    }
    console.info(`\u{1F4E5} Pulling Docker image from ECR: ${imageURI}`);
    const pullResult = await zx.$`docker pull ${imageURI}`.nothrow();
    if (pullResult.exitCode === 0) {
      console.info(`\u2705 Successfully pulled: ${imageURI}`);
      return;
    }
    const localImageName = imageURI.split("/").pop()?.replace(/:.*$/, "") || "";
    const localFallbackURI = `local-${localImageName}:latest`;
    const localCheckResult = await zx.$`docker image ls ${localFallbackURI}`.nothrow();
    if (localCheckResult.stdout.includes("local-")) {
      console.info(`\u{1F3E0} ECR image not available, using local fallback: ${localFallbackURI}`);
      await zx.$`docker tag ${localFallbackURI} ${imageURI}`;
      console.info(`\u{1F3F7}\uFE0F  Tagged local image as: ${imageURI}`);
      return;
    }
    throw new Error(`\u274C Docker image not available:
  - ECR image: ${imageURI} (pull failed)
  - Local fallback: ${localFallbackURI} (not found)

\u{1F4A1} Solutions:
  1. Authenticate with ECR: aws ecr get-login-password --region ${DWHHPWIY_cjs.AWS_REGION} | docker login --username AWS --password-stdin ${DWHHPWIY_cjs.AWS_ACCOUNT_ID}.dkr.ecr.${DWHHPWIY_cjs.AWS_REGION}.amazonaws.com
  2. Build local image: docker build -t ${localFallbackURI} <dockerfile-path>
  3. Check if the image tag exists in ECR`);
  } catch (error) {
    if (error instanceof Error && error.message.includes("\u274C Docker image not available")) {
      throw error;
    }
    throw new Error(`Failed to ensure Docker image ${imageURI}: ${error instanceof Error ? error.message : String(error)}`);
  }
}
VO65XOWD_cjs.__name(ensureDockerImage, "ensureDockerImage");
async function executeToolCommand(command, args, options) {
  const { cwd, volumes: userVolumes, customEntrypoint: entrypoint, env: customEnvVars, script } = options;
  const tool = DWHHPWIY_cjs.findToolByName(command);
  const type = DWHHPWIY_cjs.getToolType(command);
  if (!tool || type === void 0) {
    const { tools } = await import('./config/index.cjs');
    const availableTools = tools.map((t) => t.name).join(", ");
    throw new Error(`\u274C Tool '${command}' not found or no type configuration available.
Available tools: ${availableTools}
Try: lz-tool --list-versions to see all available tools`);
  }
  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 userSpecifiedVersions = TYFYAP7W_cjs.extractUserVersions(options);
  const versionResult = TYFYAP7W_cjs.resolveTypeVersions(type, userSpecifiedVersions, options, cwd);
  versionResult.warnings.forEach((warning) => {
    console.warn(warning);
  });
  const resolvedVersion = versionResult.resolvedVersions[command];
  if (typeof resolvedVersion !== "string" || resolvedVersion === "") {
    throw new Error(`No version resolved for tool ${command}`);
  }
  console.info(`\u{1F527} ${command} version: ${resolvedVersion}`);
  if (tool.getSecondaryVersionCheckValue) {
    try {
      const secondaryVersion = tool.getSecondaryVersionCheckValue({
        cwd
      });
      const resolvedVersionObj = {
        version: resolvedVersion
      };
      if (!DWHHPWIY_cjs.versionsSatisfied(secondaryVersion, resolvedVersionObj)) {
        console.warn(`Warning: Local configuration version (${secondaryVersion.version}) differs from resolved version (${resolvedVersion})`);
      }
    } catch (error) {
      console.warn(`Could not validate secondary version: ${error instanceof Error ? error.message : String(error)}`);
    }
  }
  let processOutput;
  {
    const { imageTag, imageURI } = getImageName(tool.fromImage, tool.name, resolvedVersion);
    const workspaceRoot = await commonNodeUtils.getFullyQualifiedRepoRootPath();
    const relPath = path__default.default.relative(workspaceRoot, cwd);
    const privileged = tool.privileged ?? false;
    await ensureDockerImage(imageURI, imageTag);
    const volumeArgs = volumes.map((volume) => {
      if (volume.type === "host") {
        return [
          "-v",
          `${volume.hostPath}:${volume.containerPath}`
        ];
      }
      const components = [
        "lz-tooling-cache",
        volume.name
      ];
      if (!volume.shared) {
        const packageName = process__default.default.env.npm_package_name;
        if (!packageName) {
          throw new Error("npm_package_name environment variable not defined");
        }
        components.push(path__default.default.basename(packageName));
      }
      return [
        "-v",
        `${components.join("-")}:${volume.containerPath}`
      ];
    }).flat();
    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 !== void 0 && 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",
      ...privileged ? [
        "--privileged"
      ] : [],
      "--rm",
      ...envArgs,
      "-v",
      `${workspaceRoot}:/workspace`,
      "-w",
      `/workspace/${relPath}`,
      ...volumeArgs,
      ...entrypoint === void 0 ? [] : [
        "--entrypoint",
        entrypoint
      ],
      imageURI,
      ...finalArgs
    ];
    processOutput = await NSZHKDNY_cjs.lockMany(volumes.flatMap((volume) => volume.type === "isolate" && volume.locked ? [
      volume.name
    ] : []), () => zx.$`docker ${dockerArgs}`.nothrow());
    saveAptosModulesOrder(command, processOutput, workspaceRoot, relPath);
  }
  const { exitCode } = processOutput;
  if (exitCode !== 0) {
    process__default.default.exit(exitCode ?? 1);
  }
}
VO65XOWD_cjs.__name(executeToolCommand, "executeToolCommand");
function saveAptosModulesOrder(command, processOutput, workspaceRoot, relPath) {
  if ("aptos" === command) {
    const outputJson = processOutput.json();
    const modules = outputJson.Result.map((item) => `${item.split("::")[1]}.mv`);
    fs__default.default.writeFileSync(path__default.default.join(workspaceRoot, relPath, "modules.json"), JSON.stringify(modules, null, 2));
  }
}
VO65XOWD_cjs.__name(saveAptosModulesOrder, "saveAptosModulesOrder");

exports.executeToolCommand = executeToolCommand;
exports.getCombinationTag = getCombinationTag;
//# sourceMappingURL=PH3AB77Z.cjs.map
//# sourceMappingURL=PH3AB77Z.cjs.map