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

const root = resolve(import.meta.dirname, '..');
const read = path => readFileSync(resolve(root, path), 'utf8');
const assert = (condition, message) => {
  if (!condition) throw new Error(message);
};

const index = read('public/index.html');
const app = read('public/app.js');
const style = read('public/style.css');
const server = read('server.mjs');
const setup = read('setup.ps1');

assert(index.includes('name="vendoo-build" content="1.23.1"'), 'Build-Metadatum fehlt.');
assert(index.includes('style.css?v=1.23.1'), 'CSS-Cache-Buster fehlt.');
assert(index.includes('app.js?v=1.23.1'), 'JS-Cache-Buster fehlt.');
assert(index.includes('id="advanced-image-editor-btn"'), 'Sichtbarer Editor-Einstieg fehlt.');
assert(app.includes("VENDOO_UI_BUILD = '1.23.1'"), 'UI-Buildkennung fehlt.');
assert(app.includes("openPhotoEditor(0, 'generator')"), 'Editor-Button ist nicht angebunden.');
assert(style.includes('.advanced-editor-entry'), 'Editor-Button-Styling fehlt.');
assert(server.includes("Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate"), 'No-Store-Header fehlt.');
assert(setup.includes('/?build=1.23.1'), 'Windows-Start-Cache-Buster fehlt.');

const extensionFiles = [
  'extension/content.js',
  'extensions/content.js',
  'extensions/chrome/content.js',
  'extensions/edge/content.js',
  'extensions/firefox/content.js',
];
for (const file of extensionFiles) {
  const content = read(file);
  assert(content.includes('function getAssociatedControl(label, selector)'), `${file}: strikte Label-Zuordnung fehlt.`);
  assert(content.includes('function isLikelyTitleField(el)'), `${file}: Titelfeldschutz fehlt.`);
  assert(content.includes('if (!trigger || isLikelyTitleField(trigger)) return false;'), `${file}: Choice-Felder schützen Titel nicht.`);
  assert(!content.includes("label.parentElement?.querySelector('button,[role=\"button\"],select,input')"), `${file}: unsicherer Eltern-Fallback noch vorhanden.`);
  assert(!content.includes("'[class*=\"Title\"] input'"), `${file}: unspezifischer Title-Klassenfallback noch vorhanden.`);
}

const manifests = [
  'extension/manifest.json',
  'extensions/chrome/manifest.json',
  'extensions/edge/manifest.json',
  'extensions/firefox/manifest.json',
  'extensions/manifest.chromium.json',
  'extensions/manifest.firefox.json',
];
for (const file of manifests) {
  const manifest = JSON.parse(read(file));
  assert(manifest.version === '1.6.1', `${file}: erwartete Extension-Version 1.6.1.`);
}

console.log('Vendoo 1.23.1 Hotfix-Verifikation erfolgreich.');
