GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Automation and CI / globalgrid2050 / scripts/oracle

Compare and 3 more files

A JavaScript module in the oracle folder of GlobalGrid2050 that maps oracle, substations and the Renewable Energy Planning Database (REPD) register.

569 lines of Python and JavaScript from globalgrid2050, in 4 files. Topic: Automation and CI. Section 1772 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. Compare render · globalgrid2050 / scripts/oracle/compare.mjs lines 1–221
  2. GlobalGrid2050 Patch V4 Live Tracker Modular Structure storage · globalgrid2050 / scripts/patch_v4_live_tracker_modular_structure.py lines 1–112
  3. GlobalGrid2050 Patch V5 Chart Breathing Space render · globalgrid2050 / scripts/patch_v5_chart_breathing_space.py lines 1–120
  4. GlobalGrid2050 Patch V5 Chart Dynamic Annotations render · globalgrid2050 / scripts/patch_v5_chart_dynamic_annotations.py lines 1–116

Compare

A JavaScript module in the oracle folder of GlobalGrid2050 that maps oracle, substations and the Renewable Energy Planning Database (REPD) register.

renderglobalgrid2050 / scripts/oracle/compare.mjs · lines 1–221 of 221 · Entry point · pattern median (shared by 9 files)

What it does
It maps oracle, substations and the REPD register. Defines classifyRepdLookup, measure, median. Uses libraries playwright, node:fs, node:url, node:path. Side effects: changes the web page (DOM); reads or writes files; starts processes; uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain terms in the code: substations, the REPD register.
Inputs & outputs
In: JSON file oracle.json; DuckDB queries; command-line arguments. Out: interactive map.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Atlas Oracle Workflow (globalgrid2050).
What it achieves
It classifies REPD lookup (`classifyRepdLookup`) and is built from the measure step (`measure`) and the median step (`median`). Measure a candidate Atlas arrival against the ORACLE and refuse a regression.
Why it matters
Run by GlobalGrid2050 Atlas Oracle Workflow.
Application
globalgrid2050 · scripts/oracle · JavaScript module
Uses
playwright, node:fs, node:url, node:path
Used by
run by GlobalGrid2050 Atlas Oracle Workflow (workflow run)
Produces
classifyRepdLookup, measure, median
Defines here
classifyRepdLookup, measure, median
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 scripts/oracle/compare.mjs:1-221 · blob e6540d7b91c2d4bf22c04d1d7e3bc38ac011b6a2 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, process, storage · domain stage: unknown · users: none · canonical: production_core
/* Measure a candidate Atlas arrival against the ORACLE and refuse a regression.
 *
 * WHY AN ORACLE
 * -------------------------------------------------------------------------
 * "Smooth" is not a property anyone can review. testcode/202609051531 is the
 * arrival that measurably works, so it is pinned in oracle.json and every
 * candidate is compared against it on the axes where a candidate could be
 * worse. The oracle is a set of numbers, not an opinion about design.
 *
 * WHAT THIS DELIBERATELY DOES NOT DO
 * -------------------------------------------------------------------------
 * It does not check that a project name appears. An earlier harness did, and
 * reported 94 of 94 arrivals "firing" while the map was still being complained
 * about - because a rendered card proves the card was built and nothing else.
 * The engine has run when, and only when, the page states
 * "Nearest <n> kV substation:".
 *
 * It does not compare style-layer counts. The oracle and the live Atlas both
 * carry 194, and one renders 180 features while the other renders 62-74. A
 * count of what is DECLARED says nothing about what is DRAWN.
 *
 * It measures each lane several times and compares medians, because a single
 * sample over a real network is a number rather than a measurement.
 *
 *   node scripts/oracle/compare.mjs <candidate-url> [runs]
 *   node scripts/oracle/compare.mjs --remeasure-oracle [runs]
 *
 * Exit 1 on any rule broken, 0 when the candidate is no worse than the oracle.
 */
import { chromium, devices } from "playwright";
import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { dirname, join } from "node:path";

const HERE = dirname(fileURLToPath(import.meta.url));
const CONTRACT = JSON.parse(readFileSync(join(HERE, "oracle.json"), "utf8"));
const ENGINE_RE = "Nearest\\s+\\d+\\s*kV substation:";

const args = process.argv.slice(2);
const remeasure = args.includes("--remeasure-oracle");
const candidateUrl = remeasure ? CONTRACT.oracle.url : args.find((a) => !a.startsWith("-"));
const RUNS = Number(args.find((a) => /^\d+$/.test(a)) || 3);

if (!candidateUrl) {
  console.error("usage: node scripts/oracle/compare.mjs <candidate-url> [runs]");
  process.exit(2);
}

/* A REPD lookup is "sharded" when the arrival reads a small per-ref file, and
   "bulk" when it pulls a whole DATASET.
   The first version of this rule matched /duckdb/ and called the ORACLE bulk -
   the oracle loads duckdb-wasm from the CDN too. Loading a query LIBRARY is not
   the same act as fetching a dataset through it, and a rule that cannot tell
   them apart fails the very build it was written from. So this matches the
   data: parquet files, partitioned masters, and whole-register payloads. */
function classifyRepdLookup(paths) {
  const bulk = paths.filter((p) =>
    /\.parquet(\?|$)|\/partitions?\/|repd_projects_|repd_master/i.test(p));
  const sharded = paths.filter((p) => /repd-identit\w*\/\d+\.json/i.test(p));
  if (bulk.length) return { kind: "bulk", evidence: bulk.slice(0, 3) };
  if (sharded.length) return { kind: "sharded", evidence: sharded.slice(0, 3) };
  return { kind: "unknown", evidence: paths.slice(0, 4) };
}

async function measure(url, runs) {
  const browser = await chromium.launch({ headless: true });
  const samples = [];
  try {
    for (const lane of ["mobile", "desktop"]) {
      for (let i = 0; i < runs; i += 1) {
        const ctx = await browser.newContext(lane === "mobile"
          ? { ...devices["iPhone 14 Pro"] }
          : { viewport: { width: 1440, height: 900 } });
        const page = await ctx.newPage();
        let bytes = 0, requests = 0;
        const paths = new Set();
        page.on("response", (r) => {
          requests += 1;
          bytes += Number(r.headers()["content-length"] || 0);
          try { paths.add(new URL(r.url()).pathname); } catch { /* opaque */ }
        });
        const started = Date.now();
        const s = { lane };
        try {
          await page.goto(url, { waitUntil: "domcontentloaded", timeout: 60000 });
          try {
            await page.waitForFunction(
              (re) => new RegExp(re).test(document.body.innerText), ENGINE_RE, { timeout: 45000 });
            s.engine = "FIRED";
            s.engineMs = Date.now() - started;
          } catch {
            s.engine = "DID_NOT_FIRE";
          }
          await page.waitForTimeout(2500);
          Object.assign(s, await page.evaluate(() => {
            let m = null;
            for (const k of Object.keys(window)) {
              const v = window[k];
              if (v && typeof v === "object" && typeof v.getStyle === "function"
                  && typeof v.queryRenderedFeatures === "function") { m = v; break; }
            }
            const style = m ? m.getStyle() : null;
            const subs = style ? style.layers.find((l) => l.id === "l-subs") : null;
            return {
              styleLayers: style ? style.layers.length : null,
              renderedFeatures: m ? m.queryRenderedFeatures().length : null,
              subsVisible: subs ? ((subs.layout && subs.layout.visibility) || "visible") === "visible" : false,
            };
          }));
          s.requests = requests;
          s.declaredKB = Math.round(bytes / 1024);
          s.paths = [...paths];
        } catch (error) {
          s.engine = "ERROR";
          s.error = String(error).split("\n")[0].slice(0, 140);
        } finally { await ctx.close(); }
        samples.push(s);
      }
    }
  } finally { await browser.close(); }

  const median = (xs) => {
    const v = xs.filter(Number.isFinite).sort((a, b) => a - b);
    return v.length ? v[Math.floor(v.length / 2)] : null;
  };
  const lanes = {};
  for (const lane of ["mobile", "desktop"]) {
    const l = samples.filter((s) => s.lane === lane);
    const fired = l.filter((s) => s.engine === "FIRED");
    lanes[lane] = {
      runs: l.length,
      engine_fired: fired.length,
      engine_ms: median(fired.map((s) => s.engineMs)),
      requests: median(l.map((s) => s.requests)),
      declared_kb: median(l.map((s) => s.declaredKB)),
    };
  }
  const withMap = samples.find((s) => s.styleLayers != null) || {};
  const allPaths = [...new Set(samples.flatMap((s) => s.paths || []))];
  return {
    url,
    lanes,
    style_layers: withMap.styleLayers ?? null,
    rendered_features: withMap.renderedFeatures ?? null,
    l_subs_visible_on_arrival: withMap.subsVisible ?? false,
    repd_lookup: classifyRepdLookup(allPaths),
  };
}

const oracle = CONTRACT.baseline;
const R = CONTRACT.rules;
console.error(`measuring ${RUNS} run(s) per lane: ${candidateUrl}`);
const got = await measure(candidateUrl, RUNS);

const findings = [];
const note = [];

for (const lane of ["mobile", "desktop"]) {
  const c = got.lanes[lane];
  if (c.engine_fired !== c.runs) {
    findings.push(`${lane}: the grid engine fired on ${c.engine_fired} of ${c.runs} runs; the oracle fires on every one`);
  }
}

const kbLimit = Math.round(oracle.mobile.declared_kb * R.mobile_declared_kb.max_ratio_to_oracle);
if (got.lanes.mobile.declared_kb > kbLimit) {
  findings.push(
    `mobile payload ${got.lanes.mobile.declared_kb} KB exceeds ${kbLimit} KB `
    + `(oracle ${oracle.mobile.declared_kb} KB x ${R.mobile_declared_kb.max_ratio_to_oracle})`);
} else {
  note.push(`mobile payload ${got.lanes.mobile.declared_kb} KB within ${kbLimit} KB`);
}

for (const lane of ["mobile", "desktop"]) {
  const limit = Math.round(oracle[lane].engine_ms * R.engine_ms.max_ratio_to_oracle);
  const ms = got.lanes[lane].engine_ms;
  if (ms != null && ms > limit) {
    findings.push(`${lane}: engine answered in ${ms} ms, over the ${limit} ms allowed (oracle ${oracle[lane].engine_ms} ms)`);
  } else if (ms != null) {
    note.push(`${lane} engine ${ms} ms within ${limit} ms`);
  }
}

const featureFloor = Math.round(oracle.rendered_features * R.rendered_features.min_ratio_to_oracle);
if (got.rendered_features != null && got.rendered_features < featureFloor) {
  findings.push(
    `only ${got.rendered_features} features are drawn on arrival, under the floor of ${featureFloor} `
    + `(oracle draws ${oracle.rendered_features}). Both builds declare ${got.style_layers} style layers, `
    + `so a layer count would not have caught this.`);
} else if (got.rendered_features != null) {
  note.push(`${got.rendered_features} features drawn, at or above the floor of ${featureFloor}`);
}

if (R.l_subs_visible_on_arrival.required && !got.l_subs_visible_on_arrival) {
  findings.push("the substation layer is not visible on arrival, so the card measures to a network the map does not show");
} else {
  note.push("substations visible on arrival");
}

if (R.repd_lookup_is_sharded.required && got.repd_lookup.kind !== "sharded") {
  findings.push(
    `the REPD lookup is ${got.repd_lookup.kind}, not sharded: ${got.repd_lookup.evidence.join(", ")}. `
    + `The oracle reads one per-ref shard.`);
} else {
  note.push(`REPD lookup is ${got.repd_lookup.kind}`);
}

console.log(JSON.stringify({
  oracle: CONTRACT.oracle.release,
  candidate: got,
  passed: findings.length === 0,
  findings,
  within: note,
}, null, 2));

if (findings.length) {
  console.error(`\nORACLE COMPARISON FAILED - ${findings.length} finding(s):`);
  for (const f of findings) console.error("  - " + f);
  process.exit(1);
}
console.error("\nORACLE COMPARISON PASS - the candidate is no worse than " + CONTRACT.oracle.release);

GlobalGrid2050 Patch V4 Live Tracker Modular Structure

A Python command-line tool in the scripts folder that reads live grid energy.

storageglobalgrid2050 / scripts/patch_v4_live_tracker_modular_structure.py · lines 1–112 of 112 · Entry point · pattern between (shared by 12 files)

What it does
It loads live grid energy. Defines between, main. Uses libraries pathlib. Side effects: reads or writes files.
Inputs & outputs
In: JSON file live_grid_energy.json.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Patch V4 Live Tracker Modular Structure Workflow (globalgrid2050).
What it achieves
Defines `between`.
Why it matters
Run by GlobalGrid2050 Patch V4 Live Tracker Modular Structure Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
pathlib
Used by
run by GlobalGrid2050 Patch V4 Live Tracker Modular Structure Workflow (workflow run)
Produces
between, main
Defines here
between, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 scripts/patch_v4_live_tracker_modular_structure.py:1-112 · blob 0d9fcff37177cdde49523bfdc33d07e013b197fe · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem · domain stage: unknown · users: none · canonical: production_core
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
V3 = ROOT / "uk_energy_tracking_v3" / "index.md"
V4 = ROOT / "uk_energy_tracking_v4" / "index.md"
OUT = ROOT / "uk_energy_tracking_v4"
DIARY = OUT / "WORK_DIARY.md"
REPORT = ROOT / "gridbot_reports" / "v4_live_tracker_modular_structure.md"

START = "<script>\n(function(){\n  var ENERGY=\"/uk_energy_tracking_v4/live_grid_energy.json\""
END = "\n})();\n</script>"
TAGS = """<script src='/uk_energy_tracking_v4/live-config.js?v=20260526a'></script>
<script src='/uk_energy_tracking_v4/live-helpers.js?v=20260526a'></script>
<script src='/uk_energy_tracking_v4/live-gauges.js?v=20260526a'></script>
<script src='/uk_energy_tracking_v4/live-transport.js?v=20260526a'></script>
<script src='/uk_energy_tracking_v4/live-oil-chart.js?v=20260526a'></script>
<script src='/uk_energy_tracking_v4/live-app.js?v=20260526a'></script>"""


def between(text, a, b):
    x = text.find(a)
    if x < 0:
        raise SystemExit(f"marker not found: {a}")
    y = text.find(b, x)
    if y < 0:
        raise SystemExit(f"marker not found: {b}")
    return x, y


def main():
    v3 = V3.read_text(encoding="utf-8")
    if "/uk_energy_tracking_v3/live_grid_energy.json" not in v3:
        raise SystemExit("V3 benchmark marker missing")

    text = V4.read_text(encoding="utf-8")
    if "live-config.js" in text:
        print("V4 live tracker already modular")
        return

    start = text.find(START)
    if start < 0:
        raise SystemExit("V4 inline live tracker start not found")
    end = text.find(END, start)
    if end < 0:
        raise SystemExit("V4 inline live tracker end not found")
    end += len(END)

    block = text[start:end]
    body = block[len("<script>\n(function(){\n"):-len("\n})();\n</script>")]

    m1 = body.find("  function fmt(n,dp)")
    m2 = body.find("  function renderGauge(name,value)")
    m3 = body.find("  function renderCommodities(oil,fuel)")
    m4 = body.find("  var oilChartState")
    m5 = body.find("  function renderEvPrices(ev)")
    m6 = body.find("  function refresh()")
    if min(m1, m2, m3, m4, m5, m6) < 0:
        raise SystemExit("one or more split markers missing")

    modules = {
        "live-config.js": body[:m1],
        "live-helpers.js": body[m1:m2],
        "live-gauges.js": body[m2:m3],
        "live-transport.js": body[m3:m4] + "\n" + body[m5:m6],
        "live-oil-chart.js": body[m4:m5],
        "live-app.js": body[m6:],
    }

    headers = {
        "live-config.js": "// V4 live tracker config. Load first.\n",
        "live-helpers.js": "// V4 live tracker helpers. Depends on config.\n",
        "live-gauges.js": "// V4 live tracker gauges and generation mix rendering.\n",
        "live-transport.js": "// V4 live tracker commodity, road fuel and EV rendering.\n",
        "live-oil-chart.js": "// V4 live tracker oil history chart.\n",
        "live-app.js": "// V4 live tracker app boot and refresh loop. Load last.\n",
    }

    for name, content in modules.items():
        if "/uk_energy_tracking_v3/" in content:
            raise SystemExit(f"unexpected V3 reference in {name}")
        (OUT / name).write_text(headers[name] + content.strip() + "\n", encoding="utf-8")

    V4.write_text(text[:start] + TAGS + "\n" + text[end:], encoding="utf-8")

    REPORT.write_text("""# V4 live tracker modular structure

V4 live tracker JavaScript was split using the V3 tracker as benchmark and the solar BESS sandbox modular pattern as the structural model.

## Load order

```text
live-config.js
live-helpers.js
live-gauges.js
live-transport.js
live-oil-chart.js
live-app.js
```

V3 and the stable tracker were not modified.
""", encoding="utf-8")

    note = """\n\n## Diary entry: 2026-05-26 V4 live tracker modular structure\n\nV4 live tracker logic was split into config, helpers, gauges, transport, oil chart and app boot files. V3 was used only as the read only benchmark. The structure follows the adjacent sandbox modular pattern where index keeps page structure and external JavaScript files load in a deliberate dependency order.\n"""
    d = DIARY.read_text(encoding="utf-8")
    if "V4 live tracker modular structure" not in d:
        DIARY.write_text(d + note, encoding="utf-8")

    print("V4 live tracker modular structure patch complete")


if __name__ == "__main__":
    main()

GlobalGrid2050 Patch V5 Chart Breathing Space

A Python command-line tool in the scripts folder that replaces first (`replace_first`) and patches common units (`patch_common_units`) and fullscreen (`patch_fullscreen`).

renderglobalgrid2050 / scripts/patch_v5_chart_breathing_space.py · lines 1–120 of 120 · Entry point · pattern patch_ui (shared by 3 files)

What it does
It draws its content. Defines replace_first, patch_common_units, patch_ui, patch_fullscreen, main. Uses libraries pathlib, re. Side effects: changes the web page (DOM); reads or writes files.
Inputs & outputs
Out: canvas drawing.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Patch V5 Chart Overlap Controls Workflow (globalgrid2050).
What it achieves
Defines `replace_first`, `patch_common_units`, `patch_ui` and 1 more.
Why it matters
Run by GlobalGrid2050 Patch V5 Chart Overlap Controls Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
pathlib, re
Used by
run by GlobalGrid2050 Patch V5 Chart Overlap Controls Workflow (workflow run)
Produces
replace_first, patch_common_units, patch_ui, patch_fullscreen, main
Defines here
replace_first, patch_common_units, patch_ui, patch_fullscreen, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 scripts/patch_v5_chart_breathing_space.py:1-120 · blob e83d591ceb53be93308296cd27a93154544159f0 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: unknown · users: none · canonical: production_core
from pathlib import Path
import re

ROOT = Path(__file__).resolve().parents[1]
UI = ROOT / "uk_energy_tracking_v5" / "price-history-ui.js"
FS = ROOT / "uk_energy_tracking_v5" / "price-history-fullscreen.js"
INDEX = ROOT / "uk_energy_tracking_v5" / "index.md"
REPORT = ROOT / "gridbot_reports" / "patch_v5_chart_overlap_controls.md"


def replace_first(text, old, new):
    if old in text:
        return text.replace(old, new, 1)
    return text


def patch_common_units(text):
    text = text.replace("'£'+fmt(val,0)", "'£'+fmt(val,0)+'/MWh'")
    text = text.replace("'£'+fmt(val,0)+'/MWh'+'/MWh'", "'£'+fmt(val,0)+'/MWh'")
    text = text.replace("'£0'", "'£0/MWh'")
    text = text.replace("'£0/MWh/MWh'", "'£0/MWh'")
    text = text.replace("label+' £'+fmt(Number(r.priceGBPperMWh),2)", "label+' £'+fmt(Number(r.priceGBPperMWh),2)+'/MWh'")
    text = text.replace("label+' £'+fmt(Number(r.priceGBPperMWh),2)+'/MWh'+'/MWh'", "label+' £'+fmt(Number(r.priceGBPperMWh),2)+'/MWh'")
    text = text.replace("label+' '+price", "label+' '+price+'/MWh'")
    text = text.replace("label+' '+price+'/MWh'+'/MWh'", "label+' '+price+'/MWh'")
    return text


def patch_ui(text):
    text = text.replace("/uk_energy_tracking_v4/", "/uk_energy_tracking_v5/")
    text = text.replace("__v4PriceHistoryState", "__v5PriceHistoryState")
    text = text.replace("__v4PriceHistoryControls", "__v5PriceHistoryControls")
    text = text.replace("V4 captured Elexon Market Index Price", "V5 captured Elexon Market Index Price")
    text = text.replace("V4 Market Index audit", "V5 Market Index audit")

    if "function axisLabel(t,span)" not in text:
        text = replace_first(
            text,
            "function drawDateTick(g,x,y,t,q,align){g.textAlign=align||'center';g.fillStyle='#f5f7fb';g.font=12*q+'px Courier New';g.fillText(mlab(t),x,y);g.textAlign='left'}",
            "function axisLabel(t,span){var d=new Date(t);if(span<=45*86400000)return d.toLocaleDateString('en-GB',{day:'2-digit',month:'short'});return mlab(t)}\nfunction drawDateTick(g,x,y,t,q,align,span){g.textAlign=align||'center';g.fillStyle='#f5f7fb';g.font=11*q+'px Courier New';g.fillText(axisLabel(t,span||0),x,y);g.textAlign='left'}",
        )

    text = re.sub(
        r"var g=c\.getContext\('2d'\),w=c\.width,h=c\.height,pad=\{left:[^}]+\};",
        "var g=c.getContext('2d'),w=c.width,h=c.height,pad={left:86*q,right:32*q,top:46*q,bottom:136*q};",
        text,
        count=1,
    )

    text = text.replace("drawDateTick(g,x,h-34*q,ts,q", "drawDateTick(g,x,h-62*q,ts,q")
    text = text.replace("drawDateTick(g,x,h-30*q,ts,q", "drawDateTick(g,x,h-62*q,ts,q")
    text = text.replace("drawDateTick(g,x,h-46*q,ts,q", "drawDateTick(g,x,h-62*q,ts,q")

    text = text.replace("ly>g.canvas.height*.68", "ly>g.canvas.height*.58")
    text = text.replace("ly>g.canvas.height*.60", "ly>g.canvas.height*.58")
    text = text.replace("Math.min(g.canvas.height-44*q,y+48*q)", "Math.min(g.canvas.height-118*q,y+58*q)")
    text = text.replace("Math.min(g.canvas.height-70*q,y+38*q)", "Math.min(g.canvas.height-118*q,y+58*q)")
    text = text.replace("Math.min(g.canvas.height-100*q,y+38*q)", "Math.min(g.canvas.height-118*q,y+58*q)")
    text = text.replace("Math.max(42*q,y-34*q)", "Math.max(58*q,y-46*q)")
    text = text.replace("Math.max(50*q,y-38*q)", "Math.max(58*q,y-46*q)")

    text = text.replace(";drawEvents(g,rows,X,Y,q);g.fillStyle='#9aa3b6';g.font=11*q+'px Courier New';g.fillText(periodLabel(meta.period)+' | '+timeModeLabel()+' | '+rows.length+' pts',pad.left,h-12*q)", ";drawEvents(g,rows,X,Y,q)")
    text = patch_common_units(text)
    return text


def patch_fullscreen(text):
    text = text.replace("__v4PriceHistoryState", "__v5PriceHistoryState")
    text = text.replace("__v4PriceHistoryControls", "__v5PriceHistoryControls")
    text = text.replace("v4-", "v5-")

    if "s.textContent='" in text and "';\n document.head.appendChild" in text:
        start = text.index("s.textContent='") + len("s.textContent='")
        end = text.index("';\n document.head.appendChild", start)
        css = ".price-history-fullscreen-overlay.open{display:block!important}.price-history-fullscreen-overlay{position:fixed!important;inset:0!important;z-index:99999!important;background:#000!important;padding:0!important;overflow:hidden!important}.price-history-fullscreen-shell{position:fixed!important;inset:0!important;width:100vw!important;height:100dvh!important;border:0!important;border-ra  … [line shortened here: 1,999 characters; full line on GitHub]
        text = text[:start] + css + text[end:]

    if "function axisLabel(t,span)" not in text:
        text = replace_first(
            text,
            "function drawDateTick(g,x,y,t,q,align){g.textAlign=align||'center';g.fillStyle='#f5f7fb';g.font=11*q+'px Courier New';g.fillText(mlab(t),x,y);g.textAlign='left'}",
            "function axisLabel(t,span){var d=new Date(t);if(span<=45*86400000)return d.toLocaleDateString('en-GB',{day:'2-digit',month:'short'});return mlab(t)}\nfunction drawDateTick(g,x,y,t,q,align,span){g.textAlign=align||'center';g.fillStyle='#f5f7fb';g.font=10*q+'px Courier New';g.fillText(axisLabel(t,span||0),x,y);g.textAlign='left'}",
        )

    text = re.sub(
        r"var pad=\{left:\(isLandscape\?70:62\)\*q,right:\(isLandscape\?58:36\)\*q,top:[^}]+\};",
        "var pad={left:(isLandscape?70:62)*q,right:(isLandscape?58:36)*q,top:(isLandscape?58:76)*q,bottom:(isLandscape?58:76)*q};",
        text,
        count=1,
    )
    text = text.replace("ly>g.canvas.height*.68", "ly>g.canvas.height*.58")
    text = text.replace("ly>g.canvas.height*.60", "ly>g.canvas.height*.58")
    text = text.replace("Math.min(g.canvas.height-54*q,y+46*q)", "Math.min(g.canvas.height-110*q,y+58*q)")
    text = text.replace("Math.min(g.canvas.height-68*q,y+38*q)", "Math.min(g.canvas.height-110*q,y+58*q)")
    text = text.replace("Math.min(g.canvas.height-92*q,y+38*q)", "Math.min(g.canvas.height-110*q,y+58*q)")
    text = text.replace("Math.max(62*q,y-32*q)", "Math.max(64*q,y-46*q)")
    text = text.replace("Math.max(58*q,y-36*q)", "Math.max(64*q,y-46*q)")
    text = text.replace("var lab=$('fs-label');if(lab)lab.textContent='High and low price events labelled | '+modeText()+' | '+slab(meta.start)+' to '+slab(meta.end)", "var lab=$('fs-label');if(lab)lab.textContent=''")
    text = patch_common_units(text)
    return text


def main():
    UI.write_text(patch_ui(UI.read_text()))
    FS.write_text(patch_fullscreen(FS.read_text()))

    idx = INDEX.read_text()
    for old in ["20260527b", "20260527c", "20260527d", "20260527e"]:
        idx = idx.replace(f"price-history-ui.js?v={old}", "price-history-ui.js?v=20260527f")
        idx = idx.replace(f"price-history-fullscreen.js?v={old}", "price-history-fullscreen.js?v=20260527f")
    INDEX.write_text(idx)

    report = REPORT.read_text() if REPORT.exists() else "# V5 chart overlap and control placement patch\n"
    report += "\n## Idempotent units and spacing refinement\n\n"
    report += "Made the chart patch tolerant of already patched files. Added explicit £/MWh units to y axis and event labels, increased chart padding and moved full screen controls into chart corners. Cache keys updated to 20260527f.\n"
    REPORT.write_text(report)


if __name__ == "__main__":
    main()

GlobalGrid2050 Patch V5 Chart Dynamic Annotations

A Python command-line tool in the scripts folder that draws electricity price history.

renderglobalgrid2050 / scripts/patch_v5_chart_dynamic_annotations.py · lines 1–116 of 116 · Entry point · pattern patch_index (shared by 15 files)

What it does
It draws electricity price history. Defines patch_index, main. Uses libraries pathlib. Side effects: changes the web page (DOM); reads or writes files; makes network requests.
Inputs & outputs
In: JSON file electricity_price_history.json; form fields (user input). Out: canvas drawing.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Patch V5 Chart Dynamic Annotations Workflow (globalgrid2050).
What it achieves
Defines `patch_index`.
Why it matters
Run by GlobalGrid2050 Patch V5 Chart Dynamic Annotations Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
pathlib
Used by
run by GlobalGrid2050 Patch V5 Chart Dynamic Annotations Workflow (workflow run)
Produces
patch_index, main
Defines here
patch_index, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 scripts/patch_v5_chart_dynamic_annotations.py:1-116 · blob 3a18e2a0925c0eed043875f8d3a7641c7af5c36f · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, filesystem, network · domain stage: unknown · users: none · canonical: production_core
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
UI = ROOT / "uk_energy_tracking_v5" / "price-history-ui.js"
FS = ROOT / "uk_energy_tracking_v5" / "price-history-fullscreen.js"
INDEX = ROOT / "uk_energy_tracking_v5" / "index.md"
REPORT = ROOT / "gridbot_reports" / "patch_v5_chart_dynamic_annotations.md"

UI_CODE = r'''(function(){
var JSON_URL='/uk_energy_tracking_v5/electricity_price_history.json';
var ANNUAL_URL_BASE='/data/electricity/elexon_system_prices_';
var MAX_VISIBLE_ROWS=19000;
var FIRST_YEAR=2016;
var MIN_DATE=new Date(Date.UTC(FIRST_YEAR,0,1,0,0,0));
var TODAY=new Date();
var MAX_DATE=new Date(Date.UTC(TODAY.getUTCFullYear(),TODAY.getUTCMonth(),TODAY.getUTCDate(),23,59,59));
var ANNUAL_CACHE={};
var pendingTimer=null;
var STATE={all:[],visible:[],meta:null,loadedYears:[],sourceRows:0,timeMode:'all'};window.__v5PriceHistoryState=STATE;
function $(id){return document.getElementById(id)}
function fmt(n,d){return n==null||isNaN(n)?'—':Number(n).toLocaleString('en-GB',{minimumFractionDigits:d,maximumFractionDigits:d})}
function dlab(t){return new Date(t).toLocaleDateString('en-GB',{day:'2-digit',month:'long',year:'numeric'})}
function slab(t){return new Date(t).toLocaleDateString('en-GB',{day:'2-digit',month:'short',year:'numeric'})}
function tlab(t){return new Date(t).toLocaleTimeString('en-GB',{hour:'2-digit',minute:'2-digit'})}
function ymd(d){return d.toISOString().slice(0,10)}
function set(id,v){var e=$(id);if(e)e.textContent=v}
function timeModeLabel(){if(STATE.timeMode==='day')return 'Day 06 to 18 UTC';if(STATE.timeMode==='night')return 'Night 18 to 06 UTC';return 'All hours'}
function csvLine(l){var o=[],v='',q=false;for(var i=0;i<l.length;i++){var c=l[i];if(c==='"'){if(q&&l[i+1]==='"'){v+='"';i++}else q=!q}else if(c===','&&!q){o.push(v);v=''}else v+=c}o.push(v);return o}
function parseCsv(t){t=(t||'').trim();if(!t)return[];var lines=t.split(/\r?\n/),h=csvLine(lines[0]).map(function(x){return x.trim()});return lines.slice(1).map(function(line){var c=csvLine(line),r={};h.forEach(function(x,i){r[x]=(c[i]||'').trim()});var p=r.systemBuyPriceGBPperMWh||r.systemSellPriceGBPperMWh||r.priceGBPperMWh||'';return{source:r.source||'Elexon BMRS System Prices',priceTimeUTC:r.pe  … [line shortened here: 878 characters; full line on GitHub]
function loadJson(){return fetch(JSON_URL+'?t='+Date.now(),{cache:'no-store'}).then(function(r){return r.ok?r.json():{rows:[]}}).then(function(d){return d.rows||[]}).catch(function(){return[]})}
function yearsBetween(a,b){var y=[],s=a.getUTCFullYear(),e=b.getUTCFullYear();for(var n=s;n<=e;n++)y.push(n);return y}
function loadAnnual(year){if(ANNUAL_CACHE[year])return ANNUAL_CACHE[year];ANNUAL_CACHE[year]=fetch(ANNUAL_URL_BASE+year+'.csv?t='+Date.now(),{cache:'no-store'}).then(function(r){return r.ok?r.text():''}).then(parseCsv).catch(function(){return[]});return ANNUAL_CACHE[year]}
function norm(rows){var seen={};return(rows||[]).filter(function(r){return r.priceTimeUTC&&r.priceGBPperMWh!==''&&!isNaN(Number(r.priceGBPperMWh))}).map(function(r){var o=Object.assign({},r);o.priceGBPperMWh=Number(o.priceGBPperMWh);return o}).sort(function(a,b){return new Date(a.priceTimeUTC)-new Date(b.priceTimeUTC)}).filter(function(r){var k=r.priceTimeUTC+'|'+r.priceGBPperMWh+'|'+(r.source||''  … [line shortened here: 450 characters; full line on GitHub]
function merge(sys,cap){var rows=[];sys.forEach(function(r){rows.push(Object.assign({},r,{source:'Elexon BMRS System Prices',priceHealth:r.priceHealth||'historical system price'}))});cap.forEach(function(r){rows.push(Object.assign({},r,{source:r.source||'V5 captured Elexon Market Index Price'}))});return norm(rows)}
function periodDays(period){return {'7d':7,'30d':30,'3m':92,'6m':183,'12m':366}[period]||7}
function periodLabel(period){return {'7d':'1 week','30d':'1 month','3m':'3 months','6m':'6 months','12m':'12 months'}[period]||'1 week'}
function totalScrollableDays(){return Math.max(1,Math.floor((MAX_DATE-MIN_DATE)/86400000))}
function dateFromOffset(v){var d=new Date(MIN_DATE.getTime()+Number(v)*86400000);d.setUTCHours(0,0,0,0);return d}
function offsetFromDate(d){return Math.max(0,Math.min(totalScrollableDays(),Math.floor((d-MIN_DATE)/86400000)))}
function ensurePeriodOptions(){var p=$('price-history-period');if(!p)return;var wanted=[['7d','1 week'],['30d','1 month'],['3m','3 months'],['6m','6 months'],['12m','12 months']];var current=p.value||'7d';p.innerHTML='';wanted.forEach(function(x){var o=document.createElement('option');o.value=x[0];o.textContent=x[1];p.appendChild(o)});p.value=current&&wanted.some(function(x){return x[0]===current}  … [line shortened here: 415 characters; full line on GitHub]
function ensureModeTabs(){if($('price-history-time-tabs'))return;var actions=document.querySelector('#electricity-price-history-panel .price-history-actions');if(!actions)return;var tabs=document.createElement('div');tabs.id='price-history-time-tabs';tabs.className='price-history-time-tabs';tabs.innerHTML='<span>Hour filter</span><button type="button" data-mode="all" class="active">All</button><bu  … [line shortened here: 769 characters; full line on GitHub]
function ensureScroller(){if($('price-history-scroll'))return;var actions=document.querySelector('#electricity-price-history-panel .price-history-actions');if(!actions)return;var wrap=document.createElement('div');wrap.className='price-history-scroller';wrap.innerHTML='<div class="price-history-scroller-head"><strong>History scroller</strong><span id="price-history-scroll-label">2016 to present. O  … [line shortened here: 2,064 characters; full line on GitHub]
function ensureYearOptions(){var y=$('price-history-year');if(!y||y.options.length)return;var nowYear=MAX_DATE.getUTCFullYear();for(var n=nowYear;n>=FIRST_YEAR;n--){var o=document.createElement('option');o.value=String(n);o.textContent=String(n);y.appendChild(o)}y.value=String(nowYear)}
function ensureStartDate(){var y=$('price-history-year'),s=$('price-history-start');if(!s)return;var selectedYear=y&&y.value?Number(y.value):MAX_DATE.getUTCFullYear();if(!s.value||s.value.slice(0,4)!==String(selectedYear)){var start;if(selectedYear===MAX_DATE.getUTCFullYear()){start=new Date(MAX_DATE.getTime()-7*86400000)}else{start=new Date(Date.UTC(selectedYear,0,1,0,0,0))}s.value=ymd(start)}syn  … [line shortened here: 421 characters; full line on GitHub]
function syncScrollerFromStart(){var s=$('price-history-start'),r=$('price-history-scroll');if(!s||!r||!s.value)return;r.value=String(offsetFromDate(new Date(s.value+'T00:00:00Z')))}
function syncStartFromScroller(){var r=$('price-history-scroll'),s=$('price-history-start'),y=$('price-history-year');if(!r||!s)return;var d=dateFromOffset(r.value);s.value=ymd(d);if(y)y.value=String(d.getUTCFullYear())}
function selectedWindow(){ensureStartDate();var y=$('price-history-year'),s=$('price-history-start'),p=$('price-history-period');var year=y&&y.value?Number(y.value):MAX_DATE.getUTCFullYear();var period=p&&p.value?p.value:'7d';var start=s&&s.value?new Date(s.value+'T00:00:00Z'):new Date(Date.UTC(year,0,1,0,0,0));if(isNaN(start))start=new Date(Date.UTC(year,0,1,0,0,0));if(start<MIN_DATE)start=new Da  … [line shortened here: 791 characters; full line on GitHub]
function passesTimeMode(r){if(STATE.timeMode==='all')return true;var h=new Date(r.priceTimeUTC).getUTCHours();var day=h>=6&&h<18;return STATE.timeMode==='day'?day:!day}
function minMax(v){var lo=0,hi=0;v.forEach(function(x){if(x<lo)lo=x;if(x>hi)hi=x});if(lo===hi)hi=lo+1;var m=(hi-lo)*0.04;return{lo:lo-m,hi:hi+m}}
function niceStep(span){var raw=span/6,p=Math.pow(10,Math.floor(Math.log10(Math.max(raw,1)))),n=raw/p;if(n<=1)return p;if(n<=2)return 2*p;if(n<=5)return 5*p;return 10*p}
function axisLabel(t,span){var d=new Date(t);if(span<=45*86400000)return d.toLocaleDateString('en-GB',{day:'2-digit',month:'short',year:'numeric'});return d.toLocaleDateString('en-GB',{month:'short',year:'2-digit'})}
function drawDateTick(g,x,y,t,q,align,span){g.textAlign=align||'center';g.fillStyle='#f5f7fb';g.font=11*q+'px Courier New';g.fillText(axisLabel(t,span||0),x,y);g.textAlign='left'}
function drawAxes(g,w,h,q,m,t0,t1,pad){var step=niceStep(m.hi-m.lo),start=Math.ceil(m.lo/step)*step,span=t1-t0;g.lineWidth=q;g.font=11*q+'px Courier New';g.textAlign='left';for(var val=start;val<=m.hi+step*.5;val+=step){var yy=pad.top+((m.hi-val)/(m.hi-m.lo))*(h-pad.top-pad.bottom);g.strokeStyle=val===0?'rgba(255,51,51,.95)':'rgba(255,255,255,.18)';g.lineWidth=val===0?2*q:q;g.beginPath();g.moveTo(  … [line shortened here: 912 characters; full line on GitHub]
function eventPoints(rows){if(!rows.length)return null;var hi=rows[0],lo=rows[0];rows.forEach(function(r){if(Number(r.priceGBPperMWh)>Number(hi.priceGBPperMWh))hi=r;if(Number(r.priceGBPperMWh)<Number(lo.priceGBPperMWh))lo=r});return{hi:hi,lo:lo}}
function rectsOverlap(a,b){return !(a.x+a.w<b.x||b.x+b.w<a.x||a.y+a.h<b.y||b.y+b.h<a.y)}
function distRectPoint(r,p){var dx=Math.max(r.x-p.x,0,p.x-(r.x+r.w)),dy=Math.max(r.y-p.y,0,p.y-(r.y+r.h));return Math.sqrt(dx*dx+dy*dy)}
function chooseLabel(point,lines,boxes,w,h,pad,q){var bw=158*q,bh=44*q,off=20*q,c=[{x:point.x+off,y:point.y-bh-off},{x:point.x-bw-off,y:point.y-bh-off},{x:point.x+off,y:point.y+off},{x:point.x-bw-off,y:point.y+off},{x:point.x-bw/2,y:point.y-bh-32*q},{x:point.x-bw/2,y:point.y+32*q},{x:pad.left+10*q,y:pad.top+10*q},{x:w-pad.right-bw-10*q,y:pad.top+10*q},{x:pad.left+10*q,y:h-pad.bottom-bh-10*q},{x:w-  … [line shortened here: 931 characters; full line on GitHub]
function drawMarker(g,label,r,point,lines,boxes,w,h,pad,q){var box=chooseLabel(point,lines,boxes,w,h,pad,q),cx=box.x+box.w/2,cy=box.y+box.h/2;boxes.push(box);g.fillStyle='rgba(0,0,0,.72)';g.strokeStyle='rgba(255,51,51,.35)';g.lineWidth=q;g.beginPath();g.roundRect(box.x,box.y,box.w,box.h,5*q);g.fill();g.stroke();g.strokeStyle='#ff3333';g.fillStyle='#ff3333';g.lineWidth=1.5*q;g.beginPath();g.arc(poi  … [line shortened here: 748 characters; full line on GitHub]
function drawEvents(g,rows,X,Y,q,w,h,pad){var e=eventPoints(rows);if(!e)return;var linePts=rows.map(function(r){return{x:X(r),y:Y(Number(r.priceGBPperMWh))}}),boxes=[];drawMarker(g,'HIGH',e.hi,{x:X(e.hi),y:Y(Number(e.hi.priceGBPperMWh))},linePts,boxes,w,h,pad,q);drawMarker(g,'LOW',e.lo,{x:X(e.lo),y:Y(Number(e.lo.priceGBPperMWh))},linePts,boxes,w,h,pad,q)}
function draw(rows,meta){var c=$('price-history-canvas');if(!c)return;var q=devicePixelRatio||1,r=c.getBoundingClientRect();if(r.width){c.width=Math.max(320,Math.floor(r.width*q));c.height=Math.max(320,Math.floor((r.height||360)*q))}var g=c.getContext('2d'),w=c.width,h=c.height,pad={left:86*q,right:30*q,top:34*q,bottom:96*q};g.clearRect(0,0,w,h);g.fillStyle='#05070c';g.fillRect(0,0,w,h);var t0=met  … [line shortened here: 1,172 characters; full line on GitHub]
function status(meta,sourceRows,rows,years){var s=$('price-history-range-status');var lab=$('price-history-scroll-label');var text=dlab(meta.start)+' to '+dlab(meta.end)+' | '+timeModeLabel()+' | '+rows.length.toLocaleString('en-GB')+' price points | annual files '+(years.join(', ')||'none');if(s){s.textContent=text;s.className='price-history-range-status'}if(lab)lab.textContent='Scroller sets sta  … [line shortened here: 472 characters; full line on GitHub]
function table(rows,meta){var b=$('price-history-table-body');if(!b)return;if(!rows.length){b.innerHTML='<tr><td colspan="5">No records available.</td></tr>';return}b.innerHTML=rows.slice().reverse().map(function(r){return '<tr><td>'+dlab(r.priceTimeUTC)+' '+tlab(r.priceTimeUTC)+'</td><td>£'+fmt(Number(r.priceGBPperMWh),2)+'/MWh</td><td>'+(r.settlementPeriod||'—')+'</td><td>'+dlab(r.capturedAtUTC)  … [line shortened here: 486 characters; full line on GitHub]
function load(){ensurePeriodOptions();ensureModeTabs();ensureYearOptions();ensureScroller();var meta=selectedWindow(),years=yearsBetween(meta.start,meta.end);syncScrollerFromStart();Promise.all([loadJson()].concat(years.map(loadAnnual))).then(function(parts){var cap=parts[0],sys=[];parts.slice(1).forEach(function(a){sys=sys.concat(a)});var all=merge(norm(sys),norm(cap));var rows=all.filter(functio  … [line shortened here: 1,189 characters; full line on GitHub]
function deferredLoad(){clearTimeout(pendingTimer);pendingTimer=setTimeout(load,160)}
window.__v5PriceHistoryControls={load:load,deferredLoad:deferredLoad,periodDays:periodDays,totalScrollableDays:totalScrollableDays,dateFromOffset:dateFromOffset,offsetFromDate:offsetFromDate,syncStartFromScroller:syncStartFromScroller,setOffset:function(v){var r=$('price-history-scroll');if(r){r.value=v;syncStartFromScroller();load()}},setPeriod:function(v){var p=$('price-history-period');if(p){p.  … [line shortened here: 463 characters; full line on GitHub]
document.addEventListener('DOMContentLoaded',function(){ensurePeriodOptions();ensureModeTabs();ensureYearOptions();ensureScroller();ensureStartDate();var y=$('price-history-year'),p=$('price-history-period'),s=$('price-history-start'),cl=$('price-history-clear-start'),r=$('price-history-scroll'),prev=$('price-history-prev'),next=$('price-history-next');if(cl)cl.remove();if(y)y.addEventListener('ch  … [line shortened here: 1,276 characters; full line on GitHub]
})();
'''

FS_CODE = r'''(function(){
var S={rows:[],meta:null};
function $(id){return document.getElementById(id)}
function fmt(n,d){return Number(n).toLocaleString('en-GB',{minimumFractionDigits:d,maximumFractionDigits:d})}
function slab(t){return new Date(t).toLocaleDateString('en-GB',{day:'2-digit',month:'short',year:'numeric'})}
function tlab(t){return new Date(t).toLocaleTimeString('en-GB',{hour:'2-digit',minute:'2-digit'})}
function mm(v){var lo=0,hi=0;v.forEach(function(x){if(x<lo)lo=x;if(x>hi)hi=x});if(lo===hi)hi=lo+1;var m=(hi-lo)*0.04;return{lo:lo-m,hi:hi+m}}
function niceStep(span){var raw=span/7,p=Math.pow(10,Math.floor(Math.log10(Math.max(raw,1)))),n=raw/p;if(n<=1)return p;if(n<=2)return 2*p;if(n<=5)return 5*p;return 10*p}
function injectStyle(){if(document.getElementById('v5-fullscreen-graph-controls'))return;var s=document.createElement('style');s.id='v5-fullscreen-graph-controls';s.textContent='.price-history-fullscreen-overlay.open{display:block!important}.price-history-fullscreen-overlay{position:fixed!important;inset:0!important;z-index:99999!important;background:#000!important;padding:0!important;overflow:hid  … [line shortened here: 2,161 characters; full line on GitHub]
function ensureControls(){injectStyle();var o=$('price-history-fullscreen-overlay');if(!o||$('fs-mini'))return;var mini=document.createElement('div');mini.id='fs-mini';mini.className='fs-mini';mini.innerHTML='<button type="button" data-fs-mode="all" class="active">All</button><button type="button" data-fs-mode="day">Day</button><button type="button" data-fs-mode="night">Night</button><button type=  … [line shortened here: 1,226 characters; full line on GitHub]
function bindControls(){var c=window.__v5PriceHistoryControls;if(!c)return;var prev=$('fs-prev'),next=$('fs-next'),mini=$('fs-mini'),period=$('fs-period'),close2=$('fs-close2');if(close2)close2.onclick=close;if(prev)prev.addEventListener('click',function(){var st=window.__v5PriceHistoryState||{},days=c.periodDays((st.meta||{}).period||'7d'),v=c.offsetFromDate((st.meta||{}).start||new Date());c.set  … [line shortened here: 1,268 characters; full line on GitHub]
function modeText(){var st=window.__v5PriceHistoryState||{};var m=st.timeMode||'all';if(m==='day')return 'Day 06 to 18 UTC';if(m==='night')return 'Night 18 to 06 UTC';return 'All hours'}
function axisLabel(t,span){var d=new Date(t);if(span<=45*86400000)return d.toLocaleDateString('en-GB',{day:'2-digit',month:'short',year:'numeric'});return d.toLocaleDateString('en-GB',{month:'short',year:'2-digit'})}
function drawDateTick(g,x,y,t,q,align,span){g.textAlign=align||'center';g.fillStyle='#f5f7fb';g.font=10*q+'px Courier New';g.fillText(axisLabel(t,span||0),x,y);g.textAlign='left'}
function drawAxes(g,w,h,q,m,t0,t1,pad){var step=niceStep(m.hi-m.lo),start=Math.ceil(m.lo/step)*step,span=t1-t0;g.lineWidth=q;g.font=11*q+'px Courier New';g.textAlign='left';for(var val=start;val<=m.hi+step*.5;val+=step){var yy=pad.top+((m.hi-val)/(m.hi-m.lo))*(h-pad.top-pad.bottom);g.strokeStyle=val===0?'rgba(255,51,51,.98)':'rgba(255,255,255,.17)';g.lineWidth=val===0?2*q:q;g.beginPath();g.moveTo(  … [line shortened here: 910 characters; full line on GitHub]
function eventPoints(rows){if(!rows.length)return null;var hi=rows[0],lo=rows[0];rows.forEach(function(r){if(Number(r.priceGBPperMWh)>Number(hi.priceGBPperMWh))hi=r;if(Number(r.priceGBPperMWh)<Number(lo.priceGBPperMWh))lo=r});return{hi:hi,lo:lo}}
function rectsOverlap(a,b){return !(a.x+a.w<b.x||b.x+b.w<a.x||a.y+a.h<b.y||b.y+b.h<a.y)}
function distRectPoint(r,p){var dx=Math.max(r.x-p.x,0,p.x-(r.x+r.w)),dy=Math.max(r.y-p.y,0,p.y-(r.y+r.h));return Math.sqrt(dx*dx+dy*dy)}
function chooseLabel(point,lines,boxes,w,h,pad,q){var bw=158*q,bh=44*q,off=20*q,c=[{x:point.x+off,y:point.y-bh-off},{x:point.x-bw-off,y:point.y-bh-off},{x:point.x+off,y:point.y+off},{x:point.x-bw-off,y:point.y+off},{x:point.x-bw/2,y:point.y-bh-32*q},{x:point.x-bw/2,y:point.y+32*q},{x:pad.left+12*q,y:pad.top+12*q},{x:w-pad.right-bw-12*q,y:pad.top+12*q},{x:pad.left+12*q,y:h-pad.bottom-bh-12*q},{x:w-  … [line shortened here: 931 characters; full line on GitHub]
function marker(g,label,r,point,lines,boxes,w,h,pad,q){var box=chooseLabel(point,lines,boxes,w,h,pad,q),cx=box.x+box.w/2,cy=box.y+box.h/2;boxes.push(box);g.fillStyle='rgba(0,0,0,.72)';g.strokeStyle='rgba(255,51,51,.35)';g.lineWidth=q;g.beginPath();g.roundRect(box.x,box.y,box.w,box.h,5*q);g.fill();g.stroke();g.fillStyle='#ff3333';g.strokeStyle='#ff3333';g.lineWidth=1.5*q;g.beginPath();g.arc(point.x  … [line shortened here: 744 characters; full line on GitHub]
function drawEvents(g,rows,X,Y,q,w,h,pad){var e=eventPoints(rows);if(!e)return;var pts=rows.map(function(r){return{x:X(r),y:Y(Number(r.priceGBPperMWh))}}),boxes=[];marker(g,'HIGH',e.hi,{x:X(e.hi),y:Y(Number(e.hi.priceGBPperMWh))},pts,boxes,w,h,pad,q);marker(g,'LOW',e.lo,{x:X(e.lo),y:Y(Number(e.lo.priceGBPperMWh))},pts,boxes,w,h,pad,q)}
function draw(){var c=$('price-history-fullscreen-canvas');if(!c)return;var q=devicePixelRatio||1,cssW=window.innerWidth,cssH=window.innerHeight;c.width=Math.max(320,Math.floor(cssW*q));c.height=Math.max(320,Math.floor(cssH*q));var g=c.getContext('2d'),w=c.width,h=c.height,isLandscape=w>h;var pad={left:(isLandscape?86:86)*q,right:(isLandscape?46:30)*q,top:(isLandscape?66:122)*q,bottom:(isLandscape  … [line shortened here: 1,652 characters; full line on GitHub]
function syncFs(){var st=window.__v5PriceHistoryState||{},mini=$('fs-mini'),period=$('fs-period');if(mini){mini.querySelectorAll('button[data-fs-mode]').forEach(function(b){b.classList.toggle('active',b.getAttribute('data-fs-mode')===(st.timeMode||'all'))})}if(period){period.querySelectorAll('button[data-fs-period]').forEach(function(b){b.classList.toggle('active',b.getAttribute('data-fs-period')=  … [line shortened here: 435 characters; full line on GitHub]
function open(){ensureControls();var o=$('price-history-fullscreen-overlay'),st=window.__v5PriceHistoryState;if(!o)return;document.documentElement.classList.add('v5-chart-open');document.body.classList.add('v5-chart-open');o.classList.add('open');S.rows=(st&&st.visible)||[];S.meta=(st&&st.meta)||null;setTimeout(draw,40)}
function close(){var o=$('price-history-fullscreen-overlay');if(o)o.classList.remove('open');document.documentElement.classList.remove('v5-chart-open');document.body.classList.remove('v5-chart-open')}
document.addEventListener('DOMContentLoaded',function(){injectStyle();var b=$('price-history-fullscreen-btn'),c=$('price-history-fullscreen-close');if(b)b.onclick=open;if(c)c.onclick=close;document.addEventListener('keydown',function(e){if(e.key==='Escape')close()});window.addEventListener('resize',function(){if($('price-history-fullscreen-overlay')&&$('price-history-fullscreen-overlay').classList  … [line shortened here: 429 characters; full line on GitHub]
})();
'''


def patch_index(text):
    text = text.replace('<button type="button" id="price-history-clear-start" class="price-history-date-apply">Reset start</button>', '')
    for old in ['20260527b','20260527c','20260527d','20260527e','20260527f']:
        text = text.replace(f'price-history-ui.js?v={old}', 'price-history-ui.js?v=20260527g')
        text = text.replace(f'price-history-fullscreen.js?v={old}', 'price-history-fullscreen.js?v=20260527g')
    return text


def main():
    UI.write_text(UI_CODE)
    FS.write_text(FS_CODE)
    INDEX.write_text(patch_index(INDEX.read_text()))
    REPORT.parent.mkdir(parents=True, exist_ok=True)
    REPORT.write_text('# V5 dynamic chart annotation patch\n\nRebuilt V5 price chart interaction layer with dynamic HIGH and LOW label placement, black backing boxes, explicit £/MWh units, full year date labels, price point counts, fullscreen period controls, bottom centre fullscreen arrows and removal of Reset start.\n')

if __name__ == '__main__':
    main()