// STABLE VIEWPORT CORE — build guard.
// Run: node scripts/viewport-safety.mjs
// Fails (exit 1) if forbidden imports/patterns reappear in the locked core, or
// if more than one <Canvas> is detected in the 3D workshop layout.
import fs from 'fs';
import path from 'path';

const ROOT = 'src/components/workshop3d';
const FORBIDDEN = [
  /@react-three\/drei/,
  /shaderMaterial/,
  /LineDashedMaterial/,
  /dashSize/,
  /gapSize/,
  /extensions-derivatives/,
  /postprocessing/,
  /EffectComposer/,
  /ContactShadows/,
  /AccumulativeShadows/,
  /PresentationControls/,
  /\bStage\b/,
  /\bBounds\b/,
  /\bEnvironment\b/,
];

const violations = [];

function walk(dir) {
  for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
    const p = path.join(dir, e.name);
    if (e.isDirectory()) walk(p);
    else if (/\.(jsx?|tsx?)$/.test(e.name)) {
      const c = fs.readFileSync(p, 'utf-8');
      for (const re of FORBIDDEN) {
        const m = c.match(re);
        if (m) violations.push(`${p}: forbidden pattern "${m[0]}"`);
      }
    }
  }
}
walk(ROOT);

// One-Canvas rule: count <Canvas occurrences across the workshop layout + page.
const layoutFiles = ['src/components/workshop/WorkshopLayout.jsx', 'src/pages/Workshop3D.jsx'];
let canvasCount = 0;
for (const f of layoutFiles) {
  if (!fs.existsSync(f)) continue;
  const c = fs.readFileSync(f, 'utf-8');
  canvasCount += (c.match(/<Canvas\b/g) || []).length;
}

// Stable-key rule: Canvas must not be keyed by route/project/customer.
const core = fs.readFileSync(path.join(ROOT, 'StableViewportCore.jsx'), 'utf-8');
const keyMatches = core.match(/key=\{?["'`]?[a-zA-Z0-9_-]+["'`]?\}?/g) || [];
const badKeys = keyMatches.filter((k) => /(route|project|customer|uuid|station|mode)/i.test(k));

if (canvasCount > 1) violations.push(`One-Canvas rule violated: ${canvasCount} <Canvas> detected in workshop layout/page.`);
if (badKeys.length) violations.push(`Unstable Canvas key(s): ${badKeys.join(', ')}`);

if (violations.length) {
  console.error('VIEWPORT SAFETY GUARD FAILED:');
  for (const v of violations) console.error('  - ' + v);
  process.exit(1);
}
console.log('VIEWPORT SAFETY GUARD PASSED — core is clean, one Canvas, stable key.');
process.exit(0);