#!/usr/bin/env node
import { spawn, spawnSync } from "node:child_process";
import { existsSync, mkdirSync } from "node:fs";
import { homedir } from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";

const sdkVersion = "^1.25.0";
const zodVersion = "^3.25.0";
const cacheRoot = resolveCacheRoot();
const sdkMarker = path.join(cacheRoot, "node_modules", "@modelcontextprotocol", "sdk", "package.json");

if (!existsSync(sdkMarker)) {
  mkdirSync(cacheRoot, { recursive: true });

  const installResult = spawnSync(
    "npm",
    [
      "install",
      "--no-audit",
      "--no-fund",
      "--prefix",
      cacheRoot,
      `@modelcontextprotocol/sdk@${sdkVersion}`,
      `zod@${zodVersion}`,
    ],
    {
      encoding: "utf-8",
      env: {
        ...process.env,
        npm_config_loglevel: "error",
      },
    },
  );

  if (installResult.stdout) {
    process.stderr.write(installResult.stdout);
  }
  if (installResult.stderr) {
    process.stderr.write(installResult.stderr);
  }

  if (installResult.status !== 0) {
    process.exit(installResult.status ?? 1);
  }
}

const env = {
  ...process.env,
  MCP_MODULES_DIR: cacheRoot,
};

const entryPath = fileURLToPath(new URL("./index.js", import.meta.url));
const child = spawn(process.execPath, [entryPath], {
  stdio: "inherit",
  env,
});

child.on("exit", (code) => {
  process.exit(code ?? 0);
});

function resolveCacheRoot() {
  if (process.env.MCP_ORY_HYDRA_CACHE_DIR) {
    return process.env.MCP_ORY_HYDRA_CACHE_DIR;
  }

  const baseCache = process.env.XDG_CACHE_HOME ?? path.join(homedir(), ".cache");
  return path.join(baseCache, "mcp-ory-hydra");
}
