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

const root = resolve(import.meta.dirname, '..');
const gate = resolve(root, 'tools', 'verify-initial-disabled-modules-1.41.2.mjs');
const prefix = `vendoo-module-defaults-regression-${process.pid}-${Date.now()}-`;
const failures = [];

for (let attempt = 1; attempt <= 3; attempt += 1) {
  const result = spawnSync(process.execPath, [gate], {
    cwd: root,
    env: { ...process.env, VENDOO_TEST_TEMP_PREFIX: prefix },
    encoding: 'utf8',
    timeout: 60_000,
  });
  if (result.error) failures.push(`Durchlauf ${attempt}: ${result.error.message}`);
  if (result.status !== 0) {
    failures.push(`Durchlauf ${attempt}: Exit-Code ${result.status}
${result.stdout || ''}
${result.stderr || ''}`.trim());
  }
}

const leftovers = readdirSync(tmpdir(), { withFileTypes: true })
  .filter(entry => entry.isDirectory() && entry.name.startsWith(prefix))
  .map(entry => entry.name);
if (leftovers.length) failures.push(`Temporäre Testordner wurden nicht entfernt: ${leftovers.join(', ')}`);

if (failures.length) {
  console.error(`Initial-Module-Cleanup-Regression 1.43.0 fehlgeschlagen (${failures.length}):`);
  failures.forEach(item => console.error(`- ${item}`));
  process.exit(1);
}
console.log('Initial-Module-Cleanup-Regression 1.43.0 erfolgreich: drei isolierte Durchläufe ohne offene SQLite-Datei oder Temp-Rest.');
