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

const root = resolve(import.meta.dirname, '..');
const roots = ['app', 'lib', 'public', 'scripts', 'tools'];
const rootFiles = ['bootstrap.mjs', 'server.mjs'];
const ignored = new Set(['node_modules', 'release-output', '.git', 'runtime', 'modules', 'updates', 'backups', 'uploads', 'logs']);
const files = [...rootFiles.map(name => join(root, name))];

function walk(directory) {
  for (const entry of readdirSync(directory, { withFileTypes: true })) {
    if (entry.isDirectory() && ignored.has(entry.name)) continue;
    const pathname = join(directory, entry.name);
    if (entry.isDirectory()) walk(pathname);
    else if (['.js', '.mjs', '.cjs'].includes(extname(entry.name))) files.push(pathname);
  }
}

for (const name of roots) {
  const directory = join(root, name);
  try { if (statSync(directory).isDirectory()) walk(directory); } catch {}
}

const failures = [];
for (const file of files.sort()) {
  const result = spawnSync(process.execPath, ['--check', file], { encoding: 'utf8' });
  if (result.status !== 0) failures.push(`${relative(root, file).split(sep).join('/')}\n${result.stderr || result.stdout}`);
}

if (failures.length) {
  console.error(`Syntaxprüfung fehlgeschlagen (${failures.length}):`);
  for (const failure of failures) console.error(`\n${failure}`);
  process.exit(1);
}
console.log(`Syntaxprüfung erfolgreich: ${files.length} JavaScript-/MJS-/CJS-Dateien geprüft.`);
