import { readFileSync, readdirSync, 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, nav_targets: 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];
  });
}
for (const file of walk(root)) {
  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'));
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');
const db = readFileSync(resolve(root, 'lib/db.mjs'), 'utf8');
const quality = readFileSync(resolve(root, 'lib/quality-center.mjs'), 'utf8');
if (pkg.version !== '1.28.0') failures.push(`package.json-Version ist ${pkg.version}`);
for (const marker of ['content="1.28.0"', 'style.css?v=1.28.0', 'app.js?v=1.28.0']) if (!html.includes(marker)) failures.push(`Build-Marker fehlt: ${marker}`);
if (!app.startsWith("const VENDOO_UI_BUILD = '1.28.0';")) failures.push('UI-Build ist nicht 1.28.0');
const ids = [...html.matchAll(/\bid="([^"]+)"/g)].map(match => match[1]);
summary.html_ids = ids.length;
const duplicateIds = [...new Set(ids.filter((id, index) => ids.indexOf(id) !== index))];
if (duplicateIds.length) failures.push(`Doppelte HTML-IDs: ${duplicateIds.join(', ')}`);
const sections = new Set([...html.matchAll(/<section\s+id="([^"]+)"/g)].map(match => match[1]));
const navTargets = [...html.matchAll(/class="[^"]*nav-item[^"]*"[^>]*data-tab="([^"]+)"/g)].map(match => match[1]);
summary.nav_targets = navTargets.length;
for (const target of navTargets) if (!sections.has(target)) failures.push(`Navigation ohne Zielsektion: ${target}`);
summary.css_blocks = (css.match(/{/g) || []).length;
if (summary.css_blocks !== (css.match(/}/g) || []).length) failures.push('CSS-Klammern unausgeglichen');
for (const marker of ['data-tab="quality-center"','id="quality-center"','id="quality-ai-modal"','id="quality-analyze-visible"']) if (!html.includes(marker)) failures.push(`Quality-Center-UI fehlt: ${marker}`);
for (const marker of ['.quality-workspace','.quality-score-ring','.quality-ai-compare','@container (max-width: 920px)']) if (!css.includes(marker)) failures.push(`Quality-Center-CSS fehlt: ${marker}`);
for (const marker of ['setupQualityCenter()', "if (tabId === 'quality-center') loadQualityCenter()", 'generateQualityAiSuggestion', 'applyQualityAiSuggestion']) if (!app.includes(marker)) failures.push(`Quality-Center-JavaScript fehlt: ${marker}`);
for (const marker of ["app.get('/api/quality-center'", "app.post('/api/quality-center/:id/analyze'", "app.post('/api/quality-center/:id/ai-suggestions'", "app.post('/api/quality-center/:id/apply-suggestions'"]) if (!server.includes(marker)) failures.push(`Quality-Center-API fehlt: ${marker}`);
if (!db.includes('CREATE TABLE IF NOT EXISTS quality_reports')) failures.push('quality_reports-Tabelle fehlt');
for (const marker of ['analyzeListingQuality','listQualityCenter','getQualityHistory','compareQualityReports','findDuplicates','inspectImages']) if (!quality.includes(marker)) failures.push(`Quality-Modul-Funktion fehlt: ${marker}`);
for (const marker of ['missing_title','missing_description','missing_photos','missing_price','duplicate_sku','photo_low_resolution']) if (!quality.includes(marker)) failures.push(`Qualitätsregel fehlt: ${marker}`);
if (!server.includes('Die AI erstellt') && !html.includes('Die AI erstellt nur Vorschläge')) failures.push('AI-Bestätigungsregel fehlt');
const dbResult = spawnSync('python', [resolve(root, 'tools/verify-db-migrations.py')], { encoding: 'utf8' });
if (dbResult.status !== 0) failures.push(`DB-Migration: ${dbResult.stderr || dbResult.stdout}`);
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}`);
for (const path of ['lib/quality-center.mjs','docs/SLICE_33_ARTICLE_QUALITY_CENTER.md','local-ai/workflows/vendoo_flux_schnell_api.json']) if (!existsSync(resolve(root, path))) failures.push(`Pflichtdatei fehlt: ${path}`);
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');
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, quality_center:true, persistent_reports:true, duplicate_detection:true, image_inspection:true, ai_confirmation:true }, null, 2));
