import { readdirSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { resolve } from 'node:path';
import { spawnSync } from 'node:child_process';
import { dirname } from 'node:path';
import { fileURLToPath } from 'node:url';

const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
const cases = [
  ['initial-modules', 'tools/verify-initial-disabled-modules-1.41.2.mjs', 'vendoo-win-cleanup-modules-'],
  ['controlled-invitations', 'tools/verify-controlled-invitations-1.42.0.mjs', 'vendoo-win-cleanup-invitations-'],
  ['capability-graph', 'tools/verify-capability-graph-1.41.2.mjs', 'vendoo-win-cleanup-capabilities-'],
  ['platform-architecture', 'tools/verify-platform-architecture-1.41.2.mjs', 'vendoo-win-cleanup-architecture-'],
];
const failures = [];

for (const [name, relativeFile, prefix] of cases) {
  for (let attempt = 1; attempt <= 3; attempt += 1) {
    const result = spawnSync(process.execPath, [resolve(root, relativeFile)], {
      cwd: root,
      env: { ...process.env, VENDOO_TEST_TEMP_PREFIX: prefix },
      encoding: 'utf8',
      timeout: 60_000,
    });
    if (result.status !== 0) {
      failures.push(`${name} Durchlauf ${attempt} scheiterte (${result.status}): ${(result.stderr || result.stdout || '').trim()}`);
      continue;
    }
    const leftovers = readdirSync(tmpdir()).filter((entry) => entry.startsWith(prefix));
    if (leftovers.length) failures.push(`${name} Durchlauf ${attempt} hinterließ Temp-Ordner: ${leftovers.join(', ')}`);
  }
}

if (failures.length) {
  console.error(`Windows-SQLite-Cleanup-Regression 1.43.0 fehlgeschlagen (${failures.length}):`);
  for (const failure of failures) console.error(`- ${failure}`);
  process.exit(1);
}
console.log('Windows-SQLite-Cleanup-Regression 1.43.0 erfolgreich: Initialmodule, Einladungen, Capability-Graph und Architektur liefen je dreimal isoliert ohne offene SQLite-Datei oder Temp-Rest.');
