// The MATLAB implementation, loaded from ../matlab at build time. The app
// keeps an editable in-memory copy of these sources (see App.tsx); edits feed
// straight into the render worker and are deliberately not persisted, so a
// reload restores the shipped code.

export interface MFile {
  name: string;
  source: string;
}

const modules = import.meta.glob('../../matlab/*.m', {
  eager: true,
  query: '?raw',
  import: 'default',
}) as Record<string, string>;

export const DEFAULT_MFILES: MFile[] = Object.entries(modules)
  .map(([path, source]) => ({ name: path.split('/').pop()!, source }))
  .sort((a, b) => a.name.localeCompare(b.name));

// Files the app itself executes. The others are entry points for running the
// model from the numbl CLI, and editing them changes nothing in the browser.
export const EXECUTED_BY_APP = new Set([
  'woodblock_basis.m',
  'woodblock_solve.m',
  'woodblock_radiate.m',
  'woodblock_output.m',
]);

// Cheap content hash (FNV-1a) so the worker can key its caches on the code.
export function hashMFiles(files: MFile[]): string {
  let h = 0x811c9dc5;
  for (const f of files) {
    const s = f.name + ' ' + f.source + '';
    for (let i = 0; i < s.length; i++) {
      h ^= s.charCodeAt(i);
      h = Math.imul(h, 0x01000193);
    }
  }
  return (h >>> 0).toString(36);
}
