// Post-build gate: the marketing entries stay light. The landing (/) and the
// learning section (/learn/) must never gain a static edge into the heavy
// vendor chunks — this shipped once (Vite's preload helper emitted inside the
// monaco chunk chained every lazy import() to it; a vega-scale import in
// theme-controls was reachable from Landing). Vite lists an entry's full
// static graph as modulepreload links / module scripts in its HTML, so
// grepping the emitted HTML catches any regression regardless of cause.
//
// Runs as part of `npm run build` (after `vite build`). Exit 1 on violation.
import { existsSync, readFileSync, readdirSync } from 'node:fs';
import { join } from 'node:path';

const pages = ['dist/index.html', 'dist/learn/index.html'];
if (existsSync('dist/learn')) {
  for (const entry of readdirSync('dist/learn', { withFileTypes: true })) {
    if (entry.isDirectory()) pages.push(join('dist/learn', entry.name, 'index.html'));
  }
}

const HEAVY = /vendor-(?:monaco|vega)-[^"']*\.js/;
const missing = pages.filter((p) => !existsSync(p));
if (missing.length > 0) {
  console.error(
    `check-light-entries: expected pages missing from dist/:\n  ${missing.join('\n  ')}`,
  );
  process.exit(1);
}
// The gate bans chunks by name, so it must not fail open: if the names minted in
// vite.config.ts (manualChunks) ever change, this makes the rename update the gate
// instead of silently disarming it.
const assets = readdirSync('dist/assets');
for (const chunk of ['vendor-monaco', 'vendor-vega']) {
  if (!assets.some((f) => f.startsWith(`${chunk}-`) && f.endsWith('.js'))) {
    console.error(
      `check-light-entries: no ${chunk}-*.js in dist/assets — chunk naming changed; update vite.config.ts manualChunks and this gate together.`,
    );
    process.exit(1);
  }
}
const offenders = pages.filter((p) => HEAVY.test(readFileSync(p, 'utf8')));
if (offenders.length > 0) {
  console.error(
    `check-light-entries: light entries reference heavy vendor chunks:\n  ${offenders.join('\n  ')}`,
  );
  process.exit(1);
}
console.log(`check-light-entries: OK (${pages.length} pages clean of vendor-monaco/vendor-vega)`);
