/**
 * Sandboxed suite executor. This page is listed under manifest "sandbox" so
 * dynamic code evaluation is legal here (it is forbidden in every other
 * extension context). It holds no privileges: no chrome.* APIs, no vault —
 * it receives a self-contained test program string, runs it, and posts the
 * results back to the embedding offscreen document.
 *
 * Message types:
 *   rha-run-suite  — execute full suite program (existing)
 *   rha-parse-probe — construct-only `new Function(program)` parse gate (SET 40a)
 *   rha-module-probe — execute module-probe program; return __RHA_PROBE__ result (SET 47a)
 */
window.addEventListener('message', async (ev) => {
  const d = ev.data;
  if (!d || !d.id || typeof d.program !== 'string') return;

  // SET 40a — parse probe: construct only (do not execute body).
  if (d.type === 'rha-parse-probe') {
    let error = null;
    try {
      // eslint-disable-next-line no-new-func
      new Function(d.program);
    } catch (e) {
      if (e instanceof EvalError || /unsafe-eval/i.test(e instanceof Error ? e.message : String(e))) {
        error = 'GATE_UNAVAILABLE';
      } else {
        error = e instanceof Error ? e.message : String(e);
      }
    }
    ev.source.postMessage({ type: 'rha-parse-result', id: d.id, error }, '*');
    return;
  }

  // SET 47a — module probe: construct + run __RHA_PROBE__ (sandbox allows eval).
  if (d.type === 'rha-module-probe') {
    let error = null;
    try {
      delete globalThis.__RHA_PROBE__;
      // eslint-disable-next-line no-new-func
      new Function(d.program)();
      const probe = globalThis.__RHA_PROBE__;
      error = typeof probe === 'function' ? probe() : 'probe did not define __RHA_PROBE__';
    } catch (e) {
      if (e instanceof EvalError || /unsafe-eval/i.test(e instanceof Error ? e.message : String(e))) {
        error = 'GATE_UNAVAILABLE';
      } else {
        error = e instanceof Error ? e.message : String(e);
      }
    } finally {
      delete globalThis.__RHA_PROBE__;
    }
    ev.source.postMessage({ type: 'rha-module-result', id: d.id, error }, '*');
    return;
  }

  if (d.type !== 'rha-run-suite') return;
  let result;
  try {
    delete globalThis.__RHA_RUN__;
    // eslint-disable-next-line no-new-func
    new Function(d.program)();
    result = typeof globalThis.__RHA_RUN__ === 'function'
      ? await globalThis.__RHA_RUN__()
      : { total: 0, failures: [], crashed: 'program did not define __RHA_RUN__' };
  } catch (e) {
    result = { total: 0, failures: [], crashed: e instanceof Error ? e.message : String(e) };
  } finally {
    delete globalThis.__RHA_RUN__;
  }
  ev.source.postMessage({ type: 'rha-run-result', id: d.id, result }, '*');
});
