import {
  installOpencodeWrapper
} from "./chunk-UY3VT3HQ.js";

// src/backends/opencode/setup.ts
var SENTINEL_NAME = ".claude-agents-opencode-installed";
async function prepareOpencodeOnSandbox(sandboxName, provider) {
  await installOpencodeWrapper(sandboxName, provider);
  const script = [
    "set -euo pipefail",
    `SENTINEL="$HOME/${SENTINEL_NAME}"`,
    'if [ -f "$SENTINEL" ]; then exit 0; fi',
    "npm install -g opencode-ai",
    "PREFIX=$(npm config get prefix)",
    // Only symlink if npm prefix differs from /usr/local — otherwise the
    // symlink overwrites npm's existing binary with a circular self-reference.
    // This happens on Docker/Apple containers where PREFIX=/usr/local.
    'if [ "$PREFIX" != "/usr/local" ]; then ln -sf "$PREFIX/bin/opencode" /usr/local/bin/opencode; fi',
    "/usr/local/bin/opencode --version || $PREFIX/bin/opencode --version",
    'touch "$SENTINEL"'
  ].join(" && ");
  const result = await provider.exec(sandboxName, ["bash", "-c", script], {
    timeoutMs: 5 * 6e4
    // 5 minutes — cold install typically <30s but leave headroom
  });
  if (result.exit_code !== 0) {
    throw new Error(
      `opencode install failed (${result.exit_code}): ${result.stderr.slice(0, 500)}`
    );
  }
}

export {
  prepareOpencodeOnSandbox
};
