/**
 * Runs every scripts/*-smoke.ts and reports one verdict.
 *
 * The smokes are this project's test suite — they carry far more of its
 * behaviour than the unit tests do — and until now there was no way to run them
 * except one command per file, from memory. Nothing in CI or the deploy touched
 * them, so "the suite passes" was a claim nobody could check cheaply.
 *
 * They share a live database, so they run one at a time: each seeds its own
 * ZZ-prefixed fixture and purges it, and running two at once would have them
 * purging each other's rows.
 *
 * Run: cd apps/api && npm run smoke
 *      cd apps/api && npm run smoke -- deposit      (only matching files)
 */
import { execFileSync } from 'node:child_process';
import { readdirSync } from 'node:fs';
import { join } from 'node:path';

const HERE = __dirname;
const filter = process.argv.slice(2).filter((a) => !a.startsWith('-'));

const files = readdirSync(HERE)
  .filter((f) => f.endsWith('-smoke.ts'))
  .filter((f) => filter.length === 0 || filter.some((q) => f.includes(q)))
  .sort();

if (files.length === 0) {
  console.log(filter.length ? `No smoke matches ${filter.join(', ')}` : 'No smokes found');
  process.exit(1);
}

interface Result {
  file: string;
  passed: number;
  failed: number;
  ok: boolean;
  ms: number;
  output: string;
}

const results: Result[] = [];
console.log(`Running ${files.length} smoke${files.length === 1 ? '' : 's'}\n`);

for (const file of files) {
  const started = Date.now();
  let output = '';
  let ok = true;
  try {
    output = execFileSync(
      process.execPath,
      [require.resolve('ts-node/dist/bin.js'), '-P', join(HERE, '..', 'tsconfig.json'), join(HERE, file)],
      { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], cwd: join(HERE, '..') },
    );
  } catch (err) {
    ok = false;
    const e = err as { stdout?: string; stderr?: string };
    output = `${e.stdout ?? ''}${e.stderr ?? ''}`;
  }
  // Each smoke ends with "==== N passed, M failed ====".
  const m = /(\d+) passed, (\d+) failed/.exec(output);
  const passed = m ? Number(m[1]) : 0;
  const failed = m ? Number(m[2]) : 0;
  // No summary line at all means it died before finishing — not a pass.
  const finished = m !== null;
  results.push({ file, passed, failed, ok: ok && finished && failed === 0, ms: Date.now() - started, output });

  const last = results[results.length - 1];
  const mark = last.ok ? '✓' : '✗';
  const detail = finished ? `${passed} passed, ${failed} failed` : 'did not finish';
  console.log(`  ${mark} ${file.padEnd(32)} ${detail.padEnd(24)} ${(last.ms / 1000).toFixed(1)}s`);
}

const bad = results.filter((r) => !r.ok);
if (bad.length) {
  console.log(`\n${'='.repeat(72)}`);
  for (const r of bad) {
    console.log(`\n--- ${r.file} ---`);
    // The failing assertions and anything after them; the passes are noise here.
    const lines = r.output.split('\n');
    const from = Math.max(0, lines.findIndex((l) => l.includes('✗') || l.includes('FATAL')));
    console.log(lines.slice(from).join('\n').trim());
  }
}

const totalPassed = results.reduce((s, r) => s + r.passed, 0);
const totalFailed = results.reduce((s, r) => s + r.failed, 0);
const seconds = (results.reduce((s, r) => s + r.ms, 0) / 1000).toFixed(0);
console.log(
  `\n${bad.length === 0 ? 'OK' : 'FAILED'}: ${results.length} smokes, ${totalPassed} assertions, ${totalFailed} failed, ${bad.length} script(s) not green, ${seconds}s`,
);
process.exit(bad.length === 0 ? 0 : 1);
