import { readFileSync, readdirSync, statSync, existsSync } from 'fs';
import { resolve, extname, relative } from 'path';
import { spawnSync } from 'child_process';

const root = resolve(new URL('..', import.meta.url).pathname);
const failures = [];
const summary = { js_files: 0, json_files: 0, html_ids: 0, css_blocks: 0 };

function walk(dir) {
  return readdirSync(dir, { withFileTypes: true }).flatMap(entry => {
    const full = resolve(dir, entry.name);
    if (entry.isDirectory()) return ['node_modules', '.git', 'uploads'].includes(entry.name) ? [] : walk(full);
    return [full];
  });
}

const files = walk(root);
for (const file of files) {
  const ext = extname(file).toLowerCase();
  if (['.js', '.mjs'].includes(ext)) {
    summary.js_files += 1;
    const result = spawnSync(process.execPath, ['--check', file], { encoding: 'utf8' });
    if (result.status !== 0) failures.push(`${relative(root, file)}: ${result.stderr.trim()}`);
  }
  if (ext === '.json') {
    summary.json_files += 1;
    try { JSON.parse(readFileSync(file, 'utf8').replace(/^\uFEFF/, '')); }
    catch (error) { failures.push(`${relative(root, file)}: ungültiges JSON (${error.message})`); }
  }
}

const pkg = JSON.parse(readFileSync(resolve(root, 'package.json'), 'utf8'));
if (pkg.version !== '1.26.1') failures.push(`package.json-Version ist ${pkg.version}`);
const html = readFileSync(resolve(root, 'public/index.html'), 'utf8');
const app = readFileSync(resolve(root, 'public/app.js'), 'utf8');
const css = readFileSync(resolve(root, 'public/style.css'), 'utf8');
const server = readFileSync(resolve(root, 'server.mjs'), 'utf8');
summary.html_ids = [...html.matchAll(/\bid="([^"]+)"/g)].length;
summary.css_blocks = (css.match(/{/g) || []).length;
if (summary.css_blocks !== (css.match(/}/g) || []).length) failures.push('CSS-Klammern unausgeglichen');

for (const marker of ['content="1.26.1"', 'style.css?v=1.26.1', 'app.js?v=1.26.1']) {
  if (!html.includes(marker)) failures.push(`Build-Marker fehlt: ${marker}`);
}
if (!app.startsWith("const VENDOO_UI_BUILD = '1.26.1';")) failures.push('UI-Build ist nicht 1.26.1');
for (const marker of ["app.get('/healthz'", "app.get('/api/admin/diagnostics'", "db.pragma('quick_check'", 'probeComfyUi']) {
  if (!server.includes(marker)) failures.push(`Server-Diagnose fehlt: ${marker}`);
}
for (const path of [
  'extensions/chrome/manifest.json', 'extensions/edge/manifest.json',
  'extensions/firefox/manifest.json', 'extensions/safari/web-extension/manifest.json',
  'local-ai/workflows/vendoo_flux_schnell_api.json',
]) if (!existsSync(resolve(root, path))) failures.push(`Pflichtdatei fehlt: ${path}`);

const forbidden = ['FASHN', 'virtual_tryon', 'LoadImage'];
const workflow = readFileSync(resolve(root, 'local-ai/workflows/vendoo_flux_schnell_api.json'), 'utf8');
if (workflow.includes('LoadImage')) failures.push('Freier FLUX-Workflow enthält LoadImage');
if (/FASHN|virtual_tryon/i.test(server + app)) failures.push('Entfernte VTO/FASHN-Logik wieder aktiv');

const uiResult = spawnSync(process.execPath, [resolve(root, 'tools/verify-ui-contracts-1.26.1.mjs')], { encoding: 'utf8' });
if (uiResult.status !== 0) failures.push(`UI-Verträge: ${uiResult.stderr || uiResult.stdout}`);

if (failures.length) {
  console.error(JSON.stringify({ ok: false, failures, summary }, null, 2));
  process.exit(1);
}
console.log(JSON.stringify({
  ok: true,
  version: pkg.version,
  ...summary,
  health_endpoint: true,
  admin_diagnostics: true,
  request_timeout_and_retry: true,
  workspace_resize_contracts: true,
  extension_variants: 4,
}, null, 2));
