GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Electricity markets and data pipelines / globalgrid2050 / scripts

GlobalGrid2050 Fetch Generation MW Year Staged and 1 more file

A Python command-line tool in the scripts folder that fetches solar from Elexon Balancing Mechanism Reporting Service (BMRS).

636 lines of Python from globalgrid2050, in 2 files. Topic: Electricity markets and data pipelines. Section 875 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 Download Ons MWh Energy Use V6 energy-data · globalgrid2050 / scripts/download_ons_mwh_energy_use_v6.py lines 1–241
  2. GlobalGrid2050 Fetch Generation MW Year Staged energy-data · globalgrid2050 / scripts/fetch_generation_mw_year_staged.py lines 1–395

GlobalGrid2050 Download Ons MWh Energy Use V6

A Python command-line tool in the scripts folder that fetches 11energyusebyindustrysourceandfuel, ons mwh energy use annual, ons mwh summary top uses and ons mwh summary by fuel.

energy-dataglobalgrid2050 / scripts/download_ons_mwh_energy_use_v6.py · lines 1–241 of 241 · Entry point · pattern parse_float (shared by 6 files)

What it does
It fetches 11energyusebyindustrysourceandfuel, ons mwh energy use annual, ons mwh summary top uses and ons mwh summary by fuel. Defines 16 functions or classes, including utc_now, col_to_num, cell_col, cell_row, download_workbook. Uses libraries json, re, urllib.request, zipfile, xml.etree.ElementTree. Side effects: reads or writes files; makes network requests.
Why it exists in the grid workflow
Domain stage upstream_foresight (topic 'markets-data'): 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: Excel file 11energyusebyindustrysourceandfuel.xlsx; JSON file ons_mwh_energy_use_annual.json; JSON file ons_mwh_summary_top_uses_latest.json; JSON file ons_mwh_summary_by_fuel.json.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Ons MWh Energy Use Annual V6 Workflow (globalgrid2050).
What it achieves
It downloads workbook (`download_workbook`), loads shared strings (`load_shared_strings`) and reads sheet (`read_sheet`). Defines `utc_now`, `col_to_num`, `cell_col` and 12 more.
Why it matters
Run by GlobalGrid2050 Ons MWh Energy Use Annual V6 Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
json, re, urllib.request, zipfile, xml.etree.ElementTree, collections, datetime, pathlib
Used by
run by GlobalGrid2050 Ons MWh Energy Use Annual V6 Workflow (workflow run)
Produces
utc_now, col_to_num, cell_col, cell_row, download_workbook, load_shared_strings, workbook_sheets, cell_value, read_sheet, normalise_header, find_data_table, get_field
Defines here
utc_now, col_to_num, cell_col, cell_row, download_workbook, load_shared_strings, workbook_sheets, cell_value, read_sheet, normalise_header, find_data_table, get_field, parse_float, parse_workbook, write_outputs, 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/download_ons_mwh_energy_use_v6.py:1-241 · blob 2b8a61248aad65d477814a42d9524566a3907cda · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import json
import re
import urllib.request
import zipfile
import xml.etree.ElementTree as ET
from collections import defaultdict
from datetime import datetime, timezone
from pathlib import Path

ONS_XLSX_URL = 'https://www.ons.gov.uk/file?uri=/economy/environmentalaccounts/datasets/ukenvironmentalaccountsenergyusebyindustrysourceandfuel/current/11energyusebyindustrysourceandfuel.xlsx'
RAW_DIR = Path('data/ons')
RAW_XLSX = RAW_DIR / '11energyusebyindustrysourceandfuel.xlsx'
OUT_DIR = Path('uk_energy_tracking_v6/generation_history/mwh_energy_use')
ANNUAL_JSON = OUT_DIR / 'ons_mwh_energy_use_annual.json'
TOP_JSON = OUT_DIR / 'ons_mwh_summary_top_uses_latest.json'
FUEL_JSON = OUT_DIR / 'ons_mwh_summary_by_fuel.json'
REPORT_MD = OUT_DIR / 'ONS_MWH_ENERGY_USE_REPORT.md'
MTOE_TO_TWH = 11.63
TWH_TO_MWH = 1_000_000
NS = {'a': 'http://schemas.openxmlformats.org/spreadsheetml/2006/main', 'r': 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'}
REL_NS = {'rel': 'http://schemas.openxmlformats.org/package/2006/relationships'}


def utc_now():
    return datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z')


def col_to_num(col):
    n = 0
    for ch in col:
        n = n * 26 + (ord(ch.upper()) - 64)
    return n


def cell_col(ref):
    m = re.match(r'([A-Z]+)', ref or '')
    return col_to_num(m.group(1)) if m else 0


def cell_row(ref):
    m = re.search(r'(\d+)$', ref or '')
    return int(m.group(1)) if m else 0


def download_workbook():
    RAW_DIR.mkdir(parents=True, exist_ok=True)
    req = urllib.request.Request(ONS_XLSX_URL, headers={'User-Agent': 'GlobalGrid2050 open data pipeline'})
    with urllib.request.urlopen(req, timeout=120) as response:
        RAW_XLSX.write_bytes(response.read())
    print(f'Downloaded {RAW_XLSX} ({RAW_XLSX.stat().st_size} bytes)')


def load_shared_strings(zf):
    try:
        root = ET.fromstring(zf.read('xl/sharedStrings.xml'))
    except KeyError:
        return []
    out = []
    for si in root.findall('a:si', NS):
        text = ''.join(t.text or '' for t in si.findall('.//a:t', NS))
        out.append(text)
    return out


def workbook_sheets(zf):
    wb = ET.fromstring(zf.read('xl/workbook.xml'))
    rels = ET.fromstring(zf.read('xl/_rels/workbook.xml.rels'))
    rel_map = {rel.attrib['Id']: rel.attrib['Target'] for rel in rels.findall('rel:Relationship', REL_NS)}
    sheets = []
    for sheet in wb.findall('.//a:sheet', NS):
        rid = sheet.attrib.get('{http://schemas.openxmlformats.org/officeDocument/2006/relationships}id')
        target = rel_map.get(rid, '')
        if target and not target.startswith('xl/'):
            target = 'xl/' + target
        sheets.append((sheet.attrib.get('name', ''), target))
    return sheets


def cell_value(cell, shared):
    t = cell.attrib.get('t')
    if t == 'inlineStr':
        return ''.join(x.text or '' for x in cell.findall('.//a:t', NS)).strip()
    v = cell.find('a:v', NS)
    if v is None:
        return ''
    raw = v.text or ''
    if t == 's':
        try:
            return shared[int(raw)].strip()
        except Exception:
            return ''
    return raw.strip()


def read_sheet(zf, path, shared):
    root = ET.fromstring(zf.read(path))
    rows = []
    for row in root.findall('.//a:sheetData/a:row', NS):
        values = {}
        for cell in row.findall('a:c', NS):
            ref = cell.attrib.get('r', '')
            values[cell_col(ref)] = cell_value(cell, shared)
        if values:
            rows.append((int(row.attrib.get('r', cell_row(next(iter(values), 0)) or 0)), values))
    return rows


def normalise_header(value):
    return re.sub(r'\s+', ' ', str(value or '').strip()).lower()


def find_data_table(rows):
    for row_num, values in rows:
        headers = {normalise_header(v): c for c, v in values.items()}
        if 'economic sector' in headers and 'sourcename' in headers:
            years = {}
            for col, value in values.items():
                s = str(value).strip()
                if re.fullmatch(r'19\d{2}|20\d{2}', s):
                    years[int(s)] = col
            if years:
                return row_num, values, years
    return None, None, None


def get_field(row, header_map, names):
    for name in names:
        col = header_map.get(name)
        if col:
            return str(row.get(col, '')).strip()
    return ''


def parse_float(value):
    try:
        if value in (None, ''):
            return None
        return float(str(value).replace(',', ''))
    except Exception:
        return None


def parse_workbook():
    records = []
    source_sheet = None
    with zipfile.ZipFile(RAW_XLSX) as zf:
        shared = load_shared_strings(zf)
        for sheet_name, path in workbook_sheets(zf):
            if not path or not path.endswith('.xml'):
                continue
            rows = read_sheet(zf, path, shared)
            header_row, header_values, years = find_data_table(rows)
            if not header_row:
                continue
            source_sheet = sheet_name
            header_map = {normalise_header(v): c for c, v in header_values.items()}
            for row_num, row in rows:
                if row_num <= header_row:
                    continue
                economic_sector = get_field(row, header_map, ['economic sector'])
                source_name = get_field(row, header_map, ['sourcename', 'source name'])
                activity_name = get_field(row, header_map, ['activity name', 'activityname'])
                fuel = get_field(row, header_map, ['fuel', 'fuel type', 'activityname'])
                subsection = get_field(row, header_map, ['subsection'])
                if not any([economic_sector, source_name, activity_name, fuel]):
                    continue
                for year, col in sorted(years.items()):
                    mtoe = parse_float(row.get(col))
                    if mtoe is None:
                        continue
                    twh = mtoe * MTOE_TO_TWH
                    records.append({
                        'year': year,
                        'subsection': subsection,
                        'economicSector': economic_sector,
                        'sourceName': source_name,
                        'activityName': activity_name,
                        'fuel': fuel,
                        'mtoe': round(mtoe, 6),
                        'twh': round(twh, 6),
                        'mwh': round(twh * TWH_TO_MWH, 3),
                        'sourceDataset': 'ONS Energy use by industry, source and fuel',
                    })
            break
    return source_sheet, records


def write_outputs(sheet, records):
    OUT_DIR.mkdir(parents=True, exist_ok=True)
    latest_year = max((r['year'] for r in records), default=None)
    total_by_year = defaultdict(float)
    by_fuel = defaultdict(float)
    for r in records:
        total_by_year[r['year']] += r['mwh']
        by_fuel[(r['year'], r['fuel'])] += r['mwh']
    latest_rows = [r for r in records if r['year'] == latest_year]
    latest_top = sorted(latest_rows, key=lambda r: r['mwh'], reverse=True)[:25]
    fuel_rows = [{'year': y, 'fuel': fuel, 'mwh': round(mwh, 3), 'twh': round(mwh / TWH_TO_MWH, 6)} for (y, fuel), mwh in sorted(by_fuel.items())]
    base = {
        'generatedUTC': utc_now(),
        'sourceUrl': ONS_XLSX_URL,
        'sourceWorkbook': str(RAW_XLSX),
        'sourceSheet': sheet,
        'conversion': {'mtoeToTwh': MTOE_TO_TWH, 'twhToMwh': TWH_TO_MWH, 'formula': 'MWh = Mtoe * 11.63 * 1000000'},
    }
    ANNUAL_JSON.write_text(json.dumps({**base, 'rows': records}, indent=2), encoding='utf-8')
    TOP_JSON.write_text(json.dumps({**base, 'latestYear': latest_year, 'rows': latest_top}, indent=2), encoding='utf-8')
    FUEL_JSON.write_text(json.dumps({**base, 'rows': fuel_rows}, indent=2), encoding='utf-8')
    total_twh = total_by_year.get(latest_year, 0) / TWH_TO_MWH if latest_year else 0
    REPORT_MD.write_text('\n'.join([
        '# ONS MWh Energy Use Report',
        '',
        f'Generated UTC: {base["generatedUTC"]}',
        f'Source workbook: {ONS_XLSX_URL}',
        f'Source sheet: {sheet}',
        f'Records: {len(records)}',
        f'Latest year: {latest_year}',
        f'Latest year total TWh: {total_twh:,.1f}',
        '',
        '## Outputs',
        '',
        f'- `{ANNUAL_JSON}`',
        f'- `{TOP_JSON}`',
        f'- `{FUEL_JSON}`',
    ]) + '\n', encoding='utf-8')
    print(f'Wrote {ANNUAL_JSON}')
    print(f'Wrote {TOP_JSON}')
    print(f'Wrote {FUEL_JSON}')
    print(f'Wrote {REPORT_MD}')


def main():
    download_workbook()
    sheet, records = parse_workbook()
    if not records:
        raise RuntimeError('No ONS energy use records parsed from workbook')
    write_outputs(sheet, records)


if __name__ == '__main__':
    main()

GlobalGrid2050 Fetch Generation MW Year Staged

A Python command-line tool in the scripts folder that fetches solar from Elexon Balancing Mechanism Reporting Service (BMRS).

energy-dataglobalgrid2050 / scripts/fetch_generation_mw_year_staged.py · lines 1–395 of 395 · Entry point · pattern fetch_elexon_day (shared by 2 files)

What it does
It fetches solar. Defines 19 functions or classes, including utc_now, stamp, iso_z, pick, num. Uses libraries __future__, argparse, csv, datetime, json. Side effects: 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. Domain terms in the code: solar.
Inputs & outputs
In: data source: Elexon BMRS; command-line arguments.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Overnight Generation MW Backfill Workflow (globalgrid2050).
What it achieves
It extracts rows (`extract_rows`), fetches Elexon day (`fetch_elexon_day`) and parses pvlive row (`parse_pvlive_row`). Fetches one year of generation source rows through public APIs, writes staged files under a per year directory and keeps each committed data file below the configured size threshold where practical. It accepts `--year`, `--delay-seconds` and `--max-file-mb`.
Why it matters
Run by GlobalGrid2050 Overnight Generation MW Backfill Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
__future__, argparse, csv, datetime, json, time, urllib.parse, urllib.request
Used by
run by GlobalGrid2050 Overnight Generation MW Backfill Workflow (workflow run)
Produces
utc_now, stamp, iso_z, pick, num, http_json, extract_rows, elexon_url, fetch_elexon_day, pvlive_urls, parse_pvlive_row, fetch_pvlive_day
Defines here
utc_now, stamp, iso_z, pick, num, http_json, extract_rows, elexon_url, fetch_elexon_day, pvlive_urls, parse_pvlive_row, fetch_pvlive_day, year_dir, load_existing_rows, existing_days, write_csv, write_year_files, write_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/fetch_generation_mw_year_staged.py:1-395 · blob 8b52aa8c3b58f44638fd46b0463bbc2deaf79b21 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
"""
GlobalGrid2050 staged generation MW fetcher.

Fetches one year of generation source rows through public APIs, writes staged files
under a per year directory and keeps each committed data file below the configured
size threshold where practical.

This is intentionally a source staging tool. The browser should consume the daily
MW spine generated from these staged rows, not the raw staged source files.
"""

from __future__ import annotations

import argparse
import csv
import datetime as dt
import json
import time
import urllib.parse
import urllib.request
from collections import defaultdict
from pathlib import Path
from typing import Any

ROOT = Path(__file__).resolve().parent.parent
STAGE_ROOT = ROOT / "data" / "generation" / "staged_mw"
REPORT_DIR = ROOT / "data_science_protocol" / "audit_reports"
REPORT_JSON_DIR = REPORT_DIR / "json"

ELEXON_FUELINST = "https://data.elexon.co.uk/bmrs/api/v1/datasets/FUELINST"
PVLIVE_GSP0 = "https://api.solar.sheffield.ac.uk/pvlive/api/v4/gsp/0"

FIELDS = [
    "source",
    "periodStartUTC",
    "fuelType",
    "generationMW",
    "publishTimeUTC",
    "fetchedAtUTC",
    "sourceStatus",
    "sourceLineage",
]


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


def stamp() -> str:
    return dt.datetime.now(dt.timezone.utc).strftime("%Y%m%dT%H%M%SZ")


def iso_z(value: Any) -> str:
    if value in (None, ""):
        return ""
    text = str(value).replace("Z", "+00:00")
    try:
        parsed = dt.datetime.fromisoformat(text)
        if parsed.tzinfo is None:
            parsed = parsed.replace(tzinfo=dt.timezone.utc)
        return parsed.astimezone(dt.timezone.utc).isoformat().replace("+00:00", "Z")
    except Exception:
        return str(value)


def pick(row: dict[str, Any], names: list[str]) -> Any:
    folded = {str(k).lower(): v for k, v in row.items()}
    for name in names:
        value = folded.get(name.lower())
        if value not in (None, ""):
            return value
    return ""


def num(value: Any) -> str | None:
    if value in (None, ""):
        return None
    try:
        return f"{float(value):.3f}"
    except Exception:
        return None


def http_json(url: str, timeout: int = 60) -> Any:
    req = urllib.request.Request(url, headers={"User-Agent": "GlobalGrid2050 GridBot"})
    with urllib.request.urlopen(req, timeout=timeout) as response:
        return json.loads(response.read().decode("utf-8"))


def extract_rows(payload: Any) -> list[Any]:
    if isinstance(payload, list):
        return payload
    if isinstance(payload, dict):
        for key in ("data", "results", "items"):
            value = payload.get(key)
            if isinstance(value, list):
                return value
    return []


def elexon_url(start_dt: dt.datetime, end_dt: dt.datetime) -> str:
    query = urllib.parse.urlencode({
        "publishDateTimeFrom": start_dt.strftime("%Y-%m-%dT%H:%MZ"),
        "publishDateTimeTo": end_dt.strftime("%Y-%m-%dT%H:%MZ"),
        "format": "json",
    })
    return f"{ELEXON_FUELINST}?{query}"


def fetch_elexon_day(day: dt.date) -> list[dict[str, str]]:
    start_dt = dt.datetime.combine(day, dt.time(0, 0), tzinfo=dt.timezone.utc)
    end_dt = dt.datetime.combine(day, dt.time(23, 59), tzinfo=dt.timezone.utc)
    payload = http_json(elexon_url(start_dt, end_dt))
    fetched = utc_now()
    out: list[dict[str, str]] = []
    for row in extract_rows(payload):
        if not isinstance(row, dict):
            continue
        fuel = pick(row, ["fuelType", "fuelTypeName", "fuel", "psrType"])
        generation = pick(row, ["generation", "generationMW", "currentUsage", "quantity"])
        period_start = pick(row, ["startTime", "publishDateTime", "periodStartUTC", "settlementDate"])
        publish_time = pick(row, ["publishDateTime", "publishTime", "createdTime"])
        mw = num(generation)
        if not fuel or mw is None or not period_start:
            continue
        out.append({
            "source": "Elexon BMRS FUELINST",
            "periodStartUTC": iso_z(period_start),
            "fuelType": str(fuel).strip().upper(),
            "generationMW": mw,
            "publishTimeUTC": iso_z(publish_time),
            "fetchedAtUTC": fetched,
            "sourceStatus": "provisional",
            "sourceLineage": "FUELINST LIVE OR RECENT PROVISIONAL",
        })
    return out


def pvlive_urls(start_dt: dt.datetime, end_dt: dt.datetime) -> list[str]:
    start_iso = start_dt.isoformat().replace("+00:00", "Z")
    end_iso = end_dt.isoformat().replace("+00:00", "Z")
    start_plain = start_dt.strftime("%Y-%m-%dT%H:%M:%SZ")
    end_plain = end_dt.strftime("%Y-%m-%dT%H:%M:%SZ")
    start_date = start_dt.date().isoformat()
    end_date = end_dt.date().isoformat()
    params = [
        {"start": start_iso, "end": end_iso},
        {"start": start_plain, "end": end_plain},
        {"from": start_iso, "to": end_iso},
        {"datetime_from": start_iso, "datetime_to": end_iso},
        {"start_date": start_date, "end_date": end_date},
    ]
    return [PVLIVE_GSP0 + "?" + urllib.parse.urlencode(p) for p in params]


def parse_pvlive_row(row: Any, fetched: str) -> dict[str, str] | None:
    if isinstance(row, list):
        if len(row) < 3:
            return None
        timestamp = row[1]
        generation = row[2]
    elif isinstance(row, dict):
        timestamp = row.get("datetime_gmt") or row.get("datetime") or row.get("time") or row.get("timestamp") or row.get("periodStartUTC")
        generation = row.get("generation_mw") or row.get("generationMW") or row.get("generation") or row.get("power")
    else:
        return None
    mw = num(generation)
    period_start = iso_z(timestamp)
    if not period_start or mw is None:
        return None
    return {
        "source": "Sheffield Solar PVLive",
        "periodStartUTC": period_start,
        "fuelType": "SOLAR",
        "generationMW": mw,
        "publishTimeUTC": "",
        "fetchedAtUTC": fetched,
        "sourceStatus": "candidate",
        "sourceLineage": "PVLIVE EMBEDDED ESTIMATE",
    }


def fetch_pvlive_day(day: dt.date) -> tuple[list[dict[str, str]], str, str]:
    start_dt = dt.datetime.combine(day, dt.time(0, 0), tzinfo=dt.timezone.utc)
    end_dt = dt.datetime.combine(day, dt.time(23, 59), tzinfo=dt.timezone.utc)
    errors: list[str] = []
    for url in pvlive_urls(start_dt, end_dt):
        try:
            payload = http_json(url)
            fetched = utc_now()
            rows = []
            for row in extract_rows(payload):
                parsed = parse_pvlive_row(row, fetched)
                if parsed:
                    rows.append(parsed)
            if rows:
                return rows, "ok", url
        except Exception as exc:
            errors.append(str(exc))
    return [], "; ".join(errors[-2:]) or "no parseable PVLive rows", ""


def year_dir(year: int) -> Path:
    return STAGE_ROOT / str(year)


def load_existing_rows(year: int) -> dict[tuple[str, str], dict[str, str]]:
    rows: dict[tuple[str, str], dict[str, str]] = {}
    for path in sorted(year_dir(year).glob("*.csv")):
        with path.open("r", encoding="utf-8", newline="") as handle:
            for row in csv.DictReader(handle):
                key = (row.get("periodStartUTC", ""), row.get("fuelType", ""))
                if key[0] and key[1]:
                    rows[key] = {field: row.get(field, "") for field in FIELDS}
    return rows


def existing_days(rows: dict[tuple[str, str], dict[str, str]]) -> set[str]:
    days = set()
    for period, _fuel in rows:
        if period:
            days.add(period[:10])
    return days


def write_csv(path: Path, rows: list[dict[str, str]]) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    with path.open("w", encoding="utf-8", newline="") as handle:
        writer = csv.DictWriter(handle, fieldnames=FIELDS)
        writer.writeheader()
        writer.writerows(rows)


def write_year_files(year: int, rows_by_key: dict[tuple[str, str], dict[str, str]], max_file_mb: float) -> list[dict[str, Any]]:
    ydir = year_dir(year)
    ydir.mkdir(parents=True, exist_ok=True)
    rows = [rows_by_key[k] for k in sorted(rows_by_key, key=lambda x: (x[0], x[1]))]
    annual = ydir / f"generation_mw_source_{year}.csv"
    write_csv(annual, rows)
    max_bytes = int(max_file_mb * 1024 * 1024)
    outputs: list[dict[str, Any]] = []
    if annual.stat().st_size <= max_bytes:
        for old in ydir.glob(f"generation_mw_source_{year}-*.csv"):
            old.unlink()
        outputs.append({"path": annual.relative_to(ROOT).as_posix(), "rows": len(rows), "sizeBytes": annual.stat().st_size})
        return outputs

    annual.unlink()
    by_month: dict[str, list[dict[str, str]]] = defaultdict(list)
    for row in rows:
        month = row.get("periodStartUTC", "")[:7]
        if month:
            by_month[month].append(row)
    for old in ydir.glob(f"generation_mw_source_{year}*.csv"):
        old.unlink()
    for month, month_rows in sorted(by_month.items()):
        mpath = ydir / f"generation_mw_source_{month}.csv"
        write_csv(mpath, month_rows)
        outputs.append({"path": mpath.relative_to(ROOT).as_posix(), "rows": len(month_rows), "sizeBytes": mpath.stat().st_size})
    return outputs


def write_report(payload: dict[str, Any]) -> None:
    REPORT_DIR.mkdir(parents=True, exist_ok=True)
    REPORT_JSON_DIR.mkdir(parents=True, exist_ok=True)
    year = payload["year"]
    s = stamp()
    md = REPORT_DIR / f"GENERATION_MW_FETCH_{year}_{s}.md"
    js = REPORT_JSON_DIR / f"GENERATION_MW_FETCH_{year}_{s}.json"
    latest_md = REPORT_DIR / f"GENERATION_MW_FETCH_{year}_LATEST.md"
    latest_js = REPORT_JSON_DIR / f"GENERATION_MW_FETCH_{year}_LATEST.json"
    lines = [
        f"# GlobalGrid2050 Generation MW Source Fetch {year}",
        "",
        f"Generated UTC: `{payload['generatedUTC']}`",
        f"Mode: `{payload['mode']}`",
        f"Year: `{year}`",
        f"Window: `{payload['startDay']}` to `{payload['endDay']}`",
        f"Rows before: `{payload['rowsBefore']}`",
        f"Rows after: `{payload['rowsAfter']}`",
        f"Elexon rows fetched: `{payload['elexonRowsFetched']}`",
        f"PVLive rows fetched: `{payload['solarRowsFetched']}`",
        f"Days attempted: `{payload['daysAttempted']}`",
        f"Days skipped because already staged: `{payload['daysSkippedExisting']}`",
        f"Errors: `{len(payload['errors'])}`",
        f"Max file MB: `{payload['maxFileMB']}`",
        "",
        "## Outputs",
        "",
    ]
    for item in payload["outputs"]:
        lines.append(f"{item['path']}  rows={item['rows']}  sizeBytes={item['sizeBytes']}")
    if payload["errors"]:
        lines.extend(["", "## Errors", ""])
        for item in payload["errors"][:60]:
            lines.append(f"{item['day']}  {item['source']}  {item['error']}")
    lines.extend(["", "## Source discipline", "", "FUELINST rows are provisional. PVLive solar rows are candidate embedded estimates. Browser views must use compact daily facts generated from these staged rows."])
    text = "\n".join(lines) + "\n"
    for path in (md, latest_md):
        path.write_text(text, encoding="utf-8")
    js_text = json.dumps(payload, indent=2, ensure_ascii=False) + "\n"
    for path in (js, latest_js):
        path.write_text(js_text, encoding="utf-8")


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--year", type=int, required=True)
    parser.add_argument("--delay-seconds", type=float, default=0.25)
    parser.add_argument("--max-file-mb", type=float, default=25.0)
    parser.add_argument("--include-solar", action="store_true")
    parser.add_argument("--refetch-existing", action="store_true")
    parser.add_argument("--apply", action="store_true")
    args = parser.parse_args()

    now = dt.datetime.now(dt.timezone.utc)
    current_year = now.year
    current_date = now.date()
    start_day = dt.date(args.year, 1, 1)
    end_day = dt.date(args.year, 12, 31)
    if args.year == current_year:
        end_day = min(end_day, current_date - dt.timedelta(days=1))
    if end_day < start_day:
        payload = {"generatedUTC": utc_now(), "mode": "apply" if args.apply else "audit only", "year": args.year, "startDay": str(start_day), "endDay": str(end_day), "rowsBefore": 0, "rowsAfter": 0, "elexonRowsFetched": 0, "solarRowsFetched": 0, "daysAttempted": 0, "daysSkippedExisting": 0, "maxFileMB": args.max_file_mb, "outputs": [], "errors": [{"day": str(start_day), "source": "calendar", "erro  … [line shortened here: 435 characters; full line on GitHub]
        write_report(payload)
        return 0

    rows_by_key = load_existing_rows(args.year)
    before = len(rows_by_key)
    staged_days = existing_days(rows_by_key)
    elexon_count = 0
    solar_count = 0
    attempted = 0
    skipped = 0
    errors: list[dict[str, str]] = []

    day = start_day
    while day <= end_day:
        day_text = day.isoformat()
        if day_text in staged_days and not args.refetch_existing:
            skipped += 1
            day += dt.timedelta(days=1)
            continue
        attempted += 1
        if args.apply:
            try:
                rows = fetch_elexon_day(day)
                elexon_count += len(rows)
                for row in rows:
                    rows_by_key[(row["periodStartUTC"], row["fuelType"])] = row
                print(f"{args.year} {day}: Elexon {len(rows)} rows")
            except Exception as exc:
                errors.append({"day": day_text, "source": "Elexon FUELINST", "error": str(exc)})
                print(f"Warning {args.year} {day}: Elexon failed: {exc}")
            if args.include_solar:
                try:
                    solar_rows, status, _url = fetch_pvlive_day(day)
                    solar_count += len(solar_rows)
                    for row in solar_rows:
                        rows_by_key[(row["periodStartUTC"], row["fuelType"])] = row
                    if not solar_rows and status:
                        errors.append({"day": day_text, "source": "PVLive", "error": status})
                    print(f"{args.year} {day}: PVLive solar {len(solar_rows)} rows")
                except Exception as exc:
                    errors.append({"day": day_text, "source": "PVLive", "error": str(exc)})
                    print(f"Warning {args.year} {day}: PVLive failed: {exc}")
            time.sleep(max(args.delay_seconds, 0))
        day += dt.timedelta(days=1)

    outputs: list[dict[str, Any]] = []
    if args.apply:
        outputs = write_year_files(args.year, rows_by_key, args.max_file_mb)
    payload = {
        "generatedUTC": utc_now(),
        "mode": "apply" if args.apply else "audit only",
        "year": args.year,
        "startDay": str(start_day),
        "endDay": str(end_day),
        "rowsBefore": before,
        "rowsAfter": len(rows_by_key),
        "elexonRowsFetched": elexon_count,
        "solarRowsFetched": solar_count,
        "daysAttempted": attempted,
        "daysSkippedExisting": skipped,
        "maxFileMB": args.max_file_mb,
        "outputs": outputs,
        "errors": errors,
    }
    write_report(payload)
    return 0


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