GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Grid network and substations / globalgrid2050 / scripts

GlobalGrid2050 Gridbot Generation Interconnector Split and 1 more file (part 1)

A Python command-line tool in the scripts folder that parses time (`parse_time`) and float (`parse_float`) and scans signed repo rows (`scan_signed_repo_rows`) (units: MWh, MW), using SHA-256.

700 lines of Python from globalgrid2050, in 2 files. Topic: Grid network and substations. Section 333 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. GlobalGrid2050 Generate GIS Single-Line Diagram (SLD) Full Code Reports electrical · globalgrid2050 / scripts/generate_gis_sld_full_code_reports.py lines 1–229
  2. GlobalGrid2050 Gridbot Generation Interconnector Split energy-data · globalgrid2050 / scripts/gridbot_generation_interconnector_split.py lines 1–471

GlobalGrid2050 Generate GIS Single-Line Diagram (SLD) Full Code Reports

A Python command-line tool in the scripts folder that reads battery storage (BESS) and solar. It sorts key (`sort_key`), reads text (`read_text`) and makes tree (`make_tree`).

electricalglobalgrid2050 / scripts/generate_gis_sld_full_code_reports.py · lines 1–229 of 229 · Entry point · pattern make_report (shared by 3 files)

What it does
It loads battery storage (BESS) and solar. Defines 8 functions or classes, including should_include, sort_key, iter_source_files, read_text, fence_lang. Uses libraries __future__, datetime, pathlib, typing. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'sld'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: battery storage (BESS), solar.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Generate GIS Single-Line Diagram (SLD) Full Code Reports Workflow (globalgrid2050).
What it achieves
Generate full code reports for V7 and V8 GIS SLD apps.
Why it matters
Run by GlobalGrid2050 Generate GIS Single-Line Diagram (SLD) Full Code Reports Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
__future__, datetime, pathlib, typing
Used by
run by GlobalGrid2050 Generate GIS Single-Line Diagram (SLD) Full Code Reports Workflow (workflow run)
Produces
should_include, sort_key, iter_source_files, read_text, fence_lang, make_tree, make_report, main
Defines here
should_include, sort_key, iter_source_files, read_text, fence_lang, make_tree, make_report, 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/generate_gis_sld_full_code_reports.py:1-229 · blob f75617521075d409414e18b41c151beb7ca83076 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
"""Generate full code reports for V7 and V8 GIS SLD apps.

Purpose:
- Produce one Markdown analysis file inside the V7 GIS SLD folder.
- Produce one Markdown analysis file inside the V8 BESS GIS SLD folder.
- Include the full source code of the local app files in a deterministic order.
- Help future AI, LLM and GridBot sessions read the complete app context before making small controlled module changes.

These reports are analysis artefacts only. They are not linked from the public homepage.
"""

from __future__ import annotations

import datetime as dt
from pathlib import Path
from typing import Iterable

ROOT = Path(__file__).resolve().parents[1]

APPS = [
    {
        "name": "V7 GIS SLD Financial Sandbox",
        "version": "V7",
        "folder": ROOT / "solar-bess-topology-v7" / "gis-sld-financial-sandbox",
        "output": "GIS_SLD_FULL_CODE_REPORT_V7.md",
        "summary": "Working V7 Solar BESS GIS SLD Financial Sandbox reference frame.",
    },
    {
        "name": "V8 BESS GIS SLD Financial Sandbox",
        "version": "V8",
        "folder": ROOT / "solar-bess-topology-v8" / "bess-gis-sld-financial-sandbox",
        "output": "GIS_SLD_FULL_CODE_REPORT_V8.md",
        "summary": "V8 standalone BESS GIS SLD development frame.",
    },
]

REPORT = ROOT / "gridbot_reports" / "generate_gis_sld_full_code_reports.md"

ALLOWED_SUFFIXES = {
    ".html",
    ".css",
    ".js",
    ".md",
    ".json",
    ".geojson",
    ".yml",
    ".yaml",
    ".txt",
}

EXCLUDE_NAMES = {
    "GIS_SLD_FULL_CODE_REPORT_V7.md",
    "GIS_SLD_FULL_CODE_REPORT_V8.md",
    "CODEBASE_BLUEPRINT.md",
}

EXCLUDE_PARTS = {
    ".git",
    "node_modules",
    "__pycache__",
    ".DS_Store",
}

LANG_BY_SUFFIX = {
    ".html": "html",
    ".css": "css",
    ".js": "javascript",
    ".json": "json",
    ".geojson": "json",
    ".yml": "yaml",
    ".yaml": "yaml",
    ".md": "markdown",
    ".txt": "text",
}


def should_include(path: Path) -> bool:
    if path.name in EXCLUDE_NAMES:
        return False
    if any(part in EXCLUDE_PARTS for part in path.parts):
        return False
    if not path.is_file():
        return False
    return path.suffix.lower() in ALLOWED_SUFFIXES


def sort_key(path: Path) -> tuple[int, str]:
    order = {
        "README.md": 0,
        "index.html": 1,
        "gis-sld-v5-config.js": 2,
        "gis-sld-v5-helpers.js": 3,
        "gis-sld-v5-state.js": 4,
        "gis-sld-v5-substations.js": 5,
        "gis-sld-v5-map.js": 6,
        "gis-sld-v5-calculations.js": 7,
        "gis-sld-v5-finance.js": 8,
        "gis-sld-v5-ui-core.js": 9,
        "gis-sld-v5-drawing.js": 10,
        "gis-sld-v5-export.js": 11,
        "gis-sld-v5-ui.js": 12,
        "gis-sld-v5.css": 13,
    }
    return (order.get(path.name, 100), str(path).lower())


def iter_source_files(folder: Path) -> list[Path]:
    if not folder.exists():
        raise FileNotFoundError(f"Missing folder: {folder}")
    files = [path for path in folder.rglob("*") if should_include(path)]
    return sorted(files, key=sort_key)


def read_text(path: Path) -> str:
    return path.read_text(encoding="utf-8", errors="replace")


def fence_lang(path: Path) -> str:
    return LANG_BY_SUFFIX.get(path.suffix.lower(), "text")


def make_tree(folder: Path, files: Iterable[Path]) -> str:
    lines = []
    for file in files:
        rel = file.relative_to(folder)
        lines.append(str(rel))
    return "\n".join(lines)


def make_report(app: dict[str, object]) -> tuple[Path, int, int]:
    folder = app["folder"]
    assert isinstance(folder, Path)
    files = iter_source_files(folder)
    output_path = folder / str(app["output"])
    now = dt.datetime.now(dt.timezone.utc).isoformat()

    chunks: list[str] = []
    chunks.append(f"# {app['name']} Full Code Report")
    chunks.append("")
    chunks.append(f"Generated UTC: {now}")
    chunks.append("")
    chunks.append("## Purpose")
    chunks.append("")
    chunks.append(str(app["summary"]))
    chunks.append("")
    chunks.append("This file is an AI and GridBot analysis artefact. Read it before modifying this GIS SLD app. It is not linked from the public homepage and should be treated as an internal development reference in the public repository.")
    chunks.append("")
    chunks.append("## Read first")
    chunks.append("")
    chunks.append("Future AI, LLM and GridBot workflows should read this report before editing this app. Changes should then be made in small controlled steps, preferably 1 module at a time, with a dedicated script, test and workflow.")
    chunks.append("")
    chunks.append("## Scope boundary")
    chunks.append("")
    if app["version"] == "V8":
        chunks.append("V8 is the standalone BESS development frame. It should not destabilise V7. Cable sizing, R, X, Z impedance, leakage, reverse current and protection coordination should remain in the advanced topology review unless deliberately promoted in a controlled future feature.")
    else:
        chunks.append("V7 is the working GIS SLD reference frame. Treat it as the stable baseline. Do not make broad replacements. Study V7 first, then port small proven behaviours into V8.")
    chunks.append("")
    chunks.append("## File inventory")
    chunks.append("")
    chunks.append("```text")
    chunks.append(make_tree(folder, files))
    chunks.append("```")
    chunks.append("")
    chunks.append("## Full source code")
    chunks.append("")

    total_lines = 0
    for file in files:
        rel = file.relative_to(folder)
        text = read_text(file)
        line_count = len(text.splitlines())
        total_lines += line_count
        chunks.append(f"### `{rel}`")
        chunks.append("")
        chunks.append(f"Lines: {line_count}")
        chunks.append("")
        chunks.append(f"```{fence_lang(file)}")
        chunks.append(text.rstrip())
        chunks.append("```")
        chunks.append("")

    output_path.write_text("\n".join(chunks), encoding="utf-8")
    return output_path, len(files), total_lines


def main() -> int:
    results = []
    for app in APPS:
        output_path, file_count, line_count = make_report(app)
        results.append((app["version"], output_path, file_count, line_count))

    REPORT.parent.mkdir(parents=True, exist_ok=True)
    now = dt.datetime.now(dt.timezone.utc).isoformat()
    report_lines = [
        "# Generate GIS SLD Full Code Reports",
        "",
        f"Generated UTC: {now}",
        "",
        "## Outputs",
        "",
    ]
    for version, output_path, file_count, line_count in results:
        report_lines.extend([
            f"### {version}",
            "",
            "```text",
            str(output_path.relative_to(ROOT)),
            "```",
            "",
            f"Files included: {file_count}",
            "",
            f"Source lines included: {line_count}",
            "",
        ])
    report_lines.extend([
        "## Notes",
        "",
        "The files are Markdown analysis reports for future AI and GridBot work. They are not linked from the public homepage.",
        "",
    ])
    REPORT.write_text("\n".join(report_lines), encoding="utf-8")
    print("Generated GIS SLD full code reports.")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())

GlobalGrid2050 Gridbot Generation Interconnector Split

A Python command-line tool in the scripts folder that parses time (`parse_time`) and float (`parse_float`) and scans signed repo rows (`scan_signed_repo_rows`) (units: MWh, MW), using SHA-256.

energy-dataglobalgrid2050 / scripts/gridbot_generation_interconnector_split.py · lines 1–471 of 781 · Entry point · pattern infer_interval_hours (shared by 2 files)

What it does
It draws generation annual mwh by technology, generation monthly mwh by technology, generation seasonal mwh by technology and generation day night mwh by technology. Defines 28 functions or classes, including utcnow, rel, read, write, sha. Uses libraries __future__, argparse, csv, datetime, hashlib. Side effects: changes the web page (DOM); reads or writes files; makes network requests; starts processes.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'generation'): 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: JSON file generation_annual_mwh_by_technology.json; JSON file generation_monthly_mwh_by_technology.json; JSON file generation_seasonal_mwh_by_technology.json; JSON file generation_day_night_mwh_by_technology.json; JSON file generation_interconnector_index.json; JSON file generation_interconnector_total_electricity_summary.json; JSON file GENERATION_INTERCONNECTOR_SPLIT_LATEST.json; JSON file _imports.json.
Downstream impact
Used directly by 2 files: GlobalGrid2050 Gridbot Generation Interconnector Split Workflow (globalgrid2050); GlobalGrid2050 Gridbot Generation Interconnector Split V2 Workflow (globalgrid2050).
What it achieves
It is built from the utcnow step (`utcnow`), the rel step (`rel`) and the read step (`read`). `/uk_energy_tracking_v6/generation_history/`. It accepts `--start-year`, `--end-year` and `--apply`.
Why it matters
Run by GlobalGrid2050 Gridbot Generation Interconnector Split Workflow and GlobalGrid2050 Gridbot Generation Interconnector Split V2 Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
__future__, argparse, csv, datetime, hashlib, json, math, re
Used by
run by GlobalGrid2050 Gridbot Generation Interconnector Split Workflow (workflow run), run by GlobalGrid2050 Gridbot Generation Interconnector Split V2 Workflow (workflow run)
Produces
utcnow, rel, read, write, sha, git, existing_rows, source_files, parse_time, parse_float, infer_interval_hours, scan_signed_repo_rows
Defines here
utcnow, rel, read, write, sha, git, existing_rows, source_files, parse_time, parse_float, infer_interval_hours, scan_signed_repo_rows, build_flows, flow_file_payload, planned_data_files
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/gridbot_generation_interconnector_split.py:1-471 · blob e7e3c2cce017e67e348bcdf48d40846f8cd21d4f · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
"""
GridBot Generation Interconnector Split — granular V6.

Live target:
  /uk_energy_tracking_v6/generation_history/

Audit/apply contract:
  - Audit mode scans signed raw-code interconnector rows already present in the repository,
    builds all proposed compact outputs in memory, and writes reports only.
  - Apply mode writes only audited UI files, compact interconnector JSON outputs and reports.
  - No raw input files are written.
  - Existing generation aggregate JSON files are not modified.

Why repo raw signed rows first?
  The deep research identified a trap: generic FUELINST/FUELHH generation feeds can lose or cap
  export polarity depending on endpoint/reporting path. The repo still contains raw-ish signed
  `elexon_generation_sources_*.csv` rows with specific INT* fuelType values. This script refuses
  to pass unless signed import and export rows are detected.

Output contract:
  - Two files per interconnector:
      interconnectors/<country>_<interconnector>_<bmrs>_imports.json
      interconnectors/<country>_<interconnector>_<bmrs>_exports.json
  - Imports are positive MWh.
  - Exports are negative MWh.
  - A compact index/summary file drives the browser.
  - Labels are: country first, interconnector name second, BMRS code third.
"""

from __future__ import annotations

import argparse
import csv
import datetime as dt
import hashlib
import json
import math
import re
import subprocess
import tempfile
from collections import defaultdict
from pathlib import Path
from typing import Any

ROOT = Path(__file__).resolve().parent.parent
APP = ROOT / "uk_energy_tracking_v6" / "generation_history"

INDEX = APP / "index.md"
LOAD = APP / "load_generation_mwh_aggregates.js"
RENDER = APP / "render_generation_mwh_aggregates.js"
CONTROL = APP / "control_generation_mwh_aggregates.js"

EXISTING_ANNUAL = APP / "generation_annual_mwh_by_technology.json"
EXISTING_MONTHLY = APP / "generation_monthly_mwh_by_technology.json"
EXISTING_SEASONAL = APP / "generation_seasonal_mwh_by_technology.json"
EXISTING_DAY_NIGHT = APP / "generation_day_night_mwh_by_technology.json"

OUT_DIR = APP / "interconnectors"
OUT_INDEX = OUT_DIR / "generation_interconnector_index.json"
OUT_TOTALS = OUT_DIR / "generation_interconnector_total_electricity_summary.json"

REPORT_DIR = ROOT / "data_science_protocol" / "audit_reports"
REPORT_JSON_DIR = REPORT_DIR / "json"
REPORT_MD = REPORT_DIR / "GENERATION_INTERCONNECTOR_SPLIT_LATEST.md"
REPORT_JSON = REPORT_JSON_DIR / "GENERATION_INTERCONNECTOR_SPLIT_LATEST.json"

SOURCE_ROOTS = [
    ROOT / "data" / "generation",
    ROOT / "data" / "generation" / "archive",
]

ROUTE = "/uk_energy_tracking_v6/generation_history/"
CACHE = "20260613interconnectorsgranular1"
LEGACY_BUCKET = "Imports & Exports"
SCRIPT_NAME = "scripts/gridbot_generation_interconnector_split.py"
WORKFLOW_NAME = "GridBot Generation Interconnector Split"
REPORT_TITLE = "Generation Interconnector Split"

# Country first, interconnector name second, BMRS code third.
LINKS = [
    ("France", "IFA / HVDC Cross-Channel", "INTFR", 1986),
    ("France", "IFA2", "INTIFA2", 2021),
    ("France", "ElecLink", "INTELEC", 2022),
    ("Belgium", "Nemo Link", "INTNEM", 2019),
    ("Netherlands", "BritNed", "INTNED", 2011),
    ("Norway", "North Sea Link", "INTNSL", 2021),
    ("Denmark", "Viking Link", "INTVKL", 2023),
    ("Ireland", "East-West Interconnector / EWIC", "INTEW", 2013),
    ("Ireland", "Greenlink", "INTGRNL", 2025),
    ("Northern Ireland", "Moyle Interconnector", "INTIRL", 2002),
]
CODE_META = {
    code: {
        "country": country,
        "interconnector": name,
        "bmrsCode": code,
        "commissioningYear": year,
        "label": f"{country} - {name} - {code}",
        "sortOrder": idx,
        "slug": re.sub(r"[^a-z0-9]+", "_", f"{country}_{name}_{code}".lower()).strip("_"),
    }
    for idx, (country, name, code, year) in enumerate(LINKS)
}
CODES = set(CODE_META)

LOAD_JS = """window.V6LoadGenerationMwhAggregates=(function(){
  var cache={};
  function f(k,u){
    if(cache[k])return cache[k];
    cache[k]=fetch(u+'?t='+Date.now(),{cache:'no-store'}).then(function(r){return r.ok?r.json():{rows:[]}}).then(function(d){return d.rows||[]}).catch(function(){return[]});
    return cache[k];
  }
  return{
    annual:function(){return f('annual','/uk_energy_tracking_v6/generation_history/generation_annual_mwh_by_technology.json')},
    monthly:function(){return f('monthly','/uk_energy_tracking_v6/generation_history/generation_monthly_mwh_by_technology.json')},
    seasonal:function(){return f('seasonal','/uk_energy_tracking_v6/generation_history/generation_seasonal_mwh_by_technology.json')},
    dayNight:function(){return f('daynight','/uk_energy_tracking_v6/generation_history/generation_day_night_mwh_by_technology.json')},
    interconnectorIndex:function(){return f('icIndex','/uk_energy_tracking_v6/generation_history/interconnectors/generation_interconnector_index.json')},
    interconnectorTotals:function(){return f('icTotals','/uk_energy_tracking_v6/generation_history/interconnectors/generation_interconnector_total_electricity_summary.json')}
  };
})();
"""

RENDER_JS = """window.V6RenderGenerationMwhAggregates=(function(){
  var colours={Solar:'#f5c518',Wind:'#00d0ff',Hydro:'#0090c0',Gas:'#c0399a',Coal:'#888888',Biomass:'#f59e2b',Nuclear:'#5cb85c','Pumped Storage':'#9b59b6',Other:'#a6adbb'};
  var hide={'Imports & Exports':1};
  var ord={Solar:10,Wind:20,Gas:30,Nuclear:40,Biomass:50,Hydro:60,'Pumped Storage':70,Coal:80,Other:90};
  function fmt(n,d){return n==null||isNaN(Number(n))?'--':Number(n).toLocaleString('en-GB',{minimumFractionDigits:d,maximumFractionDigits:d})}
  function clean(rows){return(rows||[]).filter(function(r){return r&&!hide[r.technology]})}
  function latestYear(rows,extraRows){var ys=[];(rows||[]).forEach(function(r){ys.push(Number(r.year)||0)});(extraRows||[]).forEach(function(r){ys.push(Number(r.year)||0)});return Math.max.apply(null,ys)}
  function annual(el,rows,icIndex,totals){
    if(!el)return;
    rows=rows||[]; icIndex=icIndex||[]; totals=totals||[];
    if(!rows.length){el.innerHTML='<div class="mwh-empty">Awaiting annual MWh aggregate data.</div>';return}
    var y=latestYear(rows,icIndex);
    var rs=clean(rows.filter(function(r){return Number(r.year)===y})).sort(function(a,b){return(ord[a.technology]||999)-(ord[b.technology]||999)});
    var generationTotal=rs.reduce(function(s,r){return s+Math.max(0,Number(r.totalMWh||0))},0);
    var h='<div class="mwh-aggregate-head"><strong>Annual MWh by technology</strong><span>'+y+' - generation shown; interconnectors split below</span></div><div class="mwh-bars">';
    rs.forEach(function(r){
      var v=Number(r.totalMWh||0),p=generationTotal?Math.max(0,v)/generationTotal*100:0,c=colours[r.technology]||'#00ffff';
      h+='<div class="mwh-row"><div class="mwh-label">'+r.technology+'</div><div class="mwh-track"><i style="width:'+p+'%;background:'+c+'"></i></div><div class="mwh-value">'+fmt(v/1000000,2)+' TWh</div></div>';
    });
    h+='</div>';

    var links=(icIndex||[]).filter(function(r){return Number(r.year)===y}).sort(function(a,b){return(Number(a.sortOrder)||0)-(Number(b.sortOrder)||0)});
    if(links.length){
      var maxAbs=Math.max.apply(null,links.map(function(r){return Math.max(Math.abs(Number(r.importMWh||0)),Math.abs(Number(r.exportMWh||0)),Math.abs(Number(r.netMWh||0)))}));
      h+='<div class="mwh-aggregate-head" style="margin-top:16px"><strong>Interconnectors - imports / exports</strong><span>Country - interconnector - BMRS code</span></div><div class="mwh-bars mwh-interconnector-bars">';
      links.forEach(function(r){
        var imp=Number(r.importMWh||0), exp=Number(r.exportMWh||0), net=Number(r.netMWh||0);
        var p=maxAbs?Math.max(2,Math.abs(net)/maxAbs*100):2, c=net>=0?'#00d0ff':'#ff7777';
        h+='<div class="mwh-row mwh-interconnector-row"><div class="mwh-label" title="'+r.label+'">'+r.label+'</div><div class="mwh-track"><i style="width:'+p+'%;background:'+c+'"></i></div><div class="mwh-value">I '+fmt(imp/1000000,2)+' / E '+fmt(exp/1000000,2)+' / N '+fmt(net/1000000,2)+' TWh</div></div>';
      });
      h+='</div><div class="mwh-note-line">Imports are positive. Exports are negative. Separate per-link import/export JSON files are written under /interconnectors/.</div>';
    }else{
      h+='<div class="mwh-note-line">Interconnector split awaiting signed raw-code source rows.</div>';
    }

    var total=(totals||[]).filter(function(r){return Number(r.year)===y})[0];
    if(total){
      h+='<div class="mwh-aggregate-head" style="margin-top:16px"><strong>Total electricity check line</strong><span>For reconciliation against external studies</span></div>';
      h+='<div class="mwh-note-line">Generation shown '+fmt(total.generationShownMWh/1000000,2)+' TWh · Imports '+fmt(total.totalImportMWh/1000000,2)+' TWh · Exports '+fmt(total.totalExportMWh/1000000,2)+' TWh · Net interconnector '+fmt(total.netInterconnectorMWh/1000000,2)+' TWh · Supply proxy '+fmt(total.supplyProxyMWh/1000000,2)+' TWh</div>';
    }
    el.innerHTML=h;
  }
  function monthly(el,rows,technology){
    if(!el)return;
    rows=clean(rows).filter(function(r){return !technology||r.technology===technology});
    if(!rows.length){el.innerHTML='<div class="mwh-empty">Awaiting monthly MWh aggregate data.</div>';return}
    rows=rows.slice().sort(function(a,b){return(a.year-b.year)||(a.month-b.month)});
    var mx=Math.max.apply(null,rows.map(function(r){return Number(r.totalMWh)||0})),sample=rows.slice(-24);
    var h='<div class="mwh-aggregate-head"><strong>Monthly MWh trend</strong><span>'+(technology||'All generation technologies')+'</span></div><div class="mwh-mini-chart">';
    sample.forEach(function(r){
      var p=mx?Math.max(2,Number(r.totalMWh)/mx*100):2;
      h+='<div class="mwh-col" title="'+r.year+'-'+String(r.month).padStart(2,'0')+' '+r.technology+' '+fmt(r.totalMWh/1000000,2)+' TWh"><i style="height:'+p+'%;background:'+(colours[r.technology]||'#00ffff')+'"></i></div>';
    });
    el.innerHTML=h+'</div>';
  }
  function dayNight(el,rows,technology){
    if(!el)return;
    rows=clean(rows).filter(function(r){return !technology||r.technology===technology});
    if(!rows.length){el.innerHTML='<div class="mwh-empty">Awaiting day/night aggregate data.</div>';return}
    var y=Math.max.apply(null,rows.map(function(r){return Number(r.year)||0})),day=0,night=0;
    rows.filter(function(r){return Number(r.year)===y}).forEach(function(r){day+=Number(r.dayMWh||0);night+=Number(r.nightMWh||0)});
    var t=day+night,dp=t?day/t*100:0,np=t?night/t*100:0;
    el.innerHTML='<div class="mwh-aggregate-head"><strong>Day versus night MWh</strong><span>'+y+' - '+(technology||'All generation technologies')+'</span></div><div class="mwh-split"><div style="width:'+dp+'%">Day '+fmt(dp,1)+'%</div><div style="width:'+np+'%">Night '+fmt(np,1)+'%</div></div><div class="mwh-note-line">Day '+fmt(day/1000000,2)+' TWh - Night '+fmt(night/1000000,2)+' TWh</div>';
  }
  return{annual:annual,monthly:monthly,dayNight:dayNight};
})();
"""

CONTROL_JS = """window.V6ControlGenerationMwhAggregates=(function(){
  var hide={'Imports & Exports':1};
  function byId(id){return document.getElementById(id)}
  function tech(){var e=byId('generation-mwh-technology');return e?e.value:'Solar'}
  function fillTech(){
    var e=byId('generation-mwh-technology');if(!e)return;
    var opts=((window.V6GenerationHistoryConfig&&window.V6GenerationHistoryConfig.technologies)||['Solar','Wind','Gas','Nuclear']).filter(function(t){return !hide[t]});
    e.innerHTML='';
    opts.forEach(function(t){var o=document.createElement('option');o.value=t;o.textContent=t;e.appendChild(o)});
    e.value=opts.indexOf('Solar')>=0?'Solar':(opts[0]||'');
  }
  function setStatus(t){var e=byId('generation-mwh-status');if(e)e.textContent=t}
  function refresh(){
    setStatus('Loading MWh aggregate intelligence and granular interconnector split...');
    Promise.all([
      window.V6LoadGenerationMwhAggregates.annual(),
      window.V6LoadGenerationMwhAggregates.monthly(),
      window.V6LoadGenerationMwhAggregates.dayNight(),
      window.V6LoadGenerationMwhAggregates.interconnectorIndex(),
      window.V6LoadGenerationMwhAggregates.interconnectorTotals()
    ]).then(function(p){
      window.V6RenderGenerationMwhAggregates.annual(byId('generation-mwh-annual'),p[0],p[3],p[4]);
      window.V6RenderGenerationMwhAggregates.monthly(byId('generation-mwh-monthly'),p[1],tech());
      window.V6RenderGenerationMwhAggregates.dayNight(byId('generation-mwh-daynight'),p[2],tech());
      setStatus('Aggregate files loaded - legacy Imports & Exports hidden - granular interconnector rows '+p[3].length+' - total electricity check lines '+p[4].length);
    }).catch(function(exc){setStatus('MWh aggregate load failed: '+exc)})
  }
  function init(){fillTech();var e=byId('generation-mwh-technology');if(e)e.addEventListener('change',refresh);refresh()}
  return{init:init,refresh:refresh};
})();
document.addEventListener('DOMContentLoaded',function(){window.V6ControlGenerationMwhAggregates.init()});
"""


def utcnow() -> str:
    return dt.datetime.now(dt.timezone.utc).isoformat().replace("+00:00", "Z")


def rel(p: Path) -> str:
    return p.relative_to(ROOT).as_posix()


def read(p: Path) -> str:
    return p.read_text(encoding="utf-8", errors="replace") if p.exists() else ""


def write(p: Path, txt: str) -> None:
    p.parent.mkdir(parents=True, exist_ok=True)
    p.write_text(txt, encoding="utf-8")


def sha(p: Path) -> str:
    return hashlib.sha256(p.read_bytes()).hexdigest() if p.exists() and p.is_file() else ""


def git(args: list[str]) -> str:
    try:
        result = subprocess.run(["git", *args], cwd=ROOT, text=True, capture_output=True, timeout=30)
        return result.stdout.strip() if result.returncode == 0 else ""
    except Exception:
        return ""


def existing_rows(p: Path) -> list[dict[str, Any]]:
    try:
        d = json.loads(read(p) or "{}")
        r = d.get("rows", [])
        return r if isinstance(r, list) else []
    except Exception:
        return []


def source_files() -> list[Path]:
    out: set[Path] = set()
    for base in SOURCE_ROOTS:
        if not base.exists():
            continue
        for p in base.rglob("elexon_generation_sources_*.csv"):
            out.add(p)
    return sorted(out)


def parse_time(v: str) -> dt.datetime | None:
    try:
        d = dt.datetime.fromisoformat(str(v).replace("Z", "+00:00"))
        if d.tzinfo is None:
            d = d.replace(tzinfo=dt.timezone.utc)
        return d.astimezone(dt.timezone.utc)
    except Exception:
        return None


def parse_float(v: Any) -> float | None:
    try:
        x = float(v)
        return x if math.isfinite(x) else None
    except Exception:
        return None


def infer_interval_hours(points: list[tuple[dt.datetime, float]], idx: int) -> float:
    # Infer within one raw code only; never across sibling interconnector codes.
    t = points[idx][0]
    if idx + 1 < len(points):
        d = (points[idx + 1][0] - t).total_seconds() / 3600
        if 0 < d <= 1:
            return d
    if idx > 0:
        d = (t - points[idx - 1][0]).total_seconds() / 3600
        if 0 < d <= 1:
            return d
    # Raw repo FUELINST archives are 5-minute readings.
    return 5 / 60


def scan_signed_repo_rows(start_year: int, end_year: int):
    by_code: dict[str, dict[tuple[str, str], tuple[dt.datetime, float]]] = defaultdict(dict)
    source_meta = []
    raw_rows = used_rows = skipped_rows = 0
    sign_counts = {code: {"positive": 0, "negative": 0, "zero": 0} for code in CODES}

    for p in source_files():
        file_rows = file_used = 0
        try:
            with p.open("r", encoding="utf-8", newline="") as handle:
                reader = csv.DictReader(handle)
                for row in reader:
                    raw_rows += 1
                    file_rows += 1
                    code = str(row.get("fuelType", "")).strip().upper()
                    if code not in CODES:
                        continue
                    t = parse_time(row.get("periodStartUTC", ""))
                    mw = parse_float(row.get("generationMW"))
                    if t is None or mw is None or not (start_year <= t.year <= end_year):
                        skipped_rows += 1
                        continue
                    key = (t.isoformat().replace("+00:00", "Z"), code)
                    by_code[code][key] = (t, mw)
                    if mw > 0:
                        sign_counts[code]["positive"] += 1
                    elif mw < 0:
                        sign_counts[code]["negative"] += 1
                    else:
                        sign_counts[code]["zero"] += 1
                    file_used += 1
                    used_rows += 1
        except Exception as exc:
            source_meta.append({"path": rel(p), "error": str(exc), "rows": file_rows, "usedRows": file_used})
            continue
        source_meta.append({"path": rel(p), "rows": file_rows, "usedRows": file_used, "sizeBytes": p.stat().st_size})

    return by_code, {
        "sourceMode": "repo_raw_signed_elexon_generation_sources_csv",
        "sourceFileCount": len(source_meta),
        "sourceFiles": source_meta,
        "rawRows": raw_rows,
        "usedRows": used_rows,
        "skippedRows": skipped_rows,
        "signCountsByCode": sign_counts,
    }


def build_flows(start_year: int, end_year: int):
    by_code, meta = scan_signed_repo_rows(start_year, end_year)

    monthly = defaultdict(lambda: {"mwh": 0.0, "records": 0, "firstUTC": "", "lastUTC": ""})
    annual = defaultdict(lambda: {"mwh": 0.0, "records": 0, "firstUTC": "", "lastUTC": ""})

    for code, rows_by_key in by_code.items():
        points = sorted(rows_by_key.values(), key=lambda x: x[0])
        for idx, (t, mw) in enumerate(points):
            hours = infer_interval_hours(points, idx)
            direction = "imports" if mw >= 0 else "exports"
            mwh = mw * hours  # imports positive, exports negative.
            for bucket in (monthly[(t.year, t.month, code, direction)], annual[(t.year, code, direction)]):
                bucket["mwh"] += mwh
                bucket["records"] += 1
                stamp = t.isoformat().replace("+00:00", "Z")
                if not bucket["firstUTC"] or stamp < bucket["firstUTC"]:
                    bucket["firstUTC"] = stamp
                if not bucket["lastUTC"] or stamp > bucket["lastUTC"]:
                    bucket["lastUTC"] = stamp

    return monthly, annual, meta


def flow_file_payload(code: str, direction: str, monthly_buckets: dict[Any, Any], annual_buckets: dict[Any, Any], start_year: int, end_year: int) -> dict[str, Any]:
    spec = CODE_META[code]
    monthly_rows = []
    annual_rows = []

    for (year, month, c, d), b in sorted(monthly_buckets.items()):
        if c == code and d == direction:
            monthly_rows.append({
                "year": year,
                "month": month,
                "country": spec["country"],
                "interconnector": spec["interconnector"],
                "bmrsCode": code,
                "label": spec["label"],
                "flowDirection": "import" if direction == "imports" else "export",
                "signedMWh": round(float(b["mwh"]), 3),
                "mwh": round(float(b["mwh"]), 3),
                "records": int(b["records"]),
                "firstUTC": b["firstUTC"],
                "lastUTC": b["lastUTC"],
            })

    for (year, c, d), b in sorted(annual_buckets.items()):
        if c == code and d == direction:
            annual_rows.append({
                "year": year,
                "country": spec["country"],
                "interconnector": spec["interconnector"],
                "bmrsCode": code,
                "label": spec["label"],
                "flowDirection": "import" if direction == "imports" else "export",
                "signedMWh": round(float(b["mwh"]), 3),
                "mwh": round(float(b["mwh"]), 3),
                "records": int(b["records"]),
                "firstUTC": b["firstUTC"],
                "lastUTC": b["lastUTC"],
            })

    return {
        "schemaVersion": "1.0.0-interconnector-granular-flow-file",
        "generatedUTC": utcnow(),
        "country": spec["country"],
        "interconnector": spec["interconnector"],
        "bmrsCode": code,
        "label": spec["label"],
        "flowDirection": "import" if direction == "imports" else "export",
        "signConvention": "Imports are positive MWh. Exports are negative MWh.",
        "source": "Signed Elexon BMRS raw-code rows already present in repository elexon_generation_sources_*.csv files.",
        "startYear": start_year,
        "endYear": end_year,
        "monthlyRows": monthly_rows,
        "annualRows": annual_rows,
    }


def planned_data_files(start_year: int, end_year: int):
    monthly, annual, meta = build_flows(start_year, end_year)
    files: dict[Path, str] = {}
    index_rows = []

    years = sorted({k[0] for k in annual})
    for code in sorted(CODES, key=lambda c: CODE_META[c]["sortOrder"]):
        spec = CODE_META[code]
        paths = {}
        for direction in ("imports", "exports"):
            path = OUT_DIR / f"{spec['slug']}_{direction}.json"
            payload = flow_file_payload(code, direction, monthly, annual, start_year, end_year)
            files[path] = json.dumps(payload, indent=2, ensure_ascii=False) + "\n"
            paths[direction] = rel(path)

        for year in years:
            imp = annual.get((year, code, "imports"), {"mwh": 0.0, "records": 0})
            exp = annual.get((year, code, "exports"), {"mwh": 0.0, "records": 0})
            import_mwh = float(imp["mwh"])
            export_mwh = float(exp["mwh"])  # already negative.
            index_rows.append({
                "year": year,
                "country": spec["country"],
                "interconnector": spec["interconnector"],
                "bmrsCode": code,
                "label": spec["label"],
                "importFile": paths["imports"],
                "exportFile": paths["exports"],
                "importMWh": round(import_mwh, 3),
                "exportMWh": round(export_mwh, 3),
                "netMWh": round(import_mwh + export_mwh, 3),
                "importRecords": int(imp["records"]),
                "exportRecords": int(exp["records"]),
                "sortOrder": spec["sortOrder"],
            })

    index_payload = {