#!/usr/bin/env node
import fs from 'fs';
import path from 'path';
import { spawnSync } from 'child_process';

const cwd = process.cwd();
const args = process.argv.slice(2);
const matchIdx = args.indexOf('--match');
const matchText = matchIdx >= 0 ? String(args[matchIdx + 1] || '').trim() : '';
const listOnly = args.includes('--list');

let tests = fs.readdirSync(cwd)
  .filter((file) => /^test-.*\.js$/.test(file))
  .sort();

if (matchText) {
  tests = tests.filter((file) => file.includes(matchText));
}

if (tests.length === 0) {
  console.error(`No tests found${matchText ? ` for --match ${matchText}` : ''}.`);
  process.exit(1);
}

if (listOnly) {
  for (const file of tests) console.log(file);
  process.exit(0);
}

const failures = [];

for (const file of tests) {
  console.log(`\n### ${file}`);
  const result = spawnSync(process.execPath, [path.join(cwd, file)], {
    cwd,
    encoding: 'utf8',
  });
  if (result.stdout) process.stdout.write(result.stdout);
  if (result.stderr) process.stderr.write(result.stderr);
  if (result.status !== 0) failures.push(file);
}

console.log(`\nSUMMARY total=${tests.length} failed=${failures.length}`);
if (failures.length) {
  for (const file of failures) console.log(file);
  process.exit(1);
}
