import { readdirSync, statSync } from 'node:fs';
import { join } from 'node:path';
import { spawnSync } from 'node:child_process';

function collectTestFiles(dir) {
  const out = [];
  for (const entry of readdirSync(dir)) {
    const full = join(dir, entry);
    const stat = statSync(full);
    if (stat.isDirectory()) out.push(...collectTestFiles(full));
    if (stat.isFile() && full.endsWith('.test.js')) out.push(full);
  }
  return out;
}

const root = process.argv[2] || '.tmp-test';
const files = collectTestFiles(root);

if (files.length === 0) {
  console.error(`No compiled .test.js files found under ${root}`);
  process.exit(1);
}

const result = spawnSync(process.execPath, ['--test', ...files], { stdio: 'inherit' });
process.exit(result.status ?? 1);
