import { readFileSync, readdirSync, statSync } from 'fs';
import { join } from 'path';

const root = new URL('..', import.meta.url).pathname;
const read = rel => readFileSync(join(root, rel), 'utf8');
const failures = [];
const expect = (text, marker, label = marker) => { if (!text.includes(marker)) failures.push(`Fehlt: ${label}`); };

const pkg = JSON.parse(read('package.json'));
const lock = JSON.parse(read('package-lock.json'));
const manifest = JSON.parse(read('update-manifest.json'));
const server = read('server.mjs');
const runtimePaths = read('lib/runtime-paths.mjs');
const dockerfile = read('Dockerfile');
const compose = read('compose.yaml');
const env = read('.env.example');
const html = read('public/index.html');
const app = read('public/app.js');
const setup = read('setup.ps1');
const workflow = read('local-ai/workflows/vendoo_flux_schnell_api.json');

for (const [label, value] of [
  ['package.json', pkg.version], ['package-lock.json', lock.version],
  ['package-lock root', lock.packages?.['']?.version], ['update-manifest', manifest.version],
]) if (value !== '1.32.0') failures.push(`${label}-Version ist ${value}`);

for (const marker of ['content="1.32.0"', 'style.css?v=1.32.0', 'app.js?v=1.32.0']) expect(html, marker, `UI-Build ${marker}`);
if (!app.startsWith("const VENDOO_UI_BUILD = '1.32.0';")) failures.push('UI-Build ist nicht 1.32.0');
for (const marker of ["$Version = '1.32.0'", '?build=1.32.0']) expect(setup, marker, `Windows-Setup ${marker}`);

for (const marker of [
  "app.get('/healthz'", "app.get('/readyz'", 'gracefulShutdown', "process.once('SIGTERM'",
  'verifyRuntimeWritable', 'VENDOO_SETUP_TOKEN', 'VENDOO_EXTENSION_ORIGINS', 'setup_required: true',
  "app.use('/uploads', requireAuth", 'allowed.includes(ext) && isImageMime',
]) expect(server, marker);

for (const marker of ['VENDOO_DATA_DIR', 'VENDOO_DB_PATH', 'VENDOO_UPLOADS_DIR', 'VENDOO_BACKUP_DIR', 'VENDOO_OPERATIONS_DIR']) expect(runtimePaths, marker);


if (server.includes('if (isSetupMode()) return next();')) failures.push('Unsichere globale Auth-Ausnahme im Setup-Modus ist noch vorhanden');

for (const forbiddenMarker of [
  "resolve(__dirname, 'uploads')", "resolve(__dirname, 'uploads',", "join(__dirname, 'uploads',",
  "join(__dirname, 'logs'", "join(root, 'uploads')", "join(root, 'db')",
]) if (server.includes(forbiddenMarker)) failures.push(`Server enthält noch codegebundenen Laufzeitpfad: ${forbiddenMarker}`);
for (const marker of ['FROM node:22-bookworm-slim', 'npm ci --omit=dev', 'USER node', 'HEALTHCHECK', 'ENTRYPOINT']) expect(dockerfile, marker);
for (const marker of ['read_only: true', 'no-new-privileges:true', 'cap_drop:', 'vendoo_db:', 'vendoo_uploads:', 'vendoo_backups:', '/readyz', 'pids_limit: 256', 'max-size: "10m"']) expect(compose, marker);
for (const marker of ['VENDOO_SETUP_TOKEN=', 'VENDOO_COOKIE_SECURE=', 'VENDOO_COOKIE_SAMESITE=', 'VENDOO_EXTENSION_ORIGINS=']) expect(env, marker);
if (workflow.includes('LoadImage')) failures.push('Freier FLUX-Workflow enthält LoadImage');

function walk(dir, rel = '') {
  const out = [];
  for (const name of readdirSync(dir)) {
    const path = join(dir, name); const child = join(rel, name);
    if (statSync(path).isDirectory()) out.push(...walk(path, child)); else out.push(child.replaceAll('\\', '/'));
  }
  return out;
}
const forbidden = walk(root).filter(rel =>
  /(^|\/)(vendoo\.db|\.env|node_modules|uploads|backups|operations|logs|runtime|data)(\/|$)/i.test(rel)
  && rel !== '.env.example'
);
if (forbidden.length) failures.push(`Verbotene Laufzeitdaten im Paket: ${forbidden.slice(0, 10).join(', ')}`);

if (failures.length) {
  console.error(`Deployment-Gate 1.32.0 fehlgeschlagen (${failures.length}):`);
  failures.forEach(item => console.error(`- ${item}`));
  process.exit(1);
}
console.log('Deployment-Gate 1.32.0 erfolgreich: Versionen, Pfadtrennung, Container-Härtung, Readiness, Shutdown, Setup-Schutz und Datenhygiene geprüft.');
