import { readFileSync } from 'fs';
import { resolve } from 'path';

const root = resolve(new URL('..', import.meta.url).pathname);
const html = readFileSync(resolve(root, 'public/index.html'), 'utf8');
const js = readFileSync(resolve(root, 'public/app.js'), 'utf8');
const css = readFileSync(resolve(root, 'public/style.css'), 'utf8');

const ids = [...html.matchAll(/\bid="([^"]+)"/g)].map(match => match[1]);
const duplicates = [...new Set(ids.filter((id, index) => ids.indexOf(id) !== index))];
if (duplicates.length) throw new Error(`Doppelte HTML-IDs: ${duplicates.join(', ')}`);

const navTabs = [...html.matchAll(/class="[^"]*nav-item[^"]*"[^>]*data-tab="([^"]+)"/g)].map(match => match[1]);
const sectionIds = new Set([...html.matchAll(/<section\s+id="([^"]+)"[^>]*class="[^"]*tab-content/g)].map(match => match[1]));
const missingSections = [...new Set(navTabs)].filter(tab => !sectionIds.has(tab));
if (missingSections.length) throw new Error(`Navigation ohne Zielbereich: ${missingSections.join(', ')}`);

const requiredIds = [
  'connection-banner', 'connection-retry-btn', 'system-diagnostics-btn',
  'system-diagnostics-copy', 'system-diagnostics-summary', 'system-diagnostics-grid',
];
for (const id of requiredIds) if (!ids.includes(id)) throw new Error(`Pflicht-ID fehlt: ${id}`);

const requiredJs = [
  'setupGlobalResilience()', 'setupResponsiveContracts()', 'runSystemDiagnostics',
  "'/api/admin/diagnostics'", '`/healthz?t=${Date.now()}`', 'recordClientIncident',
  'ResizeObserver', 'X-Vendoo-Request-ID', '--workspace-width',
];
for (const marker of requiredJs) if (!js.includes(marker)) throw new Error(`UI-Vertrag fehlt: ${marker}`);

const requiredCss = [
  '.connection-banner', '.diagnostics-grid', '.diagnostic-card',
  '[data-layout-width="phone"]',
];
for (const marker of requiredCss) if (!css.includes(marker)) throw new Error(`Responsive-/Diagnose-CSS fehlt: ${marker}`);

const staleLabels = ['+ Neues Listing', '>Listings<', 'Listing generieren'];
for (const label of staleLabels) if (html.includes(label)) throw new Error(`Veraltete UI-Bezeichnung gefunden: ${label}`);

console.log(JSON.stringify({
  ok: true,
  html_ids: ids.length,
  navigation_targets: [...new Set(navTabs)].length,
  sections: sectionIds.size,
  responsive_contract: true,
  global_error_capture: true,
  system_diagnostics_ui: true,
}, null, 2));
