import { readFileSync, readdirSync } from 'node:fs';
import { extname, join, relative, resolve } from 'node:path';

const root = resolve(import.meta.dirname, '..');
const ignored = new Set(['node_modules', '.git', 'runtime', 'logs', 'data', 'backups']);
const files = [];
function walk(dir) {
  for (const entry of readdirSync(dir, { withFileTypes: true })) {
    if (ignored.has(entry.name)) continue;
    const full = join(dir, entry.name);
    if (entry.isDirectory()) walk(full);
    else if (['.ps1', '.psm1', '.psd1'].includes(extname(entry.name).toLowerCase())) files.push(full);
  }
}
walk(root);

const allowedScopes = new Set(['global','local','script','private','using','env','function','variable','alias']);
const failures = [];
for (const file of files) {
  const raw = readFileSync(file);
  if (!(raw[0] === 0xef && raw[1] === 0xbb && raw[2] === 0xbf)) {
    failures.push(`${relative(root,file)}: Windows-PowerShell-Datei besitzt keine UTF-8-BOM.`);
  }
  const text = raw.toString('utf8');
  const lines = text.split(/\r?\n/);
  lines.forEach((line,index) => {
    const regex = /\$([A-Za-z_][A-Za-z0-9_]*):/g;
    for (const match of line.matchAll(regex)) {
      if (!allowedScopes.has(match[1].toLowerCase())) {
        failures.push(`${relative(root,file)}:${index+1}: ungültiger/mehrdeutiger Variablenverweis "${match[0]}"; ${'${'+match[1]+'}'}: verwenden.`);
      }
    }
  });
}

const required = [
  'scripts/updater/Vendoo.Updater.Preflight.ps1',
  'tools/verify-powershell-parser.ps1'
];
for (const file of required) {
  try { readFileSync(join(root,file)); } catch { failures.push(`Pflichtdatei fehlt: ${file}`); }
}

if (failures.length) {
  console.error(`PowerShell-Static-Gate fehlgeschlagen (${failures.length})`);
  for (const failure of failures) console.error(`- ${failure}`);
  process.exit(1);
}
console.log(`OK: PowerShell-Static-Gate – ${files.length} Dateien, UTF-8-BOM und Variablen-Doppelpunkt-Regression geprüft.`);
