GLOBALGRID2050 / EXPLORE CODE

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

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

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.

552 lines of Python from globalgrid2050, in 2 files. Topic: Grid network and substations. Section 334 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 Gridbot Generation Interconnector Split energy-data · globalgrid2050 / scripts/gridbot_generation_interconnector_split.py lines 472–781
  2. GlobalGrid2050 Gridbot Generation MWh Interconnector Split V6 energy-data · globalgrid2050 / scripts/gridbot_generation_mwh_interconnector_split_v6.py lines 1–242

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 472–781 of 781 (continued from section 333) · 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
generation_shown_by_year, total_summary_rows, add_total_file, insert_warning, insert_css, patch_index, node_check, planned_files, changed_paths, collect_checks, raw_temp_files, write_reports, 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/gridbot_generation_interconnector_split.py:472-781 · 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
        "schemaVersion": "1.0.0-interconnector-index",
        "generatedUTC": utcnow(),
        "title": "GB interconnector import/export index",
        "labelContract": "country - interconnector name - BMRS code",
        "signConvention": "Imports are positive MWh. Exports are negative MWh.",
        "sourceAudit": meta,
        "rows": index_rows,
    }
    files[OUT_INDEX] = json.dumps(index_payload, indent=2, ensure_ascii=False) + "\n"
    return files, index_rows, meta


def generation_shown_by_year() -> dict[int, float]:
    by_year = defaultdict(float)
    for row in existing_rows(EXISTING_ANNUAL):
        tech = row.get("technology")
        if tech == LEGACY_BUCKET:
            continue
        try:
            by_year[int(row.get("year"))] += float(row.get("totalMWh") or 0)
        except Exception:
            continue
    return dict(by_year)


def total_summary_rows(index_rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
    generation = generation_shown_by_year()
    years = sorted(set(generation) | {int(row["year"]) for row in index_rows})
    rows = []
    for year in years:
        imports = sum(float(row.get("importMWh") or 0) for row in index_rows if int(row["year"]) == year)
        exports = sum(float(row.get("exportMWh") or 0) for row in index_rows if int(row["year"]) == year)
        net = imports + exports
        generation_mwh = generation.get(year, 0.0)
        rows.append({
            "year": year,
            "generationShownMWh": round(generation_mwh, 3),
            "totalImportMWh": round(imports, 3),
            "totalExportMWh": round(exports, 3),
            "netInterconnectorMWh": round(net, 3),
            "supplyProxyMWh": round(generation_mwh + net, 3),
            "note": "Supply proxy equals visible generation technologies plus net interconnector imports. Use for sense-checking against external studies, not as final demand.",
        })
    return rows


def add_total_file(files: dict[Path, str], index_rows: list[dict[str, Any]]):
    rows = total_summary_rows(index_rows)
    payload = {
        "schemaVersion": "1.0.0-total-electricity-check",
        "generatedUTC": utcnow(),
        "title": "Total electricity check line for generation plus net interconnector imports",
        "unit": "MWh",
        "signConvention": "Imports positive, exports negative.",
        "rows": rows,
    }
    files[OUT_TOTALS] = json.dumps(payload, indent=2, ensure_ascii=False) + "\n"
    return rows


def insert_warning(txt: str) -> str:
    warning = '<div class="generation-source-warning mwh-interconnector-split-warning"><strong>Interconnector accounting:</strong> The former Imports &amp; Exports generation bucket is hidden. Interconnectors are shown separately as signed imports, signed exports and net flow, labelled country first, interconnector name second and BMRS code third. Total electricity check lines are shown for extern  … [line shortened here: 425 characters; full line on GitHub]
    pattern = re.compile(r'\n?\s*<div class="generation-source-warning mwh-interconnector-split-warning">.*?</div>', re.DOTALL)
    txt, count = pattern.subn("\n        " + warning, txt)
    if count:
        return txt
    anchor = '          <div class="mwh-card" id="generation-mwh-daynight"></div>\n        </div>'
    if anchor in txt:
        return txt.replace(anchor, anchor + "\n        " + warning, 1)
    return txt


def insert_css(txt: str) -> str:
    if ".mwh-interconnector-row" in txt:
        return txt
    css = """
  #generation-history-panel .mwh-interconnector-bars{margin-top:6px;}
  #generation-history-panel .mwh-row.mwh-interconnector-row{grid-template-columns:minmax(250px,.9fr) 1fr 120px;font-size:11px;}
  #generation-history-panel .mwh-row.mwh-interconnector-row .mwh-label{white-space:normal;line-height:1.25;color:#cfd7e6;}
"""
    return txt.replace("</style>", css + "</style>", 1)


def patch_index(txt: str) -> str:
    txt = insert_css(insert_warning(txt))
    for name in ("load_generation_mwh_aggregates", "render_generation_mwh_aggregates", "control_generation_mwh_aggregates"):
        txt = re.sub(rf"(/uk_energy_tracking_v6/generation_history/{name}\.js\?v=)[^\"']+", rf"\g<1>{CACHE}", txt)
    return txt


def node_check(source: str, label: str) -> dict[str, Any]:
    try:
        with tempfile.NamedTemporaryFile("w", suffix=f"_{label}.js", delete=False, encoding="utf-8") as handle:
            handle.write(source)
            tmp = Path(handle.name)
        result = subprocess.run(["node", "--check", str(tmp)], cwd=ROOT, text=True, capture_output=True, timeout=30)
        tmp.unlink(missing_ok=True)
        return {"ok": result.returncode == 0, "detail": (result.stderr or result.stdout).strip()}
    except FileNotFoundError:
        return {"ok": True, "detail": "node unavailable; syntax check skipped"}
    except Exception as exc:
        return {"ok": False, "detail": str(exc)}


def planned_files(start_year: int, end_year: int) -> tuple[dict[Path, str], list[dict[str, Any]], list[dict[str, Any]], dict[str, Any]]:
    data_files, index_rows, source_meta = planned_data_files(start_year, end_year)
    total_rows = add_total_file(data_files, index_rows)
    files = {
        INDEX: patch_index(read(INDEX)),
        LOAD: LOAD_JS,
        RENDER: RENDER_JS,
        CONTROL: CONTROL_JS,
    }
    files.update(data_files)
    return files, index_rows, total_rows, source_meta


def changed_paths(planned: dict[Path, str]) -> list[str]:
    return [rel(path) for path, content in planned.items() if read(path) != content]


def collect_checks(planned: dict[Path, str], index_rows: list[dict[str, Any]], total_rows: list[dict[str, Any]], source_meta: dict[str, Any], before_hashes: dict[str, Any]) -> tuple[dict[str, bool], dict[str, Any]]:
    index_text = planned[INDEX]
    load = planned[LOAD]
    render = planned[RENDER]
    control = planned[CONTROL]
    current_hashes = {k: sha(p) for k, p in before_hashes["paths"].items()}

    js = {
        "load": node_check(load, "load_generation_mwh_aggregates"),
        "render": node_check(render, "render_generation_mwh_aggregates"),
        "control": node_check(control, "control_generation_mwh_aggregates"),
    }

    output_paths = [p for p in planned if p.as_posix().endswith(".json") and OUT_DIR in p.parents]
    import_files = [p for p in output_paths if p.name.endswith("_imports.json")]
    export_files = [p for p in output_paths if p.name.endswith("_exports.json")]

    checks = {
        "target_files_exist": all(p.exists() for p in (INDEX, LOAD, RENDER, CONTROL)),
        "target_route_present": f"permalink: {ROUTE}" in index_text,
        "mwh_panel_present": "Generation output in MWh" in index_text and "generation-mwh-annual" in index_text,
        "legacy_imports_exports_hidden_in_render": "hide={'Imports & Exports':1}" in render,
        "legacy_imports_exports_hidden_in_control": "hide={'Imports & Exports':1}" in control,
        "load_reads_interconnector_index_and_totals": "generation_interconnector_index.json" in load and "generation_interconnector_total_electricity_summary.json" in load,
        "two_files_per_interconnector": len(import_files) == 10 and len(export_files) == 10,
        "imports_positive_exports_negative": bool(index_rows) and all(float(r.get("importMWh") or 0) >= 0 and float(r.get("exportMWh") or 0) <= 0 for r in index_rows),
        "separate_import_export_net_fields": bool(index_rows) and all(k in index_rows[0] for k in ("importMWh", "exportMWh", "netMWh")),
        "labels_are_country_first_interconnector_second_code_third": bool(index_rows) and all(len(str(r.get("label", "")).split(" - ")) >= 3 and str(r.get("label", "")).split(" - ")[2].startswith("INT") for r in index_rows),
        "all_ten_interconnector_codes_present": set(CODE_META).issubset({r.get("bmrsCode") for r in index_rows}),
        "total_electricity_summary_present": bool(total_rows) and all(k in total_rows[0] for k in ("generationShownMWh", "totalImportMWh", "totalExportMWh", "netInterconnectorMWh", "supplyProxyMWh")),
        "signed_rows_detected_in_source": any(v["positive"] > 0 for v in source_meta["signCountsByCode"].values()) and any(v["negative"] > 0 for v in source_meta["signCountsByCode"].values()),
        "raw_rows_not_written": True,
        "existing_generation_aggregate_jsons_not_modified": all(before_hashes["hashes"].get(k) == current_hashes.get(k) for k in before_hashes["hashes"]),
        "index_cache_busters_updated": CACHE in index_text,
        "index_has_interconnector_warning": "mwh-interconnector-split-warning" in index_text,
        "load_js_syntax_ok": bool(js["load"]["ok"]),
        "render_js_syntax_ok": bool(js["render"]["ok"]),
        "control_js_syntax_ok": bool(js["control"]["ok"]),
    }
    return checks, {"jsSyntax": js, "currentHashes": current_hashes}


def raw_temp_files() -> list[str]:
    hits = []
    for base in [ROOT / "data" / "raw", ROOT / "data" / "transient", ROOT / "data" / "tmp", ROOT / "tmp", ROOT / "temp"]:
        if base.exists():
            hits.extend(rel(p) for p in base.rglob("*") if p.is_file())
    return sorted(set(hits))[:200]


def write_reports(report: dict[str, Any]) -> None:
    REPORT_DIR.mkdir(parents=True, exist_ok=True)
    REPORT_JSON_DIR.mkdir(parents=True, exist_ok=True)
    lines = [
        f"# {REPORT_TITLE}",
        "",
        f"Generated UTC: `{report['generatedUTC']}`",
        f"Mode: `{report['mode']}`",
        f"Pass: `{report['pass']}`",
        "",
        "## Executive summary",
        "",
        report["executiveSummary"],
        "",
        "## Granular data contract",
        "",
        "- Two files per interconnector: one imports file and one exports file.",
        "- Imports are positive MWh.",
        "- Exports are negative MWh.",
        "- Total electricity check lines are written for external reconciliation.",
        "- Label order is country, interconnector name, BMRS code.",
        "",
        "## Interconnectors",
        "",
    ]
    lines += [f"- {row}" for row in report["interconnectors"]]
    lines += [
        "",
        "## Output rows",
        "",
        f"- Index rows: `{report['outputRows']['index']}`",
        f"- Total electricity rows: `{report['outputRows']['totalElectricity']}`",
        f"- JSON output files: `{report['outputFilesJsonCount']}`",
        "",
        "## Planned changed files",
        "",
    ]
    lines += [f"- `{p}`" for p in report["plannedChangedFiles"]]
    lines += ["", "## Changed files in this mode", ""]
    lines += [f"- `{p}`" for p in report["changedFiles"]] or ["- none"]
    lines += ["", "## Checks", "", "| Check | Result |", "|---|---|"]
    lines += [f"| {k} | {'✅' if v else '❌'} |" for k, v in report["checks"].items()]
    lines += [
        "",
        "## Method",
        "",
        "Signed raw-code interconnector rows are scanned before collapse. Energy is calculated per BMRS code, not inside a merged INT* technology bucket. Imports are stored as positive signed MWh and exports as negative signed MWh.",
        "",
        "## Rollback",
        "",
        report["rollbackMethod"],
        "",
    ]
    write(REPORT_MD, "\n".join(lines) + "\n")
    write(REPORT_JSON, json.dumps(report, indent=2, ensure_ascii=False) + "\n")


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--start-year", type=int, default=2016)
    ap.add_argument("--end-year", default="auto")
    ap.add_argument("--apply", action="store_true")
    args = ap.parse_args()

    end_year = dt.datetime.now(dt.timezone.utc).year if args.end_year == "auto" else int(args.end_year)
    mode = "apply" if args.apply else "audit"
    git_head_before = git(["rev-parse", "HEAD"])
    existing_paths = {
        "annual": EXISTING_ANNUAL,
        "monthly": EXISTING_MONTHLY,
        "seasonal": EXISTING_SEASONAL,
        "dayNight": EXISTING_DAY_NIGHT,
    }
    before_hashes = {"paths": existing_paths, "hashes": {k: sha(p) for k, p in existing_paths.items()}}
    planned, index_rows, total_rows, source_meta = planned_files(args.start_year, end_year)
    planned_changed = changed_paths(planned)
    checks, state = collect_checks(planned, index_rows, total_rows, source_meta, before_hashes)

    output_json_paths = sorted(rel(p) for p in planned if OUT_DIR in p.parents and p.suffix == ".json")
    report = {
        "reportTitle": REPORT_TITLE,
        "schemaVersion": "2.0.0-granular",
        "generatedUTC": utcnow(),
        "repository": "Ventusltd/globalgrid2050",
        "branch": git(["branch", "--show-current"]),
        "gitHeadBefore": git_head_before,
        "gitHeadAfter": git(["rev-parse", "HEAD"]),
        "workflowName": WORKFLOW_NAME,
        "scriptName": SCRIPT_NAME,
        "upgradeType": "live V6 granular interconnector split for MWh panel",
        "mode": mode,
        "sourceApis": [],
        "sourceWindows": [f"{args.start_year} to {end_year}"],
        "inputFiles": [rel(INDEX), rel(LOAD), rel(RENDER), rel(CONTROL), rel(EXISTING_ANNUAL), rel(EXISTING_MONTHLY), rel(EXISTING_SEASONAL), rel(EXISTING_DAY_NIGHT)] + [f["path"] for f in source_meta["sourceFiles"][:50]],
        "outputFiles": [rel(INDEX), rel(LOAD), rel(RENDER), rel(CONTROL), rel(REPORT_MD), rel(REPORT_JSON)] + output_json_paths,
        "outputFilesJsonCount": len(output_json_paths),
        "changedFiles": planned_changed if args.apply else [],
        "plannedChangedFiles": planned_changed,
        "addedFiles": [rel(p) for p in planned if p.suffix == ".json" and OUT_DIR in p.parents and not p.exists()],
        "deletedFiles": [],
        "interconnectors": [CODE_META[c]["label"] for c in sorted(CODES, key=lambda c: CODE_META[c]["sortOrder"])],
        "legacyBucketRowsFound": {
            "annual": sum(1 for r in existing_rows(EXISTING_ANNUAL) if r.get("technology") == LEGACY_BUCKET),
            "monthly": sum(1 for r in existing_rows(EXISTING_MONTHLY) if r.get("technology") == LEGACY_BUCKET),
        },
        "sourceAudit": source_meta,
        "outputRows": {"index": len(index_rows), "totalElectricity": len(total_rows)},
        "sourceHashesBefore": before_hashes["hashes"],
        "sourceHashesAfter": state["currentHashes"],
        "rawTemporaryFilesFound": raw_temp_files(),
        "browserRoutingAffected": True,
        "checks": checks,
        "jsSyntax": state["jsSyntax"],
        "rollbackMethod": "Revert the apply commit. Existing generation aggregate JSON files are not modified by this workflow.",
        "executiveSummary": "Splits interconnectors out of the live V6 Generation Output in MWh panel using granular signed per-link files. The legacy Imports & Exports bucket is hidden, ten interconnectors each receive separate import and export JSON files, imports remain positive, exports remain negative, and a total electricity check line is shown at the bottom for reconciliation.",
        "humanReviewStatus": "awaiting Vikram review" if not args.apply else "apply completed; verify live page after Pages deploy",
        "nextAction": "Review audit report, then rerun in apply mode only if all checks pass." if not args.apply else "Open live page and verify annual MWh panel, interconnector rows and total electricity check line on desktop and mobile.",
        "applied": bool(args.apply),
        "pass": all(checks.values()),
    }

    if not report["pass"]:
        write_reports(report)
        print(json.dumps(report, indent=2, ensure_ascii=False))
        raise SystemExit("checks failed")

    if args.apply:
        for path, content in planned.items():
            if read(path) != content:
                write(path, content)

    report["gitHeadAfter"] = git(["rev-parse", "HEAD"])
    write_reports(report)
    print(json.dumps(report, indent=2, ensure_ascii=False))
    return 0


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

GlobalGrid2050 Gridbot Generation MWh Interconnector Split V6

A Python command-line tool in the scripts folder that parses time, builds rows and patches index, covering generation annual mwh by technology and generation monthly mwh by technology.

energy-dataglobalgrid2050 / scripts/gridbot_generation_mwh_interconnector_split_v6.py · lines 1–242 of 242 · Entry point · pattern build_rows (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 16 functions or classes, including now, read, write, rel, parse_time. Uses libraries __future__, argparse, csv, datetime, json. Side effects: changes the web page (DOM); reads or writes files; makes network requests.
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_interconnector_annual_mwh_by_link_direction.json; JSON file GENERATION_MWH_INTERCONNECTOR_SPLIT_V6_LATEST.json; 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; command-line arguments.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Gridbot Generation MWh Interconnector Split V6 Workflow (globalgrid2050).
What it achieves
It parses time (`parse_time`), builds rows (`build_rows`) and patches index (`patch_index`). Defines `now`, `read`, `write` and 12 more. It reads `generation_annual_mwh_by_technology.json`. It accepts `--apply` and `--max-output-mb`.
Why it matters
Run by GlobalGrid2050 Gridbot Generation MWh Interconnector Split V6 Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
__future__, argparse, csv, datetime, json, math, re, collections
Used by
run by GlobalGrid2050 Gridbot Generation MWh Interconnector Split V6 Workflow (workflow run)
Produces
now, read, write, rel, parse_time, fnum, source_files, interval_hours, build_rows, payload, patch_index, planned
Defines here
now, read, write, rel, parse_time, fnum, source_files, interval_hours, build_rows, payload, patch_index, planned, changed_files, latest_legacy, 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/gridbot_generation_mwh_interconnector_split_v6.py:1-242 · blob 2c13614e20e9283dda5227bc8f02f3dffcf8eeea · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, filesystem, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
from __future__ import annotations

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

ROOT = Path(__file__).resolve().parent.parent
MOD = ROOT / 'uk_energy_tracking_v6' / 'generation_history'
INDEX = MOD / 'index.md'
LOAD = MOD / 'load_generation_mwh_aggregates.js'
RENDER = MOD / 'render_generation_mwh_aggregates.js'
CONTROL = MOD / 'control_generation_mwh_aggregates.js'
OUT = MOD / 'generation_interconnector_annual_mwh_by_link_direction.json'
REPORT = ROOT / 'data_science_protocol' / 'audit_reports'
REPORT_JSON = REPORT / 'json'
MD = REPORT / 'GENERATION_MWH_INTERCONNECTOR_SPLIT_V6_LATEST.md'
JS = REPORT_JSON / 'GENERATION_MWH_INTERCONNECTOR_SPLIT_V6_LATEST.json'
ROUTE = '/uk_energy_tracking_v6/generation_history/'
LEGACY = 'Imports & Exports'
STAMP = '20260613interconsplit1'
WARN_CLASS = 'mwh-interconnector-split-warning'

INTERCONNECTORS = [
    {'code':'INTFR','country':'France','name':'IFA / HVDC Cross-Channel'},
    {'code':'INTIFA2','country':'France','name':'IFA2'},
    {'code':'INTELEC','country':'France','name':'ElecLink'},
    {'code':'INTNEM','country':'Belgium','name':'Nemo Link'},
    {'code':'INTNED','country':'Netherlands','name':'BritNed'},
    {'code':'INTNSL','country':'Norway','name':'North Sea Link'},
    {'code':'INTVKL','country':'Denmark','name':'Viking Link'},
    {'code':'INTEW','country':'Ireland','name':'East-West Interconnector / EWIC'},
    {'code':'INTGRNL','country':'Ireland','name':'Greenlink'},
    {'code':'INTIRL','country':'Northern Ireland','name':'Moyle Interconnector'},
]
SPEC = {x['code']: x for x in INTERCONNECTORS}
ORDER = {x['code']: i for i, x in enumerate(INTERCONNECTORS)}

WARNING_HTML = '''        <div class="generation-source-warning mwh-interconnector-split-warning"><strong>Interconnector accounting split:</strong> The old combined Imports &amp; Exports bucket has been removed from this Generation Output in MWh panel. Named interconnector rows are shown at the bottom of the annual chart as separate gross imports and gross exports. Labels use country first, interc  … [line shortened here: 674 characters; full line on GitHub]

PATCH_LOAD = '''window.V6LoadGenerationMwhAggregates=(function(){
  var cache={};
  function fetchRows(key,url){
    if(cache[key])return cache[key];
    cache[key]=fetch(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[]});
    return cache[key];
  }
  function annual(){return fetchRows('annual','/uk_energy_tracking_v6/generation_history/generation_annual_mwh_by_technology.json')}
  function monthly(){return fetchRows('monthly','/uk_energy_tracking_v6/generation_history/generation_monthly_mwh_by_technology.json')}
  function seasonal(){return fetchRows('seasonal','/uk_energy_tracking_v6/generation_history/generation_seasonal_mwh_by_technology.json')}
  function dayNight(){return fetchRows('daynight','/uk_energy_tracking_v6/generation_history/generation_day_night_mwh_by_technology.json')}
  function interconnectors(){return fetchRows('interconnectors','/uk_energy_tracking_v6/generation_history/generation_interconnector_annual_mwh_by_link_direction.json')}
  return{annual:annual,monthly:monthly,seasonal:seasonal,dayNight:dayNight,interconnectors:interconnectors};
})();
'''

PATCH_RENDER = '''window.V6RenderGenerationMwhAggregates=(function(){
  var colours={Solar:'#f5c518',Wind:'#00d0ff',Hydro:'#0090c0',Gas:'#c0399a',Coal:'#888888',Biomass:'#f59e2b',Nuclear:'#5cb85c','Pumped Storage':'#9b59b6','Imports & Exports':'#e8615a',Other:'#a6adbb'};
  var HIDDEN={'Imports & Exports':true};
  var interconnectorColours={import:'#33d17a',export:'#ff8a3d'};
  function visible(rows){return(rows||[]).filter(function(r){return r&&!HIDDEN[r.technology]})}
  function fmt(n,d){return n==null||isNaN(Number(n))?'—':Number(n).toLocaleString('en-GB',{minimumFractionDigits:d,maximumFractionDigits:d})}
  function ilabel(r){return r.label||[r.country,r.interconnector,r.bmrsCode,r.directionLabel].filter(Boolean).join(' — ')}
  function latestYear(a,b){var ys=[];(a||[]).forEach(function(r){ys.push(Number(r.year)||0)});(b||[]).forEach(function(r){ys.push(Number(r.year)||0)});return Math.max.apply(null,ys)}
  function renderAnnual(el,rows,interRows){
    if(!el)return;rows=rows||[];interRows=interRows||[];
    if(!rows.length){el.innerHTML='<div class="mwh-empty">Awaiting annual MWh aggregate data.</div>';return;}
    var latest=latestYear(rows,interRows);
    var gen=visible(rows.filter(function(r){return Number(r.year)===latest})).sort(function(a,b){return Number(b.totalMWh)-Number(a.totalMWh)});
    var cons=interRows.filter(function(r){return Number(r.year)===latest&&Number(r.totalMWh)>0}).sort(function(a,b){return (Number(a.sortOrder)||0)-(Number(b.sortOrder)||0)});
    if(!gen.length){el.innerHTML='<div class="mwh-empty">Awaiting annual MWh aggregate data after hidden bucket filter.</div>';return;}
    var total=gen.reduce(function(s,r){return s+Number(r.totalMWh||0)},0), maxAbs=1;
    gen.concat(cons).forEach(function(r){maxAbs=Math.max(maxAbs,Math.abs(Number(r.totalMWh||0)))});
    var html='<div class="mwh-aggregate-head"><strong>Annual MWh by technology</strong><span>'+latest+' · '+fmt(total/1000000,2)+' TWh generation shown · legacy Imports & Exports removed</span></div><div class="mwh-bars">';
    gen.forEach(function(r){var v=Number(r.totalMWh||0),pct=Math.max(0,Math.abs(v)/maxAbs*100),c=colours[r.technology]||'#00ffff';html+='<div class="mwh-row"><div class="mwh-label">'+r.technology+'</div><div class="mwh-track"><i style="width:'+pct+'%;background:'+c+'"></i></div><div class="mwh-value">'+fmt(v/1000000,2)+' TWh</div></div>'});
    if(cons.length){html+='<div class="mwh-interconnector-divider">Named interconnectors · gross imports and gross exports · candidate signed-flow split</div>';cons.forEach(function(r){var v=Number(r.totalMWh||0),pct=Math.max(0,Math.abs(v)/maxAbs*100),c=interconnectorColours[String(r.direction||'')]||'#a6adbb',lab=ilabel(r);html+='<div class="mwh-row mwh-interconnector-row" title="'+lab+'"><div cl  … [line shortened here: 568 characters; full line on GitHub]
    html+='</div>';el.innerHTML=html;
  }
  function renderMonthly(el,rows,technology){if(!el)return;rows=visible(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 max=Math.max.apply(null,rows.map(function(r){return Number(r.tot  … [line shortened here: 936 characters; full line on GitHub]
  function renderDayNight(el,rows,technology){if(!el)return;rows=visible(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 latest=Math.max.apply(null,rows.map(function(r){return Number(r.year)||0}));var subset=rows.filter(function(r){return Number(r.year)===latest});va  … [line shortened here: 958 characters; full line on GitHub]
  return{annual:renderAnnual,monthly:renderMonthly,dayNight:renderDayNight};
})();
'''

PATCH_CONTROL = '''window.V6ControlGenerationMwhAggregates=(function(){
  var HIDDEN={'Imports & Exports':true};
  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 !HIDDEN[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?'S  … [line shortened here: 420 characters; full line on GitHub]
  function setStatus(text){var e=byId('generation-mwh-status');if(e)e.textContent=text}
  function refresh(){setStatus('Loading MWh aggregate intelligence...');Promise.all([window.V6LoadGenerationMwhAggregates.annual(),window.V6LoadGenerationMwhAggregates.monthly(),window.V6LoadGenerationMwhAggregates.dayNight(),window.V6LoadGenerationMwhAggregates.interconnectors?window.V6LoadGenerationMwhAggregates.interconnectors():Promise.resolve([])]).then(function(parts){window.V6RenderGenerati  … [line shortened here: 992 characters; full line on GitHub]
  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 now():
    return dt.datetime.now(dt.timezone.utc).isoformat().replace('+00:00','Z')

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

def write(path: Path, text: str):
    path.parent.mkdir(parents=True, exist_ok=True); path.write_text(text, encoding='utf-8')

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

def parse_time(v):
    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 fnum(v):
    try:
        x=float(v); return x if math.isfinite(x) else None
    except Exception:
        return None

def source_files():
    roots=[ROOT/'data'/'generation'/'archive', ROOT/'data'/'generation']
    out=set()
    for r in roots:
        if r.exists():
            for p in r.rglob('elexon_generation_sources_*.csv'): out.add(p)
    return sorted(out)

def interval_hours(items, i):
    t=items[i][0]
    if i+1 < len(items):
        h=(items[i+1][0]-t).total_seconds()/3600
        if 0 < h <= 1: return h
    if i > 0:
        h=(t-items[i-1][0]).total_seconds()/3600
        if 0 < h <= 1: return h
    return 5/60

def build_rows():
    dedup={}; meta=[]; raw=found=parsed=skipped=0
    for p in source_files():
        fr=fi=0
        try:
            with p.open('r',encoding='utf-8',newline='') as h:
                for row in csv.DictReader(h):
                    raw+=1; fr+=1
                    code=str(row.get('fuelType','')).strip().upper()
                    if code not in SPEC: continue
                    found+=1; fi+=1
                    t=parse_time(row.get('periodStartUTC','')); mw=fnum(row.get('generationMW'))
                    if t is None or mw is None: skipped+=1; continue
                    dedup[(t.isoformat().replace('+00:00','Z'),code)]=(t,code,mw); parsed+=1
            meta.append({'path':rel(p),'rows':fr,'interconnectorRows':fi,'sizeBytes':p.stat().st_size})
        except Exception as exc:
            meta.append({'path':rel(p),'error':str(exc),'rows':fr,'interconnectorRows':fi})
    by=defaultdict(list)
    for t,code,mw in dedup.values(): by[code].append((t,mw))
    buckets=defaultdict(lambda:{'totalMWh':0.0,'netSignedMWh':0.0,'records':0,'firstUTC':'','lastUTC':''})
    for code,items in by.items():
        items.sort(key=lambda x:x[0])
        for i,(t,mw) in enumerate(items):
            h=interval_hours(items,i); direction='import' if mw>=0 else 'export'; gross=abs(mw)*h; key=(t.year,code,direction); b=buckets[key]
            b['totalMWh']+=gross; b['netSignedMWh']+=mw*h; b['records']+=1
            s=t.isoformat().replace('+00:00','Z')
            if not b['firstUTC'] or s < b['firstUTC']: b['firstUTC']=s
            if not b['lastUTC'] or s > b['lastUTC']: b['lastUTC']=s
    years=sorted({k[0] for k in buckets})
    rows=[]
    for y in years:
        for spec in INTERCONNECTORS:
            for direction in ('import','export'):
                b=buckets.get((y,spec['code'],direction),{'totalMWh':0,'netSignedMWh':0,'records':0,'firstUTC':'','lastUTC':''})
                dl='Imports to GB' if direction=='import' else 'Exports from GB'
                label=f"{spec['country']} — {spec['name']} — {spec['code']} — {dl}"
                rows.append({'year':y,'technology':label,'label':label,'country':spec['country'],'interconnector':spec['name'],'bmrsCode':spec['code'],'direction':direction,'directionLabel':dl,'totalMWh':round(float(b['totalMWh']),3),'netSignedMWh':round(float(b['netSignedMWh']),3),'records':int(b['records']),'sourceMinUTC':b['firstUTC'],'sourceMaxUTC':b['lastUTC'],'source':'Elexon BMRS FUELINST r  … [line shortened here: 670 characters; full line on GitHub]
    audit={'sourceFileCount':len(meta),'sourceFiles':meta,'rawRows':raw,'interconnectorRawRows':found,'parsedRows':parsed,'dedupedTimeCodeRows':len(dedup),'skippedRows':skipped,'years':years,'interconnectorCodes':[x['code'] for x in INTERCONNECTORS]}
    return rows,audit

def payload(rows,audit):
    return {'schemaVersion':'1.0.0-interconnector-annual-mwh-link-direction','generatedUTC':now(),'title':'Annual interconnector MWh by named link and direction','unit':'MWh','source':'Existing Elexon BMRS FUELINST raw-code archive files','status':'candidate','directionConvention':'Positive signed MW is treated as import to GB. Negative signed MW is treated as export from GB.','labelContract':'cou  … [line shortened here: 532 characters; full line on GitHub]

def patch_index(text):
    css='''\n  #generation-history-panel .mwh-interconnector-divider{margin:12px 0 8px;padding-top:10px;border-top:1px solid rgba(0,255,255,.24);color:#00ffff;font-size:11px;letter-spacing:.08em;text-transform:uppercase;}\n  #generation-history-panel .mwh-row.mwh-interconnector-row{grid-template-columns:minmax(260px,.9fr) 1fr 95px;font-size:11px;}\n  #generation-history-panel .mwh-row.mwh-intercon  … [line shortened here: 478 characters; full line on GitHub]
    if '.mwh-interconnector-divider' not in text: text=text.replace('</style>', css+'</style>', 1)
    pat=re.compile(r'\n?\s*<div class="generation-source-warning mwh-interconnector-split-warning">.*?</div>', re.DOTALL)
    text,n=pat.subn('\n'+WARNING_HTML, text)
    if not n:
        anchor='          <div class="mwh-card" id="generation-mwh-daynight"></div>\n        </div>'
        text=text.replace(anchor, anchor+'\n'+WARNING_HTML, 1)
    for s in ('load_generation_mwh_aggregates.js','render_generation_mwh_aggregates.js','control_generation_mwh_aggregates.js'):
        text=re.sub(rf'(/uk_energy_tracking_v6/generation_history/{re.escape(s)}\?v=)[^"\']+', r'\g<1>'+STAMP, text)
    return text

def planned(rows,audit):
    return {INDEX:patch_index(read(INDEX)),LOAD:PATCH_LOAD,RENDER:PATCH_RENDER,CONTROL:PATCH_CONTROL,OUT:json.dumps(payload(rows,audit),indent=2,ensure_ascii=False)+'\n'}

def changed_files(planned_map):
    return [rel(p) for p,c in planned_map.items() if read(p)!=c]

def latest_legacy():
    try: rows=json.loads(read(MOD/'generation_annual_mwh_by_technology.json')).get('rows',[])
    except Exception: rows=[]
    years=[int(r.get('year') or 0) for r in rows if isinstance(r,dict)]; y=max(years) if years else 0
    vals=[float(r.get('totalMWh') or 0) for r in rows if int(r.get('year') or 0)==y and r.get('technology')==LEGACY]
    return {'latestYear':y,'rowCount':len(vals),'totalMWh':round(sum(vals),3)}

def make_report(data):
    lines=['# Generation MWh Interconnector Split V6 — '+('PASS' if data['pass'] else 'FAIL'),'','Generated UTC: `'+data['generatedUTC']+'`','Mode: `'+data['mode']+'`','Route: `'+ROUTE+'`','','## Contract','','Positive signed MW is treated as import to GB. Negative signed MW is treated as export from GB. Labels use: country — interconnector name — BMRS code — direction.','','## Planned changed fil  … [line shortened here: 404 characters; full line on GitHub]
    lines += ['- `'+x+'`' for x in data['plannedChangedFiles']] or ['- none']
    lines += ['','## Checks','','| Check | Result |','|---|---|']
    for k,v in data['checks'].items(): lines.append('| '+k+' | '+('✅' if v else '❌')+' |')
    lines += ['','## Interconnector fields']
    for s in INTERCONNECTORS:
        lines.append('- '+s['country']+' — '+s['name']+' — `'+s['code']+'` — Imports to GB / Exports from GB')
    lines += ['','## Source audit',f"- Source files scanned: `{data['sourceAudit']['sourceFileCount']}`",f"- Interconnector raw rows: `{data['sourceAudit']['interconnectorRawRows']}`",f"- Output rows: `{data['interconnectorSummary']['outputRows']}`",'','Rollback: revert the apply commit. Existing generation aggregate JSON files are not edited.']
    return '\n'.join(lines)+'\n'

def main():
    ap=argparse.ArgumentParser(); ap.add_argument('--apply',action='store_true'); ap.add_argument('--max-output-mb',type=float,default=25.0); args=ap.parse_args()
    mode='apply' if args.apply else 'audit'
    rows,audit=build_rows(); plan=planned(rows,audit); size=len(plan[OUT].encode('utf-8'))
    if size > args.max_output_mb*1024*1024: raise SystemExit('planned output too large')
    changes=changed_files(plan)
    if args.apply:
        for p,c in plan.items():
            if read(p)!=c: write(p,c)
    labels_ok=all((r['label'].startswith(r['country']) and r['bmrsCode'] in r['label'] and r['directionLabel'] in r['label']) for r in rows)
    checks={'target_route_is_live_v6': f'permalink: {ROUTE}' in plan[INDEX], 'mwh_panel_present': 'Generation output in MWh' in plan[INDEX], 'legacy_imports_exports_hidden_in_renderer': "var HIDDEN={'Imports & Exports':true};" in plan[RENDER], 'legacy_imports_exports_removed_from_dropdown': ".filter(function(t){return !HIDDEN[t]})" in plan[CONTROL], 'interconnector_json_loader_added': 'generation_  … [line shortened here: 1,054 characters; full line on GitHub]
    summary={'outputPath':rel(OUT),'outputRows':len(rows),'outputSizeBytes':size,'latestYear':max([r['year'] for r in rows], default=0)}
    report={'reportTitle':'Generation MWh Interconnector Split V6','schemaVersion':'1.0.0','generatedUTC':now(),'mode':mode,'repository':'Ventusltd/globalgrid2050','route':ROUTE,'directionConvention':'positive signed MW = import to GB; negative signed MW = export from GB','labelContract':'country — interconnector name — BMRS code — direction','changedFiles':changes if args.apply else [],'plannedCh  … [line shortened here: 697 characters; full line on GitHub]
    REPORT.mkdir(parents=True,exist_ok=True); REPORT_JSON.mkdir(parents=True,exist_ok=True)
    write(JS,json.dumps(report,indent=2,ensure_ascii=False)+'\n'); write(MD,make_report(report))
    print(json.dumps(report,indent=2,ensure_ascii=False))
    return 0 if report['pass'] else 1

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