'use strict';
const fs = require('fs');
const path = require('path');

const files = [
  '../../frontend/js/g3d.js',
  '../../frontend/textbooks/geometry_11_hub.html',
  '../../frontend/textbooks/geometry_11_ch1.html',
  '../../frontend/textbooks/geometry_11_ch2.html',
  '../../frontend/textbooks/geometry_11_ch3.html',
  '../../frontend/textbooks/geometry_11_ch4.html',
];

let totalErrors = 0;

for (const rel of files) {
  const p = path.join(__dirname, rel);
  const src = fs.readFileSync(p, 'utf8');
  if (rel.endsWith('.js')) {
    // pure JS file
    try {
      new Function(src);
      console.log('OK (parse) ' + rel);
    } catch (e) {
      totalErrors++;
      console.error('FAIL ' + rel + ':\n' + e.message);
    }
    continue;
  }
  // Extract all inline <script>...</script> bodies (skip src= scripts)
  const re = /<script(?![^>]*\bsrc=)[^>]*>([\s\S]*?)<\/script>/gi;
  let m, idx = 0;
  while ((m = re.exec(src))) {
    idx++;
    try {
      new Function(m[1]);
    } catch (e) {
      totalErrors++;
      console.error('FAIL ' + rel + ' [inline script #' + idx + ']:\n' + e.message);
    }
  }
  console.log('OK (' + idx + ' inline) ' + rel);
}

if (totalErrors > 0) {
  console.error('\nTOTAL ERRORS: ' + totalErrors);
  process.exit(1);
}
console.log('\nAll OK.');
