GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Kuiper, cosmos and drawing engines / cosmic / tools/explore/theme

Test Pilot Browser and 2 more files

A test in the theme folder of Cosmic covering the Renewable Energy Planning Database (REPD) register. It is built from the served step (`served`) and the browser step (`browser`).

521 lines of Python from cosmic, in 3 files. Topic: Kuiper, cosmos and drawing engines. Section 1159 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. Test Ide test · cosmic / tools/explore/theme/test_ide.py lines 1–211
  2. Test Pilot Bng test · cosmic / tools/explore/theme/test_pilot_bng.py lines 1–56
  3. Test Pilot Browser test · cosmic / tools/explore/theme/test_pilot_browser.py lines 1–254

Test Ide

A test in the theme folder of Cosmic that checks Pilot. It is built from the served step (`served`).

testcosmic / tools/explore/theme/test_ide.py · lines 1–211 of 211 · Not reached from any entry point (candidate for review) · pattern _chromium (shared by 7 files)

What it does
It tests its inputs. Defines 14 functions or classes, including test_ide_files_exist_and_parse, test_ide_has_no_external_hosts_or_cdn, test_ide_never_rewrites_page_text, test_ide_css_is_scoped_to_body_ide, test_ide_palette_and_motion. Uses libraries __future__, functools, http.server, json, os. Side effects: changes the web page (DOM); reads or writes files; starts processes.
Inputs & outputs
In: JSON file pilot-places.json; command-line arguments.
What it achieves
Tests for the Explore Code IDE layer and Pilot page (HOTBAR-36).
Why it matters
Guards the behaviour of Pilot.
Application
cosmic · tools/explore/theme · test
Uses
Pilot (script call), __future__, functools, http.server, json, os, re, shutil, socketserver
Used by
none found
Produces
test_ide_files_exist_and_parse, test_ide_has_no_external_hosts_or_cdn, test_ide_never_rewrites_page_text, test_ide_css_is_scoped_to_body_ide, test_ide_palette_and_motion, test_ide_keys_and_features_present, test_phone_bar_targets_44px, test_pilot_page_local_only_except_listed_hosts, test_pilot_provenance_header, test_scan_text_rules, test_places_are_real_coordinates_with_keys, served
Defines here
test_ide_files_exist_and_parse, test_ide_has_no_external_hosts_or_cdn, test_ide_never_rewrites_page_text, test_ide_css_is_scoped_to_body_ide, test_ide_palette_and_motion, test_ide_keys_and_features_present, test_phone_bar_targets_44px, test_pilot_page_local_only_except_listed_hosts, test_pilot_provenance_header, test_scan_text_rules, test_places_are_real_coordinates_with_keys, _chromium, served, test_browser_layout_keys_and_js_off
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
cosmic@51bebf892d63a617408bc5e25b270b9f893e9c03 tools/explore/theme/test_ide.py:1-211 · blob 159d03162c6210b6e16c75c4eb8b012a50a23850 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, process · domain stage: unknown · users: none · canonical: unreached_review
"""Tests for the Explore Code IDE layer and Pilot page (HOTBAR-36).

Static tests always run. Browser tests run when Playwright and a Chromium build are available and the
published site copy exists (EXPLORE_SITE, default /tmp/site8/explore-code); otherwise they are skipped.
Run: python3 -m pytest -q tools/explore/theme/test_ide.py
"""
from __future__ import annotations

import functools, http.server, json, os, re, shutil, socketserver, subprocess, tempfile, threading
from pathlib import Path

import pytest

HERE = Path(__file__).resolve().parent
IDE_JS, IDE_CSS = HERE / 'ide.js', HERE / 'ide.css'
PILOT_JS, PILOT_HTML, PILOT_CSS = HERE / 'pilot.js', HERE / 'pilot.html', HERE / 'pilot.css'
PLACES = HERE / 'pilot-places.json'
SITE = Path(os.environ.get('EXPLORE_SITE', '/tmp/site8/explore-code'))
HOSTS_MD = Path(os.environ.get('PILOT_HOSTS', '/tmp/vk/bonusB/pilot/HOSTS.md'))
SRC = Path('/home/claude/src')
KEY_RE = re.compile(r'^(\S+)@([0-9a-f]{40}) (.+):(\d+)-(\d+) ([0-9a-f]{40}|-)$')


# ---------------------------------------------------------------- static: IDE layer
def test_ide_files_exist_and_parse():
    assert IDE_JS.exists() and IDE_CSS.exists()
    if shutil.which('node'):
        r = subprocess.run(['node', '-e', 'new Function(require("fs").readFileSync(process.argv[1],"utf8"))', str(IDE_JS)], capture_output=True, text=True)
        assert r.returncode == 0, r.stderr


def test_ide_has_no_external_hosts_or_cdn():
    for p in (IDE_JS, IDE_CSS):
        s = p.read_text()
        assert not re.search(r'https?://', s), f'{p.name} must not reference any host'
        assert '@import' not in s


def test_ide_never_rewrites_page_text():
    s = IDE_JS.read_text()
    assert 'innerHTML' not in s and 'outerHTML' not in s and 'document.write' not in s and 'insertAdjacentHTML' not in s
    # textContent is only assigned on elements the layer created (facts, top bar, toast, lists, gutter)
    for m in re.finditer(r'(\w+)\.textContent\s*=', s):
        assert m.group(1) in {'n', 'facts', 'top', 'gut', 'box', 'ul', 'toastEl', 'mapPanel', 'btn', 'tape'}, m.group(0)


def test_ide_css_is_scoped_to_body_ide():
    css = re.sub(r'/\*.*?\*/', '', IDE_CSS.read_text(), flags=re.S)
    css = re.sub(r'@keyframes[^{]+\{(?:[^{}]*\{[^{}]*\})*\s*\}', '', css)
    for sel in re.findall(r'([^{}@;]+)\{', css):
        sel = sel.strip()
        if not sel or sel.startswith(('from', 'to', '0%', 'media')) or re.match(r'^\d', sel):
            continue
        for part in sel.split(','):
            assert part.strip().startswith('body.ide'), f'unscoped selector: {part.strip()}'


def test_ide_palette_and_motion():
    css = IDE_CSS.read_text().lower()
    for c in ('#000', '#0b0e14', '#2f343d', '#fff', '#a6adbb', '#66ccff', '#00ffff'):
        assert c in css
    assert 'prefers-reduced-motion' in css
    assert 'prefers-reduced-motion' in IDE_JS.read_text()


def test_ide_keys_and_features_present():
    s = IDE_JS.read_text()
    for k in ("case 'j'", "case 'k'", "case ']'", "case '['", "case 'u'", "case 'U'", "case '/'", "case 'v'", "case '?'"):
        assert k in s, k
    assert "e.key === 'k' || e.key === 'K'" in s  # Ctrl/Cmd+K palette
    for word in ('Copy key', 'Copy lines', 'Show in map', "'../visual/'", '#file=', 'history.pushState', 'ec-ide:', 'pl:hud-ready', 'data-pl-slot=modes'):
        assert word in s, word
    for m in ('read', 'map', 'pilot', 'clarity'):
        assert f"'{m}'" in s


def test_phone_bar_targets_44px():
    css = IDE_CSS.read_text()
    assert re.search(r'\.ide-bb \{[^}]*min-height: 44px', css)


# ---------------------------------------------------------------- static: Pilot
def test_pilot_page_local_only_except_listed_hosts():
    html = PILOT_HTML.read_text()
    assert not re.search(r'<(script|link)[^>]+(src|href)="https?://', html), 'no external scripts/styles'
    hosts = set(re.findall(r'https://([a-z0-9.-]+)/', PILOT_JS.read_text()))
    # imagery + terrain, plus GridAtlas published data (PILOT.data.GA, Pilot-200 CONTRACT.md section 9)
    assert {'server.arcgisonline.com', 's3.amazonaws.com'} <= hosts <= {'server.arcgisonline.com', 's3.amazonaws.com', 'ventusltd.github.io'}
    if HOSTS_MD.exists():
        md = HOSTS_MD.read_text()
        for h in hosts & {'server.arcgisonline.com', 's3.amazonaws.com'}:   # newer hosts: test_pilot_static.ALLOWED_HOSTS
            assert h in md, f'{h} missing from HOSTS.md'
    js = PILOT_JS.read_text()
    assert 'Esri, Maxar, Earthstar Geographics' in js and 'OpenStreetMap' in js and 'offline' in js


def test_pilot_provenance_header():
    js = PILOT_JS.read_text()
    assert 'globalgrid2050@9a12d0e24526a90dc1c75ac7d372c95e58d0c8ad energy-transition-simulator/202610290235/mod/pylons-real.js' in js.replace('\n     ', ' ')
    assert 'solar-design-studio/202609271853-site-world/world/arrival.mjs' in js


def test_scan_text_rules():
    import importlib.util
    spec = importlib.util.spec_from_file_location('pilot', HERE / 'pilot.py'); mod = importlib.util.module_from_spec(spec); spec.loader.exec_module(mod)
    got = list(mod.scan_text("const s = { name: 'West Burton', lat: 53.3616, lon: -0.8092 };\nfoo(1.234, 2.345)\nconst p = [-1.2589, 51.7528];"))
    assert (53.3616, -0.8092, 1, 'West Burton') in got
    assert (51.7528, -1.2589, 3, None) in got
    assert all(r[2] != 2 for r in got), 'pairs outside GB/IE bounds are not places'


@pytest.mark.skipif(not PLACES.exists(), reason='pilot-places.json not built')
def test_places_are_real_coordinates_with_keys():
    d = json.loads(PLACES.read_text())
    assert d['schema'] == 'explore-pilot-places-v1' and d['places']
    for p in d['places']:
        assert 49.8 <= p['lat'] <= 60.95 and -10.7 <= p['lon'] <= 1.9
        assert p['files'], p['name']
        for f in p['files']:
            m = KEY_RE.match(f['key']); assert m, f['key']
            assert int(m.group(4)) == f['line'] and f['url'].startswith('s/')
    # spot-check: the coordinate is written on the keyed line in the clone at that commit
    checked = 0
    for p in d['places'][:15]:
        f = p['files'][0]; m = KEY_RE.match(f['key'])
        clone = SRC / m.group(1)
        if not clone.is_dir():
            continue
        text = subprocess.run(['git', '-C', str(clone), 'show', f'{m.group(2)}:{m.group(3)}'], capture_output=True, text=True, errors='replace').stdout
        line = text.split('\n')[f['line'] - 1]
        nums = [float(x) for x in re.findall(r'-?\d{1,3}\.\d{3,}', line)]
        assert any(abs(n - p['lat']) < 0.002 for n in nums) and any(abs(n - p['lon']) < 0.002 for n in nums), (p['name'], line[:200])
        checked += 1
    assert checked or not SRC.exists()


# ---------------------------------------------------------------- browser
def _chromium():
    try:
        from playwright.sync_api import sync_playwright  # noqa: F401
    except Exception:
        return None
    for c in ('/opt/pw-browsers/chromium-1243/chrome-linux64/chrome',):
        if Path(c).exists():
            return c
    return ''


CH = _chromium()
needs_browser = pytest.mark.skipif(CH is None or not (SITE / 's' / '0001.html').exists(), reason='Playwright or site copy unavailable')


@pytest.fixture(scope='module')
def served():
    tmp = Path(tempfile.mkdtemp(prefix='ide-test-'))
    (tmp / 's').mkdir(); (tmp / 'raw' / 's').mkdir(parents=True); (tmp / 'theme').mkdir()
    shutil.copy(SITE / 'explore.css', tmp / 'explore.css'); shutil.copy(SITE / 'index.html', tmp / 'index.html')
    (tmp / 'favicon.ico').write_bytes(b'')
    for n in ('0001', '0500'):
        h = (SITE / 's' / f'{n}.html').read_text()
        (tmp / 'raw' / 's' / f'{n}.html').write_text(h.replace('href="../', 'href="../../'))
        (tmp / 's' / f'{n}.html').write_text(h.replace('</head>', '<link rel="stylesheet" href="../theme/ide.css"><script defer src="../theme/ide.js"></script></head>', 1))
    for f in ('ide.css', 'ide.js'):
        shutil.copy(HERE / f, tmp / 'theme' / f)
    handler = functools.partial(http.server.SimpleHTTPRequestHandler, directory=str(tmp))
    handler.log_message = lambda *a, **k: None
    srv = socketserver.TCPServer(('127.0.0.1', 0), handler)
    threading.Thread(target=srv.serve_forever, daemon=True).start()
    yield f'http://127.0.0.1:{srv.server_address[1]}'
    srv.shutdown(); shutil.rmtree(tmp, ignore_errors=True)


@needs_browser
def test_browser_layout_keys_and_js_off(served):
    from playwright.sync_api import sync_playwright
    with sync_playwright() as p:
        b = p.chromium.launch(**({'executable_path': CH} if CH else {}))
        for w, h in ((390, 844), (820, 1180), (1366, 768), (1920, 1080)):
            ctx = b.new_context(viewport={'width': w, 'height': h}, has_touch=w < 900)
            pg = ctx.new_page(); errs = []
            pg.on('console', lambda m: errs.append(m.text) if m.type == 'error' else None)
            pg.on('pageerror', lambda e: errs.append(str(e)))
            pg.goto(served + '/s/0001.html', wait_until='networkidle')
            assert pg.evaluate('document.body.classList.contains("ide")')
            sw, iw = pg.evaluate('[document.documentElement.scrollWidth, innerWidth]')
            assert sw <= iw, f'horizontal scroll at {w}: {sw} > {iw}'
            if w < 1200:
                hs = pg.evaluate('[...document.querySelectorAll("#ide-bar .ide-bb")].map(e => e.getBoundingClientRect().height)')
                assert hs and min(hs) >= 44
            else:
                assert pg.locator('#ide-rail').is_visible() and pg.locator('#ide-facts').is_visible()
            assert not errs, errs
            ctx.close()
        ctx = b.new_context(viewport={'width': 1920, 'height': 1080}); pg = ctx.new_page()
        pg.goto(served + '/s/0001.html', wait_until='networkidle')
        pg.keyboard.press('j'); assert pg.evaluate('window.__exploreIDE.cur()') == 1 and pg.evaluate('location.hash') == '#f2'
        pg.keyboard.press('k'); assert pg.evaluate('window.__exploreIDE.cur()') == 0
        pg.go_back(); pg.wait_for_timeout(200); assert pg.evaluate('location.hash') == '#f2'
        pg.keyboard.press('?'); assert pg.locator('#ide-ov').count() == 1; pg.keyboard.press('Escape')
        pg.keyboard.press('Control+k'); assert pg.locator('.ide-pal').count() == 1; pg.keyboard.press('Escape')
        pg.keyboard.press('4'); assert pg.evaluate('document.body.classList.contains("ide-clarity")'); pg.keyboard.press('1')
        with pg.expect_navigation():
            pg.keyboard.press(']')
        assert pg.url.endswith('/s/0002.html')
        ctx.close()
        off = b.new_context(java_script_enabled=False); pg = off.new_page()
        for n in ('0001', '0500'):
            pg.goto(f'{served}/s/{n}.html'); a = pg.evaluate('document.body.innerText')
            pg.goto(f'{served}/raw/s/{n}.html'); r = pg.evaluate('document.body.innerText')
            assert a == r, f'JS-off innerText changed on {n}'
        off.close(); b.close()

Test Pilot Bng

A test in the theme folder of Cosmic covering solar.

testcosmic / tools/explore/theme/test_pilot_bng.py · lines 1–56 of 56 · Not reached from any entry point (candidate for review)

What it does
It tests solar. Defines test_goto_bng_matches_source. Uses libraries __future__, json, shutil, subprocess, pathlib. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain terms in the code: solar.
Inputs & outputs
Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid).
What it achieves
OS grid parity: `pilot-goto.js`'s 11 BNG functions vs their source `bng.mjs` (W10 CAPSTAN-41; THEODOLITE-19 STAR-1 #1).
Why it matters
No other file in the estate was found to import it.
Application
cosmic · tools/explore/theme · test
Uses
__future__, json, shutil, subprocess, pathlib, pytest
Used by
none found
Produces
test_goto_bng_matches_source
Defines here
test_goto_bng_matches_source
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
cosmic@51bebf892d63a617408bc5e25b270b9f893e9c03 tools/explore/theme/test_pilot_bng.py:1-56 · blob 2c11d631e254d220146a305f2ddee27fd56423f2 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: unknown · users: none · canonical: unreached_review
"""OS grid parity: pilot-goto.js's 11 BNG functions vs their source bng.mjs (W10 CAPSTAN-41; THEODOLITE-19 STAR-1 #1).

Source: Ventusltd/globalgrid2050@9a12d0e24526a90dc1c75ac7d372c95e58d0c8ad
solar-design-studio/202609271853-site-world/world/bng.mjs:45-212 (families 144670-144680). The block between the
"OS National Grid (pure maths)" and "query classifier" markers in pilot-goto.js is evaluated on its own and compared
with the original over a lattice across GB. Needs node and the globalgrid2050 clone (skips otherwise).
Run: python3 -m pytest -q tools/explore/theme/test_pilot_bng.py
"""
from __future__ import annotations

import json, shutil, subprocess
from pathlib import Path

import pytest

HERE = Path(__file__).resolve().parent
GG = Path('/home/claude/src/globalgrid2050')
SHA = '9a12d0e24526a90dc1c75ac7d372c95e58d0c8ad'
PATH = 'solar-design-studio/202609271853-site-world/world/bng.mjs'


@pytest.mark.skipif(not shutil.which('node') or not (GG / '.git').exists(), reason='node or globalgrid2050 clone unavailable')
def test_goto_bng_matches_source(tmp_path):
    src = subprocess.run(['git', '-C', str(GG), 'show', f'{SHA}:{PATH}'], capture_output=True, text=True).stdout
    assert 'wgs84ToBng' in src
    (tmp_path / 'bng.mjs').write_text(src)
    goto = (HERE / 'pilot-goto.js').read_text()
    a = goto.index('OS National Grid (pure maths)'); a = goto.index('\n', a) + 1
    b = goto.index('// ----', a)
    (tmp_path / 'block.js').write_text(goto[a:b])
    (tmp_path / 't.mjs').write_text('''
import fs from 'node:fs';
const B = await import('./bng.mjs');
const G = new Function(fs.readFileSync(new URL('./block.js', import.meta.url), 'utf8') + '\\nreturn {bngToWgs84, wgs84ToBng, parseGridRef, gridRef};')();
const v = (p, k, i) => p[k] ?? p[i];
let maxEN = 0, maxLL = 0, diff = 0, n = 0;
for (let lat = 50; lat <= 58.5; lat += 0.37) for (let lon = -6; lon <= 1.7; lon += 0.29) {
  n++;
  const a = B.wgs84ToBng(lat, lon), b = G.wgs84ToBng(lat, lon);
  const ae = v(a, 'e', 0), an = v(a, 'n', 1);
  maxEN = Math.max(maxEN, Math.hypot(ae - v(b, 'e', 0), an - v(b, 'n', 1)));
  const c = B.bngToWgs84(ae, an), d = G.bngToWgs84(ae, an);
  maxLL = Math.max(maxLL, Math.abs(v(c, 'lat', 0) - v(d, 'lat', 0)), Math.abs(v(c, 'lon', 1) - v(d, 'lon', 1)));
  if (String(B.gridRef(ae, an, 10)) !== String(G.gridRef(ae, an, 10))) diff++;
}
const pb = B.parseGridRef('TQ 30624 78388'), pg = G.parseGridRef('TQ 30624 78388');
console.log(JSON.stringify({n, maxEN, maxLL, diff, parse: [v(pb, 'e', 0), v(pb, 'n', 1), v(pg, 'e', 0), v(pg, 'n', 1)]}));
''')
    r = subprocess.run(['node', 't.mjs'], capture_output=True, text=True, cwd=tmp_path, timeout=120)
    assert r.returncode == 0, r.stderr
    out = json.loads(r.stdout)
    assert out['n'] > 600
    assert out['maxEN'] < 1e-6, out          # metres
    assert out['maxLL'] < 1e-12, out         # degrees
    assert out['diff'] == 0, out             # 10-figure grid references identical
    assert out['parse'][:2] == out['parse'][2:] == [530624, 178388], out

Test Pilot Browser

A test in the theme folder of Cosmic covering the Renewable Energy Planning Database (REPD) register. It is built from the served step (`served`) and the browser step (`browser`).

testcosmic / tools/explore/theme/test_pilot_browser.py · lines 1–254 of 254 · Entry point · pattern _chromium (shared by 7 files)

What it does
It tests the REPD register. Defines 14 functions or classes, including _chromium, served, browser, _open, _has_pilot. Uses libraries __future__, functools, http.server, importlib.util, json. Side effects: changes the web page (DOM); reads or writes files.
Why it exists in the grid workflow
Domain terms in the code: the REPD register.
Inputs & outputs
Out: JSON file play-index.json; JSON file repd-fixture.json.
Downstream impact
Used directly by 1 file: CI Chess Workflow (cosmic).
What it achieves
Browser tests for the Pilot / Drone View page with every shipped module (Pilot-200, W10 CAPSTAN-41).
Why it matters
Run by CI Chess Workflow.
Application
cosmic · tools/explore/theme · test
Uses
__future__, functools, http.server, importlib.util, json, os, shutil, socketserver
Used by
run by CI Chess Workflow (workflow run)
Produces
served, browser, test_loads_clean_no_sideways_scroll_and_taps, test_contract_surface_and_modules_registered, test_flyto_instant_and_reduced_motion, test_long_flight_fast_arc_reaches_target, test_module_smoke, test_vicinity_query_contract_states, test_no_overlapping_controls_at_390, test_repd_ranking_matches_gridatlas_order, test_vicinity_substations_never_wait_for_optional_layers
Defines here
_chromium, served, browser, _open, _has_pilot, test_loads_clean_no_sideways_scroll_and_taps, test_contract_surface_and_modules_registered, test_flyto_instant_and_reduced_motion, test_long_flight_fast_arc_reaches_target, test_module_smoke, test_vicinity_query_contract_states, test_no_overlapping_controls_at_390, test_repd_ranking_matches_gridatlas_order, test_vicinity_substations_never_wait_for_optional_layers
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
cosmic@51bebf892d63a617408bc5e25b270b9f893e9c03 tools/explore/theme/test_pilot_browser.py:1-254 · blob f6527098ef470b440b46cccec66c604b4a085e08 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: unknown · users: none · canonical: unknown
"""Browser tests for the Pilot / Drone View page with every shipped module (Pilot-200, W10 CAPSTAN-41).

Builds pilot/ exactly as inject.py publishes it (copy_assets + sync_pilot) into a temp site, serves it locally and
drives it with Playwright at 390x844 (primary, touch) and 1366x768. Runs with ?offline=1 so no external host is
contacted; modules must degrade quietly offline (CONTRACT.md section 9). Skips without Playwright/Chromium.
Screenshots: $PILOT_SHOTS (default /tmp/vk/pilot200/shots).
Run: python3 -m pytest -q tools/explore/theme/test_pilot_browser.py
"""
from __future__ import annotations

import functools, http.server, importlib.util, json, os, shutil, socketserver, tempfile, threading
from pathlib import Path

import pytest

HERE = Path(__file__).resolve().parent
SHOTS = Path(os.environ.get('PILOT_SHOTS', '/tmp/vk/pilot200/shots'))
MOD_NAMES = sorted(p.stem[6:] for p in HERE.glob('pilot-*.js'))
ORIGIN = (52.2053, 0.1218)
CONTRACT_MEMBERS = ('cam', 'camLL', 'flyTo', 'stop', 'onFrame', 'on', 'off', 'emit', 'ready', 'module', 'modules',
                    'addLayer', 'removeLayer', 'layer', 'layers', 'setLayerVisible', 'registerMode', 'setMode', 'mode',
                    'hud', 'panel', 'openPanel', 'closePanel', 'card', 'note', 'esc', 'credit', 'toLatLon', 'fromLatLon',
                    'dist', 'bearing', 'ground', 'setFast', 'fast', 'hash', 'debug', 'data')


def _chromium():
    try:
        from playwright.sync_api import sync_playwright  # noqa: F401
    except Exception:
        return None
    for c in sorted(Path('/opt/pw-browsers').glob('chromium-*/chrome-linux64/chrome')):
        return str(c)
    return ''


CH = _chromium()
pytestmark = pytest.mark.skipif(CH is None, reason='Playwright unavailable')


@pytest.fixture(scope='module')
def served():
    spec = importlib.util.spec_from_file_location('inject', HERE / 'inject.py')
    inj = importlib.util.module_from_spec(spec); spec.loader.exec_module(inj)
    tmp = Path(tempfile.mkdtemp(prefix='pilot-test-'))
    vers = inj.copy_assets(tmp)
    inj.sync_pilot(tmp, vers)
    (tmp / 'index.html').write_text('<!doctype html><title>Explore Code</title><p>hub</p>')
    (tmp / 'favicon.ico').write_bytes(b'')
    (tmp / 'theme' / 'play-index.json').write_text('{}')
    # REPD fixture for the vicinity query-contract tests: one project ~1 km north of ORIGIN (not real data; test only)
    (tmp / 'pilot' / 'repd-fixture.json').write_text(json.dumps({'schema': 'gridatlas.browser-registry.v1', 'generation': 'test', 'source': {'dataset': 'test fixture'},
        'records': [{'repd_ref': 'T1', 'name': 'Fixture project', 'technology': 'solar', 'status': 'operational', 'capacity_mw': 5,
                     'latitude': ORIGIN[0] + 0.009, 'longitude': ORIGIN[1]},
                    # ranking tie-break fixtures, far from ORIGIN (Highlands), identical names and scores
                    {'repd_ref': '30', 'name': 'Alpha Glen', 'technology': 'wind_onshore', 'status': 'operational', 'capacity_mw': 50, 'latitude': 57.3, 'longitude': -4.9},
                    {'repd_ref': '10', 'name': 'Alpha Glen', 'technology': 'wind_onshore', 'status': 'operational', 'capacity_mw': 1, 'latitude': 57.31, 'longitude': -4.91}]}))
    handler = functools.partial(http.server.SimpleHTTPRequestHandler, directory=str(tmp))
    handler.log_message = lambda *a, **k: None
    srv = socketserver.ThreadingTCPServer(('127.0.0.1', 0), handler)
    srv.daemon_threads = True
    threading.Thread(target=srv.serve_forever, daemon=True).start()
    yield f'http://127.0.0.1:{srv.server_address[1]}/pilot/index.html'
    srv.shutdown(); shutil.rmtree(tmp, ignore_errors=True)


@pytest.fixture(scope='module')
def browser():
    from playwright.sync_api import sync_playwright
    with sync_playwright() as p:
        b = p.chromium.launch(**({'executable_path': CH} if CH else {}))
        yield b
        b.close()


def _open(browser, url, w, h, reduced=False):
    ctx = browser.new_context(viewport={'width': w, 'height': h}, has_touch=w < 900, is_mobile=w < 900,
                              reduced_motion='reduce' if reduced else 'no-preference')
    pg = ctx.new_page(); errs, ext = [], []
    pg.on('console', lambda m: errs.append(m.text) if m.type == 'error' else None)
    pg.on('pageerror', lambda e: errs.append(str(e)))
    pg.on('request', lambda r: ext.append(r.url) if not r.url.startswith(('http://127.0.0.1', 'data:', 'blob:')) else None)
    pg.goto(url + '?offline=1', wait_until='load')
    pg.wait_for_timeout(1200)
    return ctx, pg, errs, ext


def _has_pilot(pg):
    return pg.evaluate('!!(window.PILOT && window.PILOT.version)')


@pytest.mark.parametrize('w,h', [(390, 844), (1366, 768)])
def test_loads_clean_no_sideways_scroll_and_taps(served, browser, w, h):
    ctx, pg, errs, ext = _open(browser, served, w, h)
    SHOTS.mkdir(parents=True, exist_ok=True)
    pg.screenshot(path=str(SHOTS / f'pilot-{w}x{h}.png'))
    assert not errs, errs
    assert not ext, f'offline=1 must not contact external hosts: {ext[:5]}'
    sw, iw = pg.evaluate('[document.documentElement.scrollWidth, innerWidth]')
    assert sw <= iw, f'sideways scroll at {w}: {sw} > {iw}'
    assert pg.evaluate('(() => { const c = document.getElementById("pv"); return c && c.width > 0 && c.height > 0; })()')
    if w < 900:
        small = pg.evaluate('''[...document.querySelectorAll('button, a.pbtn, [role=button], input[type=range], select')]
            .filter(e => { const s = getComputedStyle(e), r = e.getBoundingClientRect();
                           return s.visibility !== 'hidden' && s.display !== 'none' && r.width > 0 && r.height > 0 && r.bottom > 0 && r.top < innerHeight; })
            .filter(e => { const r = e.getBoundingClientRect(); return Math.min(r.width, r.height) < 43.5; })
            .map(e => (e.id || e.className || e.tagName) + ':' + Math.round(e.getBoundingClientRect().width) + 'x' + Math.round(e.getBoundingClientRect().height))''')
        assert not small, f'tap targets under 44 px at {w}: {small}'
    ctx.close()


def test_contract_surface_and_modules_registered(served, browser):
    ctx, pg, errs, _ = _open(browser, served, 390, 844)
    if not _has_pilot(pg):
        ctx.close(); pytest.skip('core pilot.js does not expose window.PILOT yet (W01)')
    assert pg.evaluate('window.PILOT.version') == '1'
    assert pg.evaluate('!!window.__pilot'), 'window.__pilot back-compat'
    missing = pg.evaluate(f'{list(CONTRACT_MEMBERS)!r}.filter(k => !(k in window.PILOT))')
    assert not missing, f'PILOT is missing contract members: {missing}'
    assert pg.evaluate('typeof PILOT.data.fetchJSON') == 'function'
    assert pg.evaluate('PILOT.offline') is True
    got = pg.evaluate('PILOT.modules().map(m => m.name)')
    assert sorted(got) == MOD_NAMES, f'registered {got}, shipped {MOD_NAMES}'
    d = pg.evaluate('PILOT.debug()')
    assert {'fps', 'layers', 'origin', 'fast', 'mode'} <= set(d)
    assert not errs, errs
    ctx.close()


def test_flyto_instant_and_reduced_motion(served, browser):
    ctx, pg, errs, _ = _open(browser, served, 390, 844, reduced=True)
    if not _has_pilot(pg):
        ctx.close(); pytest.skip('core pilot.js does not expose window.PILOT yet (W01)')
    # Durham (54.7761, -1.5733) -> must arrive without a long animation under reduced motion
    t = pg.evaluate('''(async () => { const t0 = performance.now();
        await Promise.race([PILOT.flyTo(54.7761, -1.5733, {dist: 0, alt: 300}), new Promise((_, j) => setTimeout(() => j('timeout'), 4000))]);
        const c = PILOT.camLL(); return [performance.now() - t0, c.lat, c.lon]; })()''')
    assert t[0] < 2500, f'reduced motion flyTo took {t[0]:.0f} ms'
    assert pg.evaluate(f'PILOT.dist({t[1]}, {t[2]}, 54.7761, -1.5733)') < 1500
    assert not errs, errs
    ctx.close()


def test_long_flight_fast_arc_reaches_target(served, browser):
    ctx, pg, errs, _ = _open(browser, served, 1366, 768)
    if not _has_pilot(pg):
        ctx.close(); pytest.skip('core pilot.js does not expose window.PILOT yet (W01)')
    pg.evaluate('PILOT.flyTo(51.5072, -0.1276, {instant: true, dist: 0})')
    r = pg.evaluate('''(async () => { if ('_timeScale' in PILOT) PILOT._timeScale = 8;
        const t0 = performance.now();
        await Promise.race([PILOT.flyTo(52.2053, 0.1218, {dist: 0}), new Promise((_, j) => setTimeout(() => j('timeout'), 30000))]);
        const c = PILOT.camLL(); return [performance.now() - t0, PILOT.dist(c.lat, c.lon, 52.2053, 0.1218)]; })()''')
    assert r[1] < 1500, f'arrived {r[1]:.0f} m from Cambridge'
    assert not errs, errs
    ctx.close()


@pytest.mark.parametrize('name', MOD_NAMES)
def test_module_smoke(served, browser, name):
    """Each shipped module registers, adds its UI/layers without errors, and survives a flight offline."""
    ctx, pg, errs, ext = _open(browser, served, 390, 844)
    if not _has_pilot(pg):
        ctx.close(); pytest.skip('core pilot.js does not expose window.PILOT yet (W01)')
    assert name in pg.evaluate('PILOT.modules().map(m => m.name)')
    pg.evaluate('PILOT.flyTo(53.4808, -2.2426, {instant: true})')
    pg.wait_for_timeout(500)
    if name == 'goto':
        assert pg.evaluate('!!(PILOT.goto && typeof PILOT.goto === "object") || !!document.querySelector("[class*=p-goto-], [id^=p-goto-]")')
    if name == 'modes':
        for m in pg.evaluate('(PILOT.modes ? Object.keys(PILOT.modes) : [])') or []:
            pg.evaluate(f'PILOT.setMode({m!r})')
        pg.evaluate('PILOT.setMode("sat"); PILOT.setMode("map")')
    sw, iw = pg.evaluate('[document.documentElement.scrollWidth, innerWidth]')
    assert sw <= iw
    assert not errs, errs
    assert not ext, ext[:5]
    ctx.close()


def test_vicinity_query_contract_states(served, browser):
    """Review finding 1: radius in metres end to end; loaded / empty / error / timeout are distinct and shown."""
    ctx = browser.new_context(viewport={'width': 390, 'height': 844}, has_touch=True)
    pg = ctx.new_page()
    pg.route('**/*', lambda r: r.continue_() if r.request.url.startswith('http://127.0.0.1') else r.abort())
    pg.goto(served + '?repdsrc=repd-fixture.json', wait_until='load')
    pg.wait_for_timeout(800)
    if not pg.evaluate('!!(window.PILOT && PILOT.vicinity && PILOT.layer && PILOT.layer("repd"))'):
        ctx.close(); pytest.skip('vicinity or repd module not shipped')
    pg.evaluate('PILOT.layer("repd")._api.load()')
    lat, lon = ORIGIN
    # 1) a project 1 km away in a 10 km search is found
    r = pg.evaluate(f'PILOT.vicinity.deploy({lat}, {lon}, {{radiusKm: 10}}).then(x => ({{st: x.repd.status, n: x.repd.model && x.repd.model.count, km: x.repd.model && x.repd.model.rows[0] && x.repd.model.rows[0].km, ukpn: x.ukpn.status}}))')
    assert r['st'] == 'ok' and r['n'] == 1 and 0.9 < r['km'] < 1.1, r
    # 3) a failed fetch (UKPN archive unreachable) is an error, never "0 found"
    assert r['ukpn'] == 'error', r
    pg.evaluate('PILOT.openPanel && PILOT.openPanel("vicinity")')
    pg.evaluate('document.querySelector(".p-vicinity-tab[data-tab=ukpn]") && document.querySelector(".p-vicinity-tab[data-tab=ukpn]").click()')
    txt = pg.evaluate('(document.querySelector(".p-vicinity-list") || {}).textContent || ""')
    assert 'not the same as none nearby' in txt, txt
    # 2) an empty success says the data loaded
    r = pg.evaluate('PILOT.vicinity.deploy(57.5, -4.5, {radiusKm: 10}).then(x => ({st: x.repd.status, n: x.repd.model && x.repd.model.count}))')
    assert r == {'st': 'ok', 'n': 0}, r
    # 4) a delayed reply is a timeout, not an empty result
    pg.evaluate("""(() => { const o = PILOT.emit; PILOT.emit = function (n, d) { if (n === 'repd:query') { setTimeout(() => o.call(PILOT, n, d), 3000); return; } return o.apply(PILOT, arguments); }; })()""")
    r = pg.evaluate(f'PILOT.vicinity.deploy({lat}, {lon}, {{radiusKm: 10}}).then(x => x.repd.status)')
    assert r == 'timeout', r
    ctx.close()


def test_no_overlapping_controls_at_390(served, browser):
    """Fixed controls and HUD clusters do not sit on each other on a phone (canvas, reticle and toasts excluded)."""
    ctx, pg, errs, _ = _open(browser, served, 390, 844)
    bad = pg.evaluate('''(() => { const out = [];
      for (const e of document.querySelectorAll('body *')) { const s = getComputedStyle(e);
        if (!(s.position === 'fixed' || s.position === 'absolute') || s.display === 'none' || s.visibility === 'hidden') continue;
        if (e.id === 'pv' || e.classList.contains('reticle') || /toast/.test(e.className) || e.id === 'note') continue;
        const r = e.getBoundingClientRect(); if (r.width < 30 || r.height < 20) continue;
        if (out.some(o => o.el.contains(e))) continue;
        out.push({el: e, id: e.id || String(e.className), r}); }
      const res = [];
      for (let i = 0; i < out.length; i++) for (let j = i + 1; j < out.length; j++) { const a = out[i].r, c = out[j].r;
        const w = Math.min(a.right, c.right) - Math.max(a.left, c.left), h = Math.min(a.bottom, c.bottom) - Math.max(a.top, c.top);
        if (w > 4 && h > 4 && !out[i].el.contains(out[j].el) && !out[j].el.contains(out[i].el)) res.push(out[i].id + ' x ' + out[j].id); }
      return res; })()''')
    assert not bad, f'overlapping controls at 390x844: {bad}'
    ctx.close()


def test_repd_ranking_matches_gridatlas_order(served, browser):
    """GridAtlas rankRepdProjects: score, then name, then repd_ref (numeric); MW plays no part; limit 20."""
    ctx = browser.new_context(viewport={'width': 390, 'height': 844}); pg = ctx.new_page()
    pg.route('**/*', lambda r: r.continue_() if r.request.url.startswith('http://127.0.0.1') else r.abort())
    pg.goto(served + '?repdsrc=repd-fixture.json', wait_until='load'); pg.wait_for_timeout(600)
    if not pg.evaluate('!!(window.PILOT && PILOT.layer && PILOT.layer("repd"))'):
        ctx.close(); pytest.skip('repd module not shipped')
    refs = pg.evaluate('PILOT.layer("repd")._api.load().then(() => { const A = PILOT.layer("repd")._api; return A.search("Alpha Glen", 20, true).map(m => A.rec(m.i).repd_ref); })')
    assert refs == ['10', '30'], refs
    ctx.close()


def test_vicinity_substations_never_wait_for_optional_layers(served, browser):
    """CVAA grid-first critical path: substations show as soon as they are known, while REPD is still answering."""
    ctx = browser.new_context(viewport={'width': 390, 'height': 844}); pg = ctx.new_page()
    pg.route('**/*', lambda r: r.continue_() if r.request.url.startswith('http://127.0.0.1') else r.abort())
    pg.goto(served + '?repdsrc=repd-fixture.json', wait_until='load'); pg.wait_for_timeout(600)
    if not pg.evaluate('!!(window.PILOT && PILOT.vicinity)'):
        ctx.close(); pytest.skip('vicinity not shipped')
    pg.evaluate("""(() => { const o = PILOT.emit; PILOT.emit = function (n, d) { if (n === 'repd:query') { setTimeout(() => o.call(PILOT, n, d), 5000); return; } return o.apply(PILOT, arguments); }; })()""")
    lat, lon = ORIGIN
    pg.evaluate(f'void (window.__vd = PILOT.vicinity.deploy({lat}, {lon}, {{radiusKm: 10}}))')
    pg.wait_for_function('PILOT.vicinity.state().result && PILOT.vicinity.state().result.grid', timeout=1200)
    early = pg.evaluate('Object.keys(PILOT.vicinity.state().result)')
    assert 'grid' in early and 'repd' not in early, early
    assert pg.evaluate('window.__vd.then(x => x.repd.status)') == 'timeout'   # and the slow layer is reported, not zeroed
    ctx.close()