#!/usr/bin/env node
import { spawnSync } from "node:child_process";
import { createRequire } from "node:module";
import path from "node:path";

const configs = process.argv.slice(2);
if (configs.length === 0) {
  console.error("No tsconfig paths provided.");
  process.exit(1);
}

const require = createRequire(import.meta.url);
const tscBin = require.resolve("typescript/bin/tsc");

const memoryLimit = process.env.TYPECHECK_MAX_OLD_SPACE || "2048";
const semiSpaceLimit = process.env.TYPECHECK_MAX_SEMI_SPACE || "128";
const cwd = process.cwd();

for (const config of configs) {
  const resolvedConfig = path.resolve(cwd, config);
  const title = path.relative(cwd, resolvedConfig);
  const tscArgs = ["-p", resolvedConfig, "--noEmit", "--pretty", "false"];

  const result = spawnSync(
    process.execPath,
    [
      `--max-old-space-size=${memoryLimit}`,
      `--max-semi-space-size=${semiSpaceLimit}`,
      tscBin,
      ...tscArgs,
    ],
    {
      stdio: "inherit",
      cwd,
    }
  );

  if (result.status !== 0) {
    console.error(`Type check failed while processing ${title}`);
    process.exit(result.status ?? 1);
  }
}
