#!/usr/bin/env node
// shuire npm shim: locate the prebuilt binary shipped by the
// platform-specific optional dependency and execute it with inherited stdio.

const { spawnSync } = require("node:child_process");
const path = require("node:path");

const PLATFORMS = {
  "linux x64": "shuire-linux-x64",
  "linux arm64": "shuire-linux-arm64",
  "darwin x64": "shuire-darwin-x64",
  "darwin arm64": "shuire-darwin-arm64",
  "win32 x64": "shuire-win32-x64",
};

function resolveBinary() {
  const key = `${process.platform} ${process.arch}`;
  const pkg = PLATFORMS[key];
  if (!pkg) {
    console.error(
      `shuire: no prebuilt binary available for ${key}.\n` +
        `Supported targets: ${Object.values(PLATFORMS).join(", ")}.\n` +
        `You can build from source instead: cargo install shuire`,
    );
    process.exit(1);
  }

  let pkgJsonPath;
  try {
    pkgJsonPath = require.resolve(`${pkg}/package.json`);
  } catch (err) {
    console.error(
      `shuire: expected optional dependency "${pkg}" was not installed.\n` +
        `This usually means npm skipped optionalDependencies (e.g. --no-optional) ` +
        `or the install ran on an unsupported platform.\n` +
        `Try reinstalling: npm install shuire`,
    );
    process.exit(1);
  }

  const binaryName = process.platform === "win32" ? "shuire.exe" : "shuire";
  return path.join(path.dirname(pkgJsonPath), "bin", binaryName);
}

function main() {
  const binary = resolveBinary();
  const result = spawnSync(binary, process.argv.slice(2), {
    stdio: "inherit",
  });

  if (result.error) {
    const hint =
      result.error.code === "ENOENT"
        ? `missing binary at ${binary} (optional dependency may be corrupt)`
        : result.error.message;
    console.error(`shuire: failed to execute binary: ${hint}`);
    process.exit(1);
  }

  if (result.signal) {
    process.kill(process.pid, result.signal);
    return;
  }

  process.exit(result.status ?? 0);
}

main();
