GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Maps, GIS and field navigation / gridatlas / tools/proofs

Module Parity Proof and 2 more files

A JavaScript module in the proofs folder of GridAtlas that reads substations, 400kV, transformers and solar. It loads modules (`loadModules`) and makes element (`makeElement`).

609 lines of JavaScript from gridatlas, in 3 files. Topic: Maps, GIS and field navigation. Section 656 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. Menu Bar Dom Proof interaction · gridatlas / tools/proofs/menu-bar-dom.proof.mjs lines 373–514
  2. Menu Bar Mobile Hit Browser interaction · gridatlas / tools/proofs/menu-bar-mobile-hit.browser.mjs lines 1–174
  3. Module Parity Proof interaction · gridatlas / tools/proofs/modules/202609011950-module-parity.proof.mjs lines 1–293

Menu Bar Dom Proof

A JavaScript module in the proofs folder of GridAtlas that works with selector parts (`selectorParts`) and fake element (`FakeElement`).

interactiongridatlas / tools/proofs/menu-bar-dom.proof.mjs · lines 373–514 of 514 (continued from section 655) · Not reached from any entry point (candidate for review) · pattern classes (shared by 3 files)

What it does
It draws its content. Defines 13 functions or classes, including classes, selectorParts, matches, FakeElement, visit. Uses libraries node:fs/promises, node:vm. Side effects: changes the web page (DOM); reads or writes files.
Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'gridatlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
What it achieves
It proves menu bar (`proveMenuBar`) and is built from the selector parts helper (`selectorParts`) and the fake element class (`FakeElement`). Defines `classes`, `selectorParts`, `matches` and 10 more. It responds to click and change events.
Why it matters
No other file in the estate was found to import it.
Application
gridatlas · tools/proofs · JavaScript module
Uses
node:fs/promises, node:vm
Used by
none found
Produces
proveMenuBar
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/proofs/menu-bar-dom.proof.mjs:373-514 · blob ddf54aebb14c3a7b434cc174f09d9fa18dafe50b · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
      console,
      setInterval() { partialIntervals += 1; return partialIntervals; },
      clearInterval() {},
      setTimeout(fn) { fn(); return 1; }
    }
  };
  partialBox.window.window = partialBox.window;
  partialBox.globalThis = partialBox;
  vm.createContext(partialBox);
  vm.runInContext(source, partialBox, { filename: 'menu-bar-partial-dom.js' });
  check('a partial DOM fails closed without starting the long browser retry loop',
    partialBox.window.__GRIDATLAS_MODULES__?.menuBar?.installed === false
    && /document|DOM/.test(partialBox.window.__GRIDATLAS_MODULES__.menuBar.failure)
    && partialIntervals === 0);
  check('menu names are exactly File Edit View Scope Grid About',
    api?.menus.join('|') === 'File|Edit|View|Scope|Grid|About');
  check('all six menus are closed at rest',
    titleNodes.length === 6
    && titleNodes.every((node) => node.getAttribute('aria-expanded') === 'false')
    && bar.querySelectorAll('.gm-menu.gm-open').length === 0
    && api.closed_at_rest === true);
  check('every title exposes its popup, state and controlled panel',
    titleNodes.every((node) => node.getAttribute('aria-haspopup') === 'menu'
      && node.getAttribute('aria-controls')
      && complete.doc.getElementById(node.getAttribute('aria-controls'))));
  check('there are no empty or placeholder menus',
    api?.menus.every((name) => panel(name)?.children.length > 0)
    && !/nothing here yet/i.test(bar.textContent));
  check('the inventory is exactly 60 engine plus 3 Pipeline News controls',
    api?.engine_layer_controls === 60 && api.pipeline_layer_controls === 3
    && api.layer_controls === 63 && api.inspect().unique === 63);
  check('Grid exposes all 63 unique controls, not shallow direct children',
    panel('Grid')?.querySelectorAll('[data-gridatlas-layer-proxy]').length === 63
    && complete.controls.parentNode === complete.scada
    && complete.controls.querySelectorAll('input[type="checkbox"][data-layer-id]').length === 60
    && complete.controls.querySelectorAll('input[type="checkbox"][data-pn-layer]').length === 3);
  check('the forbidden Select layers alias is absent',
    !api?.menus.includes('Select layers') && !titleNodes.some((node) => node.textContent === 'Select layers'));

  const scope = complete.actions['tray-scope'];
  const clear = complete.actions['tray-clear'];
  const radius = complete.actions['btn-radius'];
  scope.click(); clear.click(); radius.click();
  check('nested Scope Clear and radius remain the original live nodes',
    panel('Scope')?.contains(scope) && panel('Scope')?.contains(clear)
    && panel('Scope')?.contains(radius)
    && scope.hits === 1 && clear.hits === 1 && radius.hits === 1);
  check('the radius result panel stays with the map and is never hidden with its controls',
    complete.result.parentNode === complete.map && complete.result.hidden === false);

  title('Grid').click();
  const proxy = panel('Grid').querySelector('[data-gridatlas-layer-proxy="engine:engine-0"]');
  const proxyName = proxy.parentNode.querySelector('.gm-layer-name');
  check('the Grid proxy mirrors the V8 live WAIT state rather than hiding it',
    proxyName.textContent === 'Engine 0 [WAIT]'
    && proxy.getAttribute('aria-label') === 'Engine 0 [WAIT]');
  proxy.click();
  check('a Grid proxy executes the original handler and reflects original state',
    complete.originals[0].checked === true && complete.originals[0].hits === 1
    && proxy.checked === true);
  check('a layer choice remains open so a phone reader can see the tick',
    title('Grid').getAttribute('aria-expanded') === 'true'
    && bar.querySelectorAll('.gm-menu.gm-open').length === 1
    && api.layer_menu_stays_open === true);

  complete.originals[0].parentNode.querySelector('[data-base-label]').textContent = 'Engine 0 [OK]';
  title('Grid').click();
  title('Grid').click();
  check('reopening Grid mirrors the V8 terminal load state visibly and accessibly',
    proxyName.textContent === 'Engine 0 [OK]'
    && proxy.getAttribute('aria-label') === 'Engine 0 [OK]'
    && api.layer_status_mirrored === true);

  complete.originals[0].click();
  check('opening Grid resynchronises state changed through the original UI',
    proxy.checked === complete.originals[0].checked && proxy.checked === false);
  title('View').click();
  check('navigating menus leaves exactly one panel open',
    title('Grid').getAttribute('aria-expanded') === 'false'
    && title('View').getAttribute('aria-expanded') === 'true'
    && bar.querySelectorAll('.gm-menu.gm-open').length === 1);
  title('View').focus();
  bar.dispatch('keydown', { key: 'Escape', target: title('View') });
  check('Escape closes and returns focus to the owning title',
    api.closed_at_rest === true && complete.doc.activeElement === title('View'));
  title('File').focus();
  bar.dispatch('keydown', { key: 'ArrowRight', target: title('File') });
  check('arrow navigation advances across the conventional menu titles',
    complete.doc.activeElement === title('Edit'));

  check('the old action stack is emptied only after nested controls move',
    complete.stack.getAttribute('data-gridatlas-menu-emptied') === '1'
    && panel('Scope').contains(clear));
  check('one identity surface remains: the VENTUS masthead is fused into the bar itself '
    + '(not moved into a closed panel, generation 202609041250) and the real SCADA brand is '
    + 'restored -- not cloned, not hidden as a duplicate -- into the Grid panel head',
    api.one_identity_surface === true
    && bar.querySelector('.gm-brand-slot')?.contains(complete.header)
    && panel('Grid')?.querySelector('.gm-panel-head')?.contains(complete.brand)
    && !complete.brand.hasAttribute('data-gridatlas-menu-duplicate'));
  check('the v8 fullscreen letterhead stands down once the bar hosts the masthead: '
    + '#fs-letterhead paints only under body.fs-active, and the deep-link arrival\'s '
    + 'enterFullscreen() is the only caller that sets it -- every phone, no desktop -- so '
    + 'without this rule a second 15px wordmark painted at x=254 over SCOPE, GRID and ABOUT '
    + 'on an iPhone 13 viewport while the fused masthead sat correctly at x=165',
    /\.gridatlas-menu-hosted #fs-letterhead\{display:none!important\}/.test(styleText)
    && bar.querySelector('.gm-brand-slot')?.contains(complete.header));
  check('install is idempotent and document listeners are not multiplied',
    api.listeners === 2 && api.install() === true && api.listeners === 2
    && (complete.doc.listeners.click || []).length === 1
    && (complete.doc.listeners.change || []).length === 1);
  check('phone panels are bounded and scroll rather than escaping 393x852',
    /@media\(max-width:700px\)/.test(source)
    && /max-height:calc\(100dvh - 40px\)/.test(source)
    && /overflow:auto/.test(source));
  check('the Grid menu remains the hit target above the v9.90 mobile project sheet',
    api?.mobile_sheet_hit_target_guard === true
    && /html\.gridatlas-sheet-open #gridatlas-menu-bar\{z-index:10020!important;pointer-events:auto!important\}/
      .test(styleText)
    && /html\.gridatlas-sheet-open #gridatlas-menu-bar \.gm-panel\{pointer-events:auto!important\}/
      .test(styleText));
  check('nothing in menu output grades a connection',
    !/\b(strong|weak|remote|excellent|poor|good|bad)\b/i.test(
      source.replace(/\/\*[\s\S]*?\*\//g, '')));

  const incomplete = run(source, { engineCount: 59, pipelineCount: 3 });
  check('62 controls fail closed with the original interface untouched',
    incomplete.api?.installed === false && !incomplete.doc.getElementById('gridatlas-menu-bar')
    && incomplete.actions['btn-radius'].parentNode === incomplete.stack
    && !incomplete.stack.hasAttribute('data-gridatlas-menu-emptied'));
  const duplicate = run(source, { engineCount: 60, pipelineCount: 3, duplicate: true });
  check('a duplicate identity also fails closed even when the raw count is 63',
    duplicate.api?.installed === false && duplicate.api.inspect().total === 63
    && duplicate.api.inspect().unique === 62
    && !duplicate.doc.getElementById('gridatlas-menu-bar'));

  if (failures.length) {
    throw new Error('menu-bar DOM proof failed (' + failures.length + '):\n- '
      + failures.join('\n- '));
  }
  return { status: 'PASS', checks: passed, layers: 63, menus: api.menus };
}

Menu Bar Mobile Hit Browser

A JavaScript module in the proofs folder of GridAtlas. It is built from the bound card to map helper (`boundCardToMap`).

interactiongridatlas / tools/proofs/menu-bar-mobile-hit.browser.mjs · lines 1–174 of 174 · Entry point · pattern boundCardToMap (shared by 10 files)

What it does
It loads data. Defines boundCardToMap. Uses libraries node:assert/strict, node:fs/promises, node:path, node:url, playwright. Side effects: changes the web page (DOM); reads or writes files.
Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'gridatlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
Inputs & outputs
In: form fields (user input).
Downstream impact
Used directly by 1 file: GridAtlas Cartridge Proof Workflow (gridatlas).
What it achieves
Defines `boundCardToMap`. It responds to click and change events.
Why it matters
Run by GridAtlas Cartridge Proof Workflow.
Application
gridatlas · tools/proofs · JavaScript module
Uses
node:assert/strict, node:fs/promises, node:path, node:url, playwright
Used by
run by GridAtlas Cartridge Proof Workflow (workflow run)
Produces
boundCardToMap
Defines here
boundCardToMap
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/proofs/menu-bar-mobile-hit.browser.mjs:1-174 · blob 4a9f6bfb0e4d244f4876ce0136e1dfbdb7d0d320 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env node

import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { chromium } from 'playwright';

const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
const menuPath = path.join(ROOT, 'atlas', 'modules', '202609031958-menu-bar.js');
const sldBodyPath = path.join(ROOT, 'atlas', 'parts', '202609012045-sld-sandbox-body.js');

const sldBody = await readFile(sldBodyPath, 'utf8');
const fullscreenStart = sldBody.indexOf('  function keepLayersInFullscreen() {');
const fullscreenEnd = sldBody.indexOf('\n  function installSld(map) {', fullscreenStart);
assert.ok(fullscreenStart >= 0 && fullscreenEnd > fullscreenStart,
  'could not extract the production fullscreen handler');
const fullscreenHandler = sldBody.slice(fullscreenStart, fullscreenEnd);

const engineIds = Array.from({ length: 60 }, (_, index) =>
  index === 37 ? 'dlr' : `engine-${index}`);
const engineControls = engineIds.map((id) => `
  <label class="key-item"><input type="checkbox" data-layer-id="${id}">
    <span data-base-label="${id === 'dlr' ? 'DLR' : id}">${id}</span></label>`).join('');
const pipelineControls = ['same-tech', 'wider-fleet', 'all-pipeline'].map((id) => `
  <label class="key-item"><input type="checkbox" data-pn-layer="${id}">
    <span data-pn-label="${id}">${id}</span></label>`).join('');

const browser = await chromium.launch({ headless: true });
try {
  const context = await browser.newContext({
    viewport: { width: 393, height: 852 },
    isMobile: true,
    hasTouch: true,
  });
  const page = await context.newPage();
  const pageErrors = [];
  page.on('pageerror', error => pageErrors.push(String(error?.message || error)));
  await page.setContent(`<!doctype html>
<html class="gridatlas-sheet-open"><head><meta name="viewport" content="width=device-width,initial-scale=1"><style>
  html,body{margin:0;width:100%;height:100%;font:12px sans-serif}
  .map-container{position:relative;width:100%;height:100%;background:#071217}
  .map-controls{position:absolute;top:50px;left:4px}
  .scada-wrapper{position:fixed;left:12px;top:580px;z-index:2;color:white}
  .key-item{display:block;min-height:22px}
  .maplibregl-popup.gridatlas-sheet{position:fixed;inset:auto 0 0 0;height:56vh;z-index:400;background:#182229}
  .maplibregl-popup.gridatlas-sheet .neon-caveat{position:absolute;inset:0;padding:20px;color:white}
</style></head><body>
  <div id="dashboard" class="dashboard">
  <div class="hud-header">GridAtlas</div>
  <div id="map-container" class="map-container">
    <div class="search-bar-wrapper"><input id="search-input"><div id="search-results"></div></div>
    <div class="map-controls">
      <button id="btn-export">Export</button><button id="btn-status">Status</button>
      <button id="btn-radius">Radius</button><button id="btn-radius-area">Area</button>
      <button id="btn-zonedraw">Zone</button><button id="btn-measure">Measure</button>
    </div>
    <button id="btn-fullscreen">Fullscreen</button>
    <div class="maplibregl-popup gridatlas-sheet"><span class="neon-caveat">Project evidence card</span></div>
  </div>
  <div class="scada-wrapper"><div class="scada-brand">Ventus</div>
    <div id="scada-ui-container">
      <div class="key-group"><div class="key-title">Engine layers</div>${engineControls}</div>
      <div class="key-group"><div class="key-title">Pipeline News</div>${pipelineControls}</div>
    </div>
  </div>
  <button id="gridatlas-dash-toggle">Layers</button>
  <button id="btn-fullscreen-exit">Exit</button>
  <div id="fs-curtain-tab">Layers</div>
  <script>
    window.originalChanges = 0;
    document.getElementById('btn-fullscreen').addEventListener('click', () =>
      document.getElementById('map-container').requestFullscreen());
    document.querySelectorAll('input[data-layer-id]').forEach((input) => {
      input.addEventListener('change', () => {
        window.originalChanges += 1;
        const label = input.closest('label').querySelector('[data-base-label]');
        label.textContent = label.getAttribute('data-base-label') + ' [OK]';
      });
    });
  </script>
  </div>
</body></html>`);

  const before = await page.locator('input[data-layer-id="engine-0"]').evaluate((input) => {
    const rect = input.getBoundingClientRect();
    const top = document.elementFromPoint(rect.left + rect.width / 2, rect.top + rect.height / 2);
    return { tag: top?.tagName, className: top?.className || '' };
  });
  assert.match(before.className, /neon-caveat/,
    'fixture must reproduce the v9.90 project sheet intercepting an original layer checkbox');

  await page.addScriptTag({ path: menuPath });
  await page.waitForFunction(() => window.__GRIDATLAS_MODULES__?.menuBar?.installed === true);

  /* Execute the production fullscreen handler, not a restatement. The real
     regression occurred when #map-container (a dashboard descendant) became
     fullscreen and the handler tried to append its ancestor into it. */
  await page.addScriptTag({ content: `
    const link = { failures: [] };
    let fullscreenBounds = 0;
    const boundCardToMap = () => { fullscreenBounds += 1; };
    ${fullscreenHandler}
    keepLayersInFullscreen();
    window.__fullscreenProof = { link, get bounds() { return fullscreenBounds; } };
  ` });

  await page.getByRole('button', { name: 'View', exact: true }).click();
  await page.locator('#btn-fullscreen').click();
  await page.waitForFunction(() => document.fullscreenElement?.id === 'map-container');

  await page.getByRole('button', { name: 'Grid', exact: true }).click();

  const proxy = page.locator('[data-gridatlas-layer-proxy="engine:dlr"]');
  await proxy.scrollIntoViewIfNeeded();
  const hit = await proxy.evaluate((input) => {
    const rect = input.getBoundingClientRect();
    const x = rect.left + rect.width / 2;
    const y = rect.top + rect.height / 2;
    const top = document.elementFromPoint(x, y);
    return { x, y, isProxy: top === input, tag: top?.tagName, className: top?.className || '' };
  });
  assert.equal(hit.isProxy, true,
    `Grid proxy lost the production hit test to ${hit.tag}.${hit.className}`);
  await page.mouse.click(hit.x, hit.y);

  await page.waitForFunction(() =>
    document.querySelector('[data-gridatlas-layer-proxy="engine:dlr"]')
      ?.getAttribute('aria-label') === 'DLR [OK]');

  const result = await page.evaluate(() => ({
    originalChecked: document.querySelector('input[data-layer-id="dlr"]').checked,
    proxyChecked: document.querySelector('[data-gridatlas-layer-proxy="engine:dlr"]').checked,
    originalChanges: window.originalChanges,
    menuExpanded: document.getElementById('gridatlas-menu-bar-title-4')
      .getAttribute('aria-expanded'),
    proxyLabel: document.querySelector('[data-gridatlas-layer-proxy="engine:dlr"]')
      .getAttribute('aria-label'),
    fullscreenElement: document.fullscreenElement?.id || '',
    fullscreenContainsMenu: document.fullscreenElement
      ?.contains(document.getElementById('gridatlas-menu-bar')),
    dashboardStillAtHome: document.getElementById('dashboard').parentElement === document.body,
    dashboardWasNotRelocated: !document.getElementById('dashboard')
      .classList.contains('gridatlas-fs-layers'),
    menuCountInFullscreen: document.fullscreenElement
      ?.querySelectorAll('.gm-title').length,
    fullscreenBounds: window.__fullscreenProof.bounds,
    fullscreenFailures: window.__fullscreenProof.link.failures,
    guard: window.__GRIDATLAS_MODULES__.menuBar.mobile_sheet_hit_target_guard,
    viewport: [innerWidth, innerHeight],
  }));
  assert.deepEqual(result, {
    originalChecked: true,
    proxyChecked: true,
    originalChanges: 1,
    menuExpanded: 'true',
    proxyLabel: 'DLR [OK]',
    fullscreenElement: 'map-container',
    fullscreenContainsMenu: true,
    dashboardStillAtHome: true,
    dashboardWasNotRelocated: true,
    menuCountInFullscreen: 6,
    fullscreenBounds: 1,
    fullscreenFailures: [],
    guard: true,
    viewport: [393, 852],
  });
  assert.deepEqual(pageErrors, [], `fullscreen raised page errors: ${pageErrors.join(' | ')}`);

  console.log(JSON.stringify({ status: 'PASS', pageErrors, before, hit, ...result }, null, 2));
  await context.close();
} finally {
  await browser.close();
}

Module Parity Proof

A JavaScript module in the proofs folder of GridAtlas that reads substations, 400kV, transformers and solar. It loads modules (`loadModules`) and makes element (`makeElement`).

interactiongridatlas / tools/proofs/modules/202609011950-module-parity.proof.mjs · lines 1–293 of 293 · version 2026-09-01 19:50 · Not reached from any entry point (candidate for review) · pattern MutationObserverStub (shared by 3 files)

What it does
It loads substations, 400kV, transformers and solar. Defines check, loadModules, makeElement, MutationObserverStub, sandboxContext. Uses libraries node:fs/promises, node:url, node:path, node:vm. Side effects: changes the web page (DOM); reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'gridatlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: substations, 400kV, transformers, solar, 750kV, 415V.
Inputs & outputs
In: JSON file current.json. Voltage levels named: 750kV, 400kV, 415V.
Downstream impact
Used directly by 1 file: Local CI (gridatlas).
What it achieves
Parity proof: the new modules against the 4,000-line incumbent. Its code works with 400 kV and 750 kV.
Why it matters
Run by Local CI.
Application
gridatlas · tools/proofs/modules · JavaScript module
Uses
GridAtlas — Atlas Page (estate URL), node:fs/promises, node:url, node:path, node:vm
Used by
run by Local CI (script call)
Produces
check, loadModules, makeElement, MutationObserverStub, sandboxContext
Defines here
check, loadModules, makeElement, MutationObserverStub, sandboxContext
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/proofs/modules/202609011950-module-parity.proof.mjs:1-293 · blob 9e6701dbcd6286cf3d1380070112141e4acf2c54 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
/**
 * Parity proof: the new modules against the 4,000-line incumbent.
 *
 * Vikram, 2026-09-01: "do not risk what you have built… modularise and
 * test against the 4000+ lines."
 *
 * So nothing is swapped here. The composed cartridges are untouched and
 * still live. This loads BOTH the incumbent cartridge and the extracted
 * modules into separate contexts, runs the same inputs through each, and
 * asserts the answers are identical. Only when a module has proven itself
 * equal to the code it would replace does replacing it become a question
 * worth asking.
 *
 * The incumbent exposes what this needs already:
 *   sandbox cartridge      link.measure = { distanceKm, voltagesKv,
 *                          representativePoint }
 *   substation cartridge   state.byName, state.nearest
 *
 *   node tools/proofs/modules/202609011950-module-parity.proof.mjs
 */

import { readFile } from 'node:fs/promises';
import { fileURLToPath } from 'node:url';
import { dirname, join, resolve } from 'node:path';
import vm from 'node:vm';

const HERE = dirname(fileURLToPath(import.meta.url));
const REPO = resolve(HERE, '..', '..', '..');
const CURRENT = JSON.parse(await readFile(join(REPO, 'atlas', 'current.json'), 'utf8'));

const MODULES = [
  '202609011950-geodesy.js',
  '202609011950-substation-lookup.js'
];

let passed = 0;
const failures = [];
function check(label, condition, detail) {
  if (condition) { passed += 1; console.log('  [PASS] ' + label); }
  else {
    failures.push(label + (detail ? ` — ${detail}` : ''));
    console.log('  [FAIL] ' + label + (detail ? ` — ${detail}` : ''));
  }
}

/* ── load the modules alone, with nothing else present ─────────────────── */

function loadModules() {
  const box = { window: {}, console, Math, JSON, Number, String, Array, Object,
    Map, Set, Boolean, Error, RegExp, isNaN, parseFloat };
  box.window.window = box.window;
  box.globalThis = box;
  vm.createContext(box);
  return box;
}

const moduleSource = new Map();
for (const name of MODULES) {
  moduleSource.set(name, await readFile(join(REPO, 'atlas', 'modules', name), 'utf8'));
}

const moduleBox = loadModules();
for (const name of MODULES) {
  vm.runInContext(moduleSource.get(name), moduleBox, { filename: name });
}
const modules = moduleBox.window.__GRIDATLAS_MODULES__;

console.log('\nthe modules load alone, and declare themselves\n');
check('geodesy registers', modules?.geodesy?.schema === 'gridatlas.module.geodesy.v1');
check('substation-lookup registers',
  modules?.substationLookup?.schema === 'gridatlas.module.substation-lookup.v1');
check('the estate radius is the estate radius',
  modules.geodesy.EARTH_RADIUS_KM === 6378.137);
check('a module refuses to load without its dependency', (() => {
  const bare = loadModules();
  try {
    vm.runInContext(moduleSource.get('202609011950-substation-lookup.js'), bare,
      { filename: 'lookup-alone.js' });
    return false;   // it should have thrown
  } catch (error) {
    return /requires the geodesy module/.test(String(error.message));
  }
})());

/* ── load the incumbent sandbox cartridge ──────────────────────────────── */

const sandboxEntry = CURRENT.cartridges.find(c => c.id === 'sld-sandbox');
const sandboxSource = await readFile(
  join(REPO, 'atlas', sandboxEntry.path.replace('./', '')), 'utf8');

function makeElement(tag) {
  return { tagName: tag, style: {}, dataset: {}, children: [], classList: {
      add() {}, remove() {}, contains: () => false, toggle: () => false },
    appendChild(child) { this.children.push(child); return child; },
    addEventListener() {}, removeEventListener() {}, setAttribute() {},
    getAttribute: () => null, querySelector: () => null, querySelectorAll: () => [],
    remove() {}, closest: () => null, getBoundingClientRect: () => ({
      x: 0, y: 0, width: 0, height: 0, top: 0, left: 0, right: 0, bottom: 0 })
  };
}

class MutationObserverStub { observe() {} disconnect() {} }

function sandboxContext() {
  const documentStub = {
    baseURI: 'https://ventusltd.github.io/gridatlas/atlas/',
    head: makeElement('head'), body: makeElement('body'), _byId: new Map(),
    getElementById() { return null; }, createElement: makeElement,
    querySelector: () => null, querySelectorAll: () => [], addEventListener() {}
  };
  const box = {
    window: { initVentusMap: (options) => options, matchMedia: () => ({ matches: false }),
      requestAnimationFrame: () => 0, cancelAnimationFrame: () => {},
      MutationObserver: MutationObserverStub, location: { search: '' },
      addEventListener() {}, innerWidth: 1280 },
    document: documentStub, console,
    fetch: async () => ({ ok: false, status: 404, json: async () => ({}) }),
    URL, Math, JSON, Number, String, Array, Object, Set, Map, Boolean, Error, RegExp,
    setTimeout, clearTimeout, setInterval, clearInterval, performance,
    requestAnimationFrame: () => 0, cancelAnimationFrame: () => {},
    MutationObserver: MutationObserverStub
  };
  box.window.maplibregl = { Map: class { constructor() {} on() {} once() {}
    getStyle() { return { layers: [] }; } isStyleLoaded() { return false; }
    getContainer() { return makeElement('div'); } }, Popup: class {} };
  box.maplibregl = box.window.maplibregl;
  box.window.window = box.window;
  box.globalThis = box;
  return box;
}

/* The modules the composition supplies from another cartridge. Since
   202609012350 the sandbox does not carry its own geodesy, so running
   it alone throws before it registers anything to compare against. */
const composition = JSON.parse(
  await readFile(join(REPO, 'atlas', 'current.json'), 'utf8'));
const siblingModules = await (async () => {
  const out = [];
  for (const entry of (composition.cartridges || [])) {
    if (entry.id === 'sld-sandbox' || !entry.assembled_from) continue;
    let manifest;
    try {
      manifest = JSON.parse(await readFile(
        join(REPO, 'atlas', String(entry.assembled_from).replace(/^\.\//, '')), 'utf8'));
    } catch { continue; }
    for (const part of (manifest.assembled_from || [])) {
      if (part.role !== 'module') continue;
      out.push(await readFile(join(REPO, part.path), 'utf8'));
    }
  }
  return out.join('\n');
})();

const sandboxBox = sandboxContext();
vm.createContext(sandboxBox);
if (siblingModules) vm.runInContext(siblingModules, sandboxBox, { filename: 'siblings.js' });
vm.runInContext(sandboxSource, sandboxBox, { filename: 'sld-sandbox.js' });
const incumbent = sandboxBox.window.__GRIDATLAS_NEON_LINKS__?.measure;

console.log('\nparity: geodesy against the incumbent measurement\n');
check('the incumbent exposes its measurement for comparison', Boolean(incumbent));

/* Cases chosen because each one has bitten this estate at least once. */
const DISTANCE_CASES = [
  ['Cottam to its substation', -0.643208, 53.352088, -0.78, 53.3],
  ['West Burton to its PoC', -0.6774547, 53.2926216, -0.812, 53.361],
  ['Cleve Hill, a two-kilometre hop', 0.913885, 51.338767, 0.9404896, 51.3381981],
  ['the length of GB', -1.0, 50.0, -1.0, 58.0],
  ['identical points', -1.0, 53.0, -1.0, 53.0],
  ['across the prime meridian', -0.001, 51.5, 0.001, 51.5]
];
let distancesEqual = true;
for (const [label, lon1, lat1, lon2, lat2] of DISTANCE_CASES) {
  const a = incumbent.distanceKm(lon1, lat1, lon2, lat2);
  const b = modules.geodesy.distanceKm(lon1, lat1, lon2, lat2);
  const same = Math.abs(a - b) < 1e-12;
  if (!same) distancesEqual = false;
  check(`distance parity: ${label}`, same, same ? '' : `${a} vs ${b}`);
}
check('every distance case agrees to floating point', distancesEqual);

console.log('\nparity: the voltage contract, where magnitude is not the unit\n');
const VOLTAGE_CASES = [
  ['a 400 kV substation', { voltage: '400000' }],
  ['two voltages at one site', { voltage: '400000;275000' }],
  ['the traction supply that read as 750 kV', { voltage: '33000;750' }],
  ['a 415 V works supply', { voltage: '33000;11000;415' }],
  ['an explicit kv property', { kv: '132' }],
  ['nothing at all', {}],
  ['a malformed token', { voltage: 'not a number' }]
];
for (const [label, properties] of VOLTAGE_CASES) {
  const a = JSON.stringify(incumbent.voltagesKv(properties));
  const b = JSON.stringify(modules.geodesy.voltagesKv(properties));
  check(`voltage parity: ${label}`, a === b, a === b ? '' : `${a} vs ${b}`);
}

console.log('\nparity: representative point, where a polygon is not its first corner\n');
const GEOMETRY_CASES = [
  ['a point', { type: 'Point', coordinates: [-1.5, 53.2] }],
  ['a square polygon', { type: 'Polygon', coordinates: [[[0, 0], [0, 2], [2, 2], [2, 0]]] }],
  ['a multipolygon', { type: 'MultiPolygon',
    coordinates: [[[[1, 1], [1, 3], [3, 3], [3, 1]]]] }],
  ['a line', { type: 'LineString', coordinates: [[0, 0], [1, 1]] }],
  ['nothing', null]
];
for (const [label, geometry] of GEOMETRY_CASES) {
  const a = JSON.stringify(incumbent.representativePoint(geometry));
  const b = JSON.stringify(modules.geodesy.representativePoint(geometry));
  check(`geometry parity: ${label}`, a === b, a === b ? '' : `${a} vs ${b}`);
}

check('the one deliberate difference is defensive, not behavioural', (() => {
  /* A Point with no coordinates: the incumbent throws, the module returns
     null. No real geometry reaches this path — every case above agrees —
     and the difference is asserted here so it is on the record rather
     than discovered later by someone debugging a null. */
  let incumbentThrew = false;
  try { incumbent.representativePoint({ type: 'Point' }); }
  catch (_) { incumbentThrew = true; }
  return incumbentThrew && modules.geodesy.representativePoint({ type: 'Point' }) === null;
})());

/* ── parity: the lookup against the substation cartridge ───────────────── */

const substationEntry = CURRENT.cartridges.find(c => c.id === 'substation-intelligence');
const substationSource = await readFile(
  join(REPO, 'atlas', substationEntry.path.replace('./', '')), 'utf8');

const PRODUCT = {
  schema: 'data-grid-gb.connection-points.v3',
  counts: { connection_points: 3 },
  connection_points: [
    { site_code: 'COTT', name: 'COTTAM', transmission_owner: 'NGET',
      voltages_kv: [400], circuits: 8, transformers: 0,
      location: { lat: 53.3, lon: -0.78, matched_by: 'exact_name' } },
    { site_code: 'WBUR', name: 'WEST BURTON', transmission_owner: 'NGET',
      voltages_kv: [400, 132], circuits: 8, transformers: 6,
      location: { lat: 53.361, lon: -0.812, matched_by: 'exact_name' } },
    { site_code: 'NOWH', name: 'NOWHERE MAPPED', transmission_owner: 'NGET',
      voltages_kv: [132], circuits: 1, transformers: 0 }
  ]
};

const substationBox = sandboxContext();
substationBox.fetch = async () => ({ ok: true, status: 200,
  json: async () => PRODUCT, headers: { get: () => null } });
substationBox.window.fetch = substationBox.fetch;
vm.createContext(substationBox);
try { vm.runInContext(substationSource, substationBox, { filename: 'substation.js' }); }
catch (_) { /* the carried engine will not boot under a stub; PART 2 registers first */ }
const network = substationBox.window.__GRIDATLAS_NETWORK__;
if (network) await network.ready;

console.log('\nparity: substation lookup against the incumbent cartridge\n');
check('the incumbent loaded the fixture product', network?.loaded === true);
const moduleIndex = modules.substationLookup.index(PRODUCT.connection_points);

const NAME_CASES = ['Cottam Substation', 'COTTAM', 'cottam substation',
  'West Burton', 'West Burton 400kV Substation', 'Nowhere Mapped',
  'Somewhere Nobody Published'];
for (const name of NAME_CASES) {
  const a = network.byName(name);
  const b = moduleIndex.byName(name);
  const same = (a?.site_code ?? null) === (b?.site_code ?? null);
  check(`name parity: "${name}" -> ${a?.site_code ?? 'null'}`, same,
    same ? '' : `${a?.site_code} vs ${b?.site_code}`);
}

const NEAREST_CASES = [
  ['from Cottam Solar, any voltage', -0.643208, 53.352088, 0],
  ['from Cottam Solar, 400 kV only', -0.643208, 53.352088, 400],
  ['from West Burton Solar, 400 kV only', -0.6774547, 53.2926216, 400]
];
for (const [label, lon, lat, minimumKv] of NEAREST_CASES) {
  const a = network.nearest(lon, lat, { minimumKv });
  const b = moduleIndex.nearest(lon, lat, { minimumKv });
  const same = (a?.point?.site_code ?? null) === (b?.point?.site_code ?? null)
    && Math.abs((a?.km ?? 0) - (b?.km ?? 0)) < 1e-12;
  check(`nearest parity: ${label} -> ${a?.point?.site_code ?? 'null'}`, same,
    same ? '' : `${a?.point?.site_code}@${a?.km} vs ${b?.point?.site_code}@${b?.km}`);
}
check('an unmapped site is never returned as nearest',
  moduleIndex.nearest(-0.6, 53.3, { minimumKv: 0 })?.point?.site_code !== 'NOWH');

console.log(`\n${passed}/${passed + failures.length} checks passed`);
if (failures.length) {
  console.error('\nFAILURES');
  for (const failure of failures) console.error('  ' + failure);
  process.exit(1);
}
console.log('the modules answer exactly as the 4,000 lines do. Nothing has been '
  + 'swapped; parity is the precondition for asking.');