"use strict";
/* Socket Lib - Built with esbuild */
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var socket_btm_exports = {};
__export(socket_btm_exports, {
  SOCKET_BTM_REPO: () => SOCKET_BTM_REPO,
  detectLibc: () => detectLibc,
  downloadSocketBtmRelease: () => downloadSocketBtmRelease,
  getBinaryAssetName: () => getBinaryAssetName,
  getBinaryName: () => getBinaryName,
  getPlatformArch: () => getPlatformArch
});
module.exports = __toCommonJS(socket_btm_exports);
var import_platform = require("../constants/platform");
var import_github_asset_url = require("./github-asset-url");
var import_github_listing = require("./github-listing");
var import_github_downloads = require("./github-downloads");
var import_fs = require("../node/fs");
var import_error = require("../primordials/error");
const SOCKET_BTM_REPO = {
  owner: "SocketDev",
  repo: "socket-btm"
};
const PLATFORM_MAP = {
  __proto__: null,
  darwin: "darwin",
  linux: "linux",
  win32: "win32"
};
const ARCH_MAP = {
  __proto__: null,
  arm64: "arm64",
  x64: "x64"
};
function detectLibc() {
  if ((0, import_platform.getPlatform)() !== "linux") {
    return void 0;
  }
  try {
    const fs = (0, import_fs.getNodeFs)();
    const muslPaths = [
      "/lib/ld-musl-x86_64.so.1",
      "/lib/ld-musl-aarch64.so.1",
      "/usr/lib/ld-musl-x86_64.so.1",
      "/usr/lib/ld-musl-aarch64.so.1"
    ];
    for (const path of muslPaths) {
      if (fs.existsSync(path)) {
        return "musl";
      }
    }
    return "glibc";
  } catch {
    return "glibc";
  }
}
async function downloadSocketBtmRelease(tool, options) {
  const config = { __proto__: null, ...options ?? {} };
  const { cwd, downloadDir, quiet = false, tag } = config;
  const toolPrefix = `${tool}-`;
  let downloadConfig;
  if (options && "asset" in options) {
    const assetConfig = {
      __proto__: null,
      ...options
    };
    const { asset, output, removeMacOSQuarantine = false } = assetConfig;
    let resolvedAsset;
    let resolvedTag = tag;
    const isExactMatch = typeof asset === "string" && !asset.includes("*");
    if (isExactMatch) {
      resolvedAsset = asset;
    } else {
      if (tag) {
        throw new import_error.ErrorCtor(
          "Cannot use asset pattern with explicit tag. Either provide exact asset name or omit tag."
        );
      }
      resolvedTag = await (0, import_github_listing.getLatestRelease)(toolPrefix, SOCKET_BTM_REPO, {
        assetPattern: asset
      }) ?? void 0;
      if (!resolvedTag) {
        throw new import_error.ErrorCtor(
          `No ${tool} release with matching asset pattern found`
        );
      }
      const assetUrl = await (0, import_github_asset_url.getReleaseAssetUrl)(
        resolvedTag,
        asset,
        SOCKET_BTM_REPO
      );
      if (!assetUrl) {
        throw new import_error.ErrorCtor(`No matching asset found in release ${resolvedTag}`);
      }
      resolvedAsset = assetUrl.split("/").pop() || asset.toString();
    }
    const outputName = output || resolvedAsset;
    const platformArch = "assets";
    downloadConfig = {
      owner: SOCKET_BTM_REPO.owner,
      repo: SOCKET_BTM_REPO.repo,
      ...cwd !== void 0 && { cwd },
      ...downloadDir !== void 0 && { downloadDir },
      toolName: tool,
      platformArch,
      binaryName: outputName,
      assetName: resolvedAsset,
      toolPrefix,
      ...resolvedTag !== void 0 && { tag: resolvedTag },
      quiet,
      removeMacOSQuarantine
    };
  } else {
    const binaryConfig = {
      __proto__: null,
      ...options
    };
    const {
      bin,
      libc = detectLibc(),
      removeMacOSQuarantine = true,
      targetArch = (0, import_platform.getArch)(),
      targetPlatform = (0, import_platform.getPlatform)()
    } = binaryConfig;
    const baseName = bin || tool;
    const assetName = getBinaryAssetName(
      baseName,
      targetPlatform,
      targetArch,
      libc
    );
    const platformArch = getPlatformArch(targetPlatform, targetArch, libc);
    const binaryName = getBinaryName(baseName, targetPlatform);
    downloadConfig = {
      owner: SOCKET_BTM_REPO.owner,
      repo: SOCKET_BTM_REPO.repo,
      ...cwd !== void 0 && { cwd },
      ...downloadDir !== void 0 && { downloadDir },
      toolName: tool,
      platformArch,
      binaryName,
      assetName,
      toolPrefix,
      ...tag !== void 0 && { tag },
      quiet,
      removeMacOSQuarantine
    };
  }
  return await (0, import_github_downloads.downloadGitHubRelease)(downloadConfig);
}
function getBinaryAssetName(binaryBaseName, platform, arch, libc) {
  const mappedArch = ARCH_MAP[arch];
  if (!mappedArch) {
    throw new import_error.ErrorCtor(`Unsupported architecture: ${arch}`);
  }
  const muslSuffix = platform === "linux" && libc === "musl" ? "-musl" : "";
  const ext = platform === "win32" ? ".exe" : "";
  if (platform === "darwin") {
    return `${binaryBaseName}-darwin-${mappedArch}${ext}`;
  }
  if (platform === "linux") {
    return `${binaryBaseName}-linux-${mappedArch}${muslSuffix}${ext}`;
  }
  if (platform === "win32") {
    return `${binaryBaseName}-win32-${mappedArch}${ext}`;
  }
  throw new import_error.ErrorCtor(`Unsupported platform: ${platform}`);
}
function getBinaryName(binaryBaseName, platform) {
  return platform === "win32" ? `${binaryBaseName}.exe` : binaryBaseName;
}
function getPlatformArch(platform, arch, libc) {
  const mappedPlatform = PLATFORM_MAP[platform];
  if (!mappedPlatform) {
    throw new import_error.ErrorCtor(`Unsupported platform: ${platform}`);
  }
  const mappedArch = ARCH_MAP[arch];
  if (!mappedArch) {
    throw new import_error.ErrorCtor(`Unsupported architecture: ${arch}`);
  }
  const muslSuffix = platform === "linux" && libc === "musl" ? "-musl" : "";
  return `${mappedPlatform}-${mappedArch}${muslSuffix}`;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  SOCKET_BTM_REPO,
  detectLibc,
  downloadSocketBtmRelease,
  getBinaryAssetName,
  getBinaryName,
  getPlatformArch
});
