GLOBALGRID2050 / EXPLORE CODE

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

GlobalGrid2050 Build Generation Ecg All Tech Mvp and 2 more files

A Python command-line tool in the scripts folder that builds tech ecg (`build_all_tech_ecg`), loads recent ecg rows (`load_recent_ecg_rows`) and renders report (`render_report`) (units: MW).

407 lines of Python from globalgrid2050, in 3 files. Topic: Electricity markets and data pipelines. Section 867 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 Build Generation Daily MW Spine from Fuelhh energy-data · globalgrid2050 / scripts/build_generation_daily_mw_spine_from_fuelhh.py lines 1–75
  2. GlobalGrid2050 Build Generation Daily MWh Fuelhh Chunks energy-data · globalgrid2050 / scripts/build_generation_daily_mwh_fuelhh_chunks.py lines 1–146
  3. GlobalGrid2050 Build Generation Ecg All Tech Mvp energy-data · globalgrid2050 / scripts/build_generation_ecg_all_tech_mvp.py lines 1–186

GlobalGrid2050 Build Generation Daily MW Spine from Fuelhh

A Python command-line tool in the scripts folder that parses time, reads rows and writes report, covering generation daily mw spine fuelhh candidate and fuelhh daily mw spine.

energy-dataglobalgrid2050 / scripts/build_generation_daily_mw_spine_from_fuelhh.py · lines 1–75 of 75 · Entry point · pattern build_spine (shared by 3 files)

What it does
Defines 8 functions or classes, including utc_now, stamp, parse_time, read_rows, build_spine. Uses libraries __future__, argparse, csv, datetime, json. Side effects: reads or writes files.
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_daily_mw_spine_fuelhh_candidate.json; command-line arguments. Out: JSON file FUELHH_DAILY_MW_SPINE_LATEST.json.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Backfill Generation Fuelhh Halfhourly V6 Workflow (globalgrid2050).
What it achieves
It reads rows (`read_rows`) and builds spine (`build_spine`). Defines `utc_now`, `stamp`, `parse_time` and 4 more. It accepts `--start-year-month` and `--apply`.
Why it matters
Run by GlobalGrid2050 Backfill Generation Fuelhh Halfhourly V6 Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
__future__, argparse, csv, datetime, json, math, collections, pathlib
Used by
run by GlobalGrid2050 Backfill Generation Fuelhh Halfhourly V6 Workflow (workflow run)
Produces
utc_now, stamp, parse_time, read_rows, build_spine, write_json, write_report, main
Defines here
utc_now, stamp, parse_time, read_rows, build_spine, write_json, 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/build_generation_daily_mw_spine_from_fuelhh.py:1-75 · blob 6f20c4842af9f19c3a42d0c5f5f846fb17a14de6 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem · 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
from collections import defaultdict
from pathlib import Path
from typing import Any

ROOT=Path(__file__).resolve().parent.parent
SOURCE_ROOT=ROOT/'data'/'generation'/'fuelhh_halfhourly'
OUT_FILE=ROOT/'data'/'confirmed'/'generation_daily_mw_spine_fuelhh_candidate.json'
REPORT_DIR=ROOT/'data_science_protocol'/'audit_reports'
REPORT_JSON_DIR=REPORT_DIR/'json'

def utc_now(): return dt.datetime.now(dt.timezone.utc).isoformat().replace('+00:00','Z')
def stamp(): return dt.datetime.now(dt.timezone.utc).strftime('%Y%m%dT%H%M%SZ')

def parse_time(value:str):
    if not value: return None
    try:
        p=dt.datetime.fromisoformat(value.replace('Z','+00:00'))
        if p.tzinfo is None: p=p.replace(tzinfo=dt.timezone.utc)
        return p.astimezone(dt.timezone.utc)
    except Exception:
        return None

def read_rows(start_year_month:str):
    buckets=defaultdict(list); source_files=[]; raw_rows=0; parsed_rows=0
    for path in sorted(SOURCE_ROOT.glob('*/*.csv')):
        if 'generation_fuelhh_' not in path.name: continue
        suffix=path.name.replace('generation_fuelhh_','').replace('.csv','')
        parts=suffix.split('_')
        if len(parts)>=2 and f'{parts[0]}-{parts[1]}' < start_year_month: continue
        file_rows=0
        with path.open('r',encoding='utf-8',newline='') as handle:
            for row in csv.DictReader(handle):
                raw_rows+=1; file_rows+=1
                t=parse_time(row.get('time',''))
                try: mw=float(row.get('generationMW',''))
                except Exception: continue
                tech=row.get('technology','') or 'Other'
                if t is None or not math.isfinite(mw): continue
                buckets[(t.date().isoformat(),tech)].append({'time':t.isoformat().replace('+00:00','Z'),'mw':mw})
                parsed_rows+=1
        source_files.append({'path':path.relative_to(ROOT).as_posix(),'rows':file_rows,'sizeBytes':path.stat().st_size})
    return buckets, {'files':source_files,'rawRows':raw_rows,'parsedRows':parsed_rows}

def build_spine(buckets):
    out=[]
    for (date,tech), points in sorted(buckets.items()):
        vals=[float(p['mw']) for p in points]
        if not vals: continue
        hi=max(points,key=lambda p:float(p['mw'])); lo=min(points,key=lambda p:float(p['mw']))
        out.append({'date':date,'technology':tech,'averageMW':round(sum(vals)/len(vals),3),'highMW':round(float(hi['mw']),3),'lowMW':round(float(lo['mw']),3),'highAtUTC':hi['time'],'lowAtUTC':lo['time'],'sampleCount':len(points),'expectedSamples':48,'completeness':round(min(1.0,len(points)/48),4),'status':'candidate','sourceStatus':'settled source candidate fact','sourceLineage':'Elexon BMRS FUELH  … [line shortened here: 404 characters; full line on GitHub]
    return out

def write_json(path,payload):
    path.parent.mkdir(parents=True,exist_ok=True)
    path.write_text(json.dumps(payload,indent=2,ensure_ascii=False)+'\n',encoding='utf-8')

def write_report(payload):
    REPORT_DIR.mkdir(parents=True,exist_ok=True); REPORT_JSON_DIR.mkdir(parents=True,exist_ok=True)
    s=stamp()
    text='\n'.join(['# GlobalGrid2050 FUELHH Daily MW Spine Report','',f"Generated UTC: `{payload['generatedUTC']}`",f"Mode: `{payload['mode']}`",f"Start year-month: `{payload['startYearMonth']}`",f"Source files: `{len(payload['sourceFiles'])}`",f"Raw rows: `{payload['rawRows']}`",f"Parsed rows: `{payload['parsedRows']}`",f"Daily fact rows: `{payload['dailyRows']}`",f"Output path: `{payload['outpu  … [line shortened here: 635 characters; full line on GitHub]
    for p in (REPORT_DIR/f'FUELHH_DAILY_MW_SPINE_{s}.md', REPORT_DIR/'FUELHH_DAILY_MW_SPINE_LATEST.md'): p.write_text(text,encoding='utf-8')
    js=json.dumps(payload,indent=2,ensure_ascii=False)+'\n'
    for p in (REPORT_JSON_DIR/f'FUELHH_DAILY_MW_SPINE_{s}.json', REPORT_JSON_DIR/'FUELHH_DAILY_MW_SPINE_LATEST.json'): p.write_text(js,encoding='utf-8')

def main():
    ap=argparse.ArgumentParser(); ap.add_argument('--start-year-month',default='2016-01'); ap.add_argument('--apply',action='store_true'); args=ap.parse_args()
    buckets,meta=read_rows(args.start_year_month); rows=build_spine(buckets)
    out={'schemaVersion':'0.1.0-fuelhh-candidate','generatedUTC':utc_now(),'title':'Generation daily MW spine from FUELHH candidate','timezone':'UTC','status':'candidate','grain':'daily average high low MW per technology','sourceNote':'Built from Elexon BMRS FUELHH monthly shards.','rows':rows}
    if args.apply: write_json(OUT_FILE,out)
    report={'generatedUTC':utc_now(),'mode':'apply' if args.apply else 'audit only','startYearMonth':args.start_year_month,'sourceFiles':meta['files'],'rawRows':meta['rawRows'],'parsedRows':meta['parsedRows'],'dailyRows':len(rows),'outputPath':OUT_FILE.relative_to(ROOT).as_posix(),'outputSizeBytes':OUT_FILE.stat().st_size if OUT_FILE.exists() else 0}
    write_report(report); return 0
if __name__=='__main__': raise SystemExit(main())

GlobalGrid2050 Build Generation Daily MWh Fuelhh Chunks

A Python command-line tool in the scripts folder that reads generation daily mwh by technology fuelhh and solar, using SHA-256. It parses time (`parse_time`) and writes JSON (`write_json`).

energy-dataglobalgrid2050 / scripts/build_generation_daily_mwh_fuelhh_chunks.py · lines 1–146 of 146 · Entry point · pattern source_files (shared by 4 files)

What it does
It loads generation daily mwh by technology fuelhh and solar. Defines 9 functions or classes, including now, stamp, rel, parse_time, file_year. Uses libraries __future__, argparse, csv, datetime, hashlib. Side effects: reads or writes files.
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: JSON file generation_daily_mwh_by_technology_fuelhh_index.json; command-line arguments.
Downstream impact
Used directly by 2 files: GlobalGrid2050 Gridbot Generation MWh Active V6 Source Audit (globalgrid2050); GlobalGrid2050 Gridbot Generation Daily MWh Fuelhh Chunks Workflow (globalgrid2050). Reached from 1 other entry point, including GlobalGrid2050 Gridbot Generation MWh Active V6 Source Audit Workflow (globalgrid2050).
What it achieves
Defines `now`, `stamp`, `rel` and 5 more. It accepts `--start-year`, `--end-year` and `--max-bytes`.
Why it matters
Run by GlobalGrid2050 Gridbot Generation MWh Active V6 Source Audit and GlobalGrid2050 Gridbot Generation Daily MWh Fuelhh Chunks Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
__future__, argparse, csv, datetime, hashlib, json, math, collections
Used by
run by GlobalGrid2050 Gridbot Generation MWh Active V6 Source Audit (script call), run by GlobalGrid2050 Gridbot Generation Daily MWh Fuelhh Chunks Workflow (workflow run)
Produces
now, stamp, rel, parse_time, file_year, source_files, build, write_json, main
Defines here
now, stamp, rel, parse_time, file_year, source_files, build, write_json, 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/build_generation_daily_mwh_fuelhh_chunks.py:1-146 · blob 7347cf0ad09880fbcb78dbec5ab6c6c302004f1d · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem · 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, hashlib, json, math
from collections import defaultdict
from pathlib import Path
from typing import Any

ROOT = Path(__file__).resolve().parent.parent
SRC = ROOT / 'data' / 'generation' / 'fuelhh_halfhourly'
OUT = ROOT / 'uk_energy_tracking_v6' / 'generation_history'
REPORT = ROOT / 'data_science_protocol' / 'audit_reports'
REPORT_JSON = REPORT / 'json'
STEM = 'GENERATION_DAILY_MWH_FUELHH_CHUNKS'
MAX_BYTES = 25_000_000

def 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 rel(p: Path) -> str:
    return p.relative_to(ROOT).as_posix()

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

def file_year(path: Path):
    s = path.name.replace('generation_fuelhh_','').replace('.csv','')
    parts = s.split('_')
    try:
        return int(parts[0])
    except Exception:
        return None

def source_files(start_year: int, end_year: int):
    files = []
    for p in sorted(SRC.glob('*/*.csv')):
        if not p.name.startswith('generation_fuelhh_'):
            continue
        y = file_year(p)
        if y is not None and start_year <= y <= end_year:
            files.append(p)
    return files

def build(start_year: int, end_year: int):
    buckets: dict[tuple[str,str], dict[str, Any]] = {}
    meta = []
    raw = parsed = skipped = 0
    for p in source_files(start_year, end_year):
        file_rows = file_parsed = 0
        with p.open('r', encoding='utf-8', newline='') as handle:
            reader = csv.DictReader(handle)
            for row in reader:
                raw += 1
                file_rows += 1
                t = parse_time(row.get('time',''))
                tech = (row.get('technology','') or 'Other').strip() or 'Other'
                try:
                    mw = float(row.get('generationMW',''))
                except Exception:
                    skipped += 1
                    continue
                if t is None or not math.isfinite(mw):
                    skipped += 1
                    continue
                day = t.date().isoformat()
                b = buckets.setdefault((day, tech), {'date': day, 'technology': tech, 'mwh': 0.0, 'sumMW': 0.0, 'records': 0, 'highMW': mw, 'lowMW': mw})
                b['mwh'] += mw * 0.5
                b['sumMW'] += mw
                b['records'] += 1
                b['highMW'] = max(float(b['highMW']), mw)
                b['lowMW'] = min(float(b['lowMW']), mw)
                parsed += 1
                file_parsed += 1
        meta.append({'path': rel(p), 'rows': file_rows, 'parsedRows': file_parsed, 'sizeBytes': p.stat().st_size})
    rows = []
    for b in buckets.values():
        n = int(b['records'])
        rows.append({'date': b['date'], 'technology': b['technology'], 'mwh': round(float(b['mwh']),3), 'averageMW': round(float(b['sumMW'])/n,3), 'highMW': round(float(b['highMW']),3), 'lowMW': round(float(b['lowMW']),3), 'records': n, 'expectedRecords': 48, 'completeness': round(n/48,4), 'source': 'Elexon BMRS FUELHH clean half hourly shard', 'methodState': 'Daily MWh equals sum of half hourly M  … [line shortened here: 421 characters; full line on GitHub]
    rows.sort(key=lambda r: (r['date'], r['technology']))
    return rows, meta, raw, parsed, skipped

def write_json(path: Path, payload: Any, compact: bool = False):
    path.parent.mkdir(parents=True, exist_ok=True)
    text = json.dumps(payload, separators=(',',':'), ensure_ascii=False) if compact else json.dumps(payload, indent=2, ensure_ascii=False) + '\n'
    path.write_text(text, encoding='utf-8')
    return path.stat().st_size, hashlib.sha256(text.encode('utf-8')).hexdigest()

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument('--start-year', type=int, required=True)
    ap.add_argument('--end-year', type=int, required=True)
    ap.add_argument('--max-bytes', type=int, default=MAX_BYTES)
    ap.add_argument('--apply', action='store_true')
    args = ap.parse_args()
    if args.end_year < args.start_year:
        raise SystemExit('end year must be greater than or equal to start year')
    rows, meta, raw, parsed, skipped = build(args.start_year, args.end_year)
    suffix = f"{args.start_year}_{args.end_year}" if args.start_year != args.end_year else str(args.start_year)
    out_path = OUT / f'generation_daily_mwh_by_technology_fuelhh_{suffix}.json'
    payload = {'schemaVersion':'1.0.0-fuelhh-daily-mwh','generatedUTC':now(),'title':'Generation daily MWh by technology from Elexon FUELHH','grain':'daily MWh by technology','unit':'MWh','timezone':'UTC','startYear':args.start_year,'endYear':args.end_year,'sourceNote':'Derived from clean Elexon FUELHH half hourly MW shards. Sheffield Solar PVLive daily MWh remains separate.','calculationMethod':'  … [line shortened here: 481 characters; full line on GitHub]
    text = json.dumps(payload, separators=(',',':'), ensure_ascii=False)
    size = len(text.encode('utf-8'))
    sha = hashlib.sha256(text.encode('utf-8')).hexdigest()
    if size > args.max_bytes:
        raise SystemExit(f'output too large: {size} bytes')
    if args.apply:
        out_path.parent.mkdir(parents=True, exist_ok=True)
        out_path.write_text(text, encoding='utf-8')
    index_path = OUT / 'generation_daily_mwh_by_technology_fuelhh_index.json'
    if args.apply:
        if index_path.exists():
            try:
                index = json.loads(index_path.read_text(encoding='utf-8'))
            except Exception:
                index = {}
        else:
            index = {}
        chunks = [c for c in index.get('chunks', []) if not (c.get('startYear') == args.start_year and c.get('endYear') == args.end_year)]
        chunks.append({'startYear':args.start_year,'endYear':args.end_year,'path':rel(out_path),'rows':len(rows),'sizeBytes':size})
        chunks.sort(key=lambda c: (c.get('startYear',0), c.get('endYear',0)))
        write_json(index_path, {'schemaVersion':'1.0.0-fuelhh-daily-mwh-index','generatedUTC':now(),'unit':'MWh','sourceNote':'Chunk index for Elexon derived daily MWh by technology. Solar PVLive is separate.','chunks':chunks})
    checks = {'source_files_found': len(meta)>0, 'raw_rows_positive': raw>0, 'parsed_rows_positive': parsed>0, 'output_rows_positive': len(rows)>0, 'output_under_25mb': size <= args.max_bytes, 'raw_halfhourly_not_written': True, 'solar_pvlive_not_mixed': True, 'formula_declared': True}
    report = {'reportTitle':'Generation Daily MWh FUELHH Chunks','schemaVersion':'1.0.0','generatedUTC':now(),'mode':'apply' if args.apply else 'audit','startYear':args.start_year,'endYear':args.end_year,'sourceRoot':rel(SRC),'sourceFileCount':len(meta),'sourceFiles':meta,'rawRows':raw,'parsedRows':parsed,'skippedRows':skipped,'outputPath':rel(out_path),'indexPath':rel(index_path),'outputRows':len  … [line shortened here: 706 characters; full line on GitHub]
    REPORT.mkdir(parents=True, exist_ok=True)
    REPORT_JSON.mkdir(parents=True, exist_ok=True)
    s = stamp()
    md = '\n'.join(['# Generation Daily MWh FUELHH Chunks','',f"Generated UTC: `{report['generatedUTC']}`",f"Mode: `{report['mode']}`",f"Window: `{args.start_year}` to `{args.end_year}`",f"Output path: `{rel(out_path)}`",f"Output rows: `{len(rows)}`",f"Output size bytes: `{size}`",f"Pass: `{report['pass']}`",'', 'Daily MWh equals sum of half hourly MW times 0.5 hours. Raw half hourly rows are not   … [line shortened here: 464 characters; full line on GitHub]
    for p in (REPORT / f'{STEM}_{s}.md', REPORT / f'{STEM}_LATEST.md'):
        p.write_text(md, encoding='utf-8')
    js = json.dumps(report, indent=2, ensure_ascii=False) + '\n'
    for p in (REPORT_JSON / f'{STEM}_{s}.json', REPORT_JSON / f'{STEM}_LATEST.json'):
        p.write_text(js, encoding='utf-8')
    if not report['pass']:
        raise SystemExit('checks failed')
    return 0

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

GlobalGrid2050 Build Generation Ecg All Tech Mvp

A Python command-line tool in the scripts folder that builds tech ecg (`build_all_tech_ecg`), loads recent ecg rows (`load_recent_ecg_rows`) and renders report (`render_report`) (units: MW).

energy-dataglobalgrid2050 / scripts/build_generation_ecg_all_tech_mvp.py · lines 1–186 of 186 · Entry point · pattern render_report (shared by 13 files)

What it does
Defines build_all_tech_ecg, load_recent_ecg_rows, render_report, main. Uses libraries __future__, argparse, json, datetime, pathlib. Side effects: reads or writes files.
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_recent_30d_30min.json; JSON file generation_recent_halfhourly_30d.json; JSON file generation_daily_candidate.json; JSON file generation_monthly_candidate.json; JSON file GENERATION_ECG_ALL_TECH_MVP_LATEST.json; command-line arguments.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Generation Ecg All Tech Mvp Workflow (globalgrid2050).
What it achieves
GlobalGrid2050 all technology ECG MVP builder. It accepts `--ecg-days`, `--apply` and `--limit-sources`.
Why it matters
Run by GlobalGrid2050 Generation Ecg All Tech Mvp Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
GlobalGrid2050 Build Generation Heartbeat Mvp (import), __future__, argparse, json, datetime, pathlib
Used by
run by GlobalGrid2050 Generation Ecg All Tech Mvp Workflow (workflow run)
Produces
build_all_tech_ecg, load_recent_ecg_rows, render_report, main
Defines here
build_all_tech_ecg, load_recent_ecg_rows, render_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/build_generation_ecg_all_tech_mvp.py:1-186 · blob 6e2d689347f07ff257f8cf5ee4b7adc2e9709c43 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
"""
GlobalGrid2050 all technology ECG MVP builder.

This keeps the ECG data for all technologies in one compact rolling hot tier file.
The browser should display only the selected technology from the dropdown.

Important rule:
The browser safe ECG candidate must be built from the 30 minute recent source.
The 5 minute recent source is useful for future live heartbeat work, but it is too
large to wire into the default browser path as one all technology static file.
"""

from __future__ import annotations

import argparse
import json
from datetime import timedelta
from pathlib import Path

from build_generation_heartbeat_mvp import (
    ROOT,
    GEN_HISTORY,
    REPORT_DIR,
    REPORT_JSON_DIR,
    build_daily,
    build_monthly,
    load_all_rows,
    load_json_rows,
    stamp,
    utc_now,
    write_payload,
)

RECENT_ECG_SOURCES = [
    "uk_energy_tracking_v6/generation_history/generation_recent_30d_30min.json",
    "uk_energy_tracking_v6/generation_history/generation_recent_halfhourly_30d.json",
]


def build_all_tech_ecg(rows, days: int):
    if not rows:
        return []
    max_time = max(r["time"] for r in rows)
    start = max_time - timedelta(days=days)
    out = []
    for r in sorted(rows, key=lambda x: (x["technology"], x["time"])):
        if r["time"] < start:
            continue
        out.append({
            "time": r["time"].isoformat().replace("+00:00", "Z"),
            "technology": r["technology"],
            "generationMW": round(r["mw"], 3),
            "status": "candidate",
            "source": "30 minute recent ECG source candidate",
        })
    return out


def load_recent_ecg_rows():
    """Use browser safe recent source files for the ECG.

    Prefer the 30 minute recent file because it is already the browser safe grain.
    The legacy 5 minute file is only a fallback for audit continuity and should not
    be selected once the 30 minute file exists and parses.
    """
    audit = []
    for rel in RECENT_ECG_SOURCES:
        path = ROOT / rel
        if not path.exists():
            audit.append({"path": rel, "exists": False, "sizeBytes": 0, "rowsParsed": 0, "selected": False})
            continue
        rows = load_json_rows(path)
        selected = bool(rows)
        audit.append({
            "path": rel,
            "exists": True,
            "sizeBytes": path.stat().st_size,
            "rowsParsed": len(rows),
            "selected": selected,
        })
        if rows:
            return rows, rel, audit
    return [], None, audit


def render_report(report: dict) -> str:
    lines = [
        "# GlobalGrid2050 All Technology ECG MVP Report",
        "",
        f"Generated UTC: `{report['generatedUTC']}`",
        f"Mode: `{report['mode']}`",
        f"ECG days: `{report['ecgDays']}`",
        f"Rows parsed for daily and monthly candidates: `{report['rowsParsed']}`",
        f"Daily rows: `{report['dailyRows']}`",
        f"Monthly rows: `{report['monthlyRows']}`",
        f"Selected ECG source: `{report['ecgSourcePath'] or 'none'}`",
        f"Rows parsed for ECG source: `{report['ecgSourceRows']}`",
        f"All technology ECG rows: `{report['ecgRows']}`",
        "",
        "## Outputs",
        "",
    ]
    for item in report["outputs"]:
        lines.append(f"{item['path']}  {item['sizeBytes']} bytes")
    lines += ["", "## ECG source candidates", ""]
    for src in report["ecgSources"]:
        lines.append(f"{src['path']}  exists={src['exists']}  selected={src['selected']}  parsed {src['rowsParsed']} rows")
    lines += ["", "## Daily and monthly source files", ""]
    for src in report["sources"]:
        lines.append(f"{src['path']}  parsed {src['rowsParsed']} rows")
    lines += ["", "## Browser rule", "", report["browserRule"]]
    lines += ["", "## Notes", "", report["notes"]]
    return "\n".join(lines) + "\n"


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--ecg-days", type=int, default=30)
    parser.add_argument("--apply", action="store_true")
    parser.add_argument("--limit-sources", type=int, default=0)
    args = parser.parse_args()

    rows, source_audit = load_all_rows(args.limit_sources or None)
    ecg_rows, ecg_source_path, ecg_source_audit = load_recent_ecg_rows()

    daily = build_daily(rows)
    monthly = build_monthly(daily)
    ecg = build_all_tech_ecg(ecg_rows, args.ecg_days)

    daily_path = ROOT / "data" / "confirmed" / "generation_daily_candidate.json"
    monthly_path = ROOT / "data" / "confirmed" / "generation_monthly_candidate.json"
    ecg_path = GEN_HISTORY / f"generation_ecg_all_technologies_{args.ecg_days}d_30min_candidate.json"

    outputs = []
    if args.apply:
        write_payload(daily_path, daily, "Generation daily candidate facts", source_audit)
        write_payload(monthly_path, monthly, "Generation monthly candidate facts", source_audit)
        write_payload(ecg_path, ecg, "Generation 30 minute ECG candidate for all technologies", ecg_source_audit)
        for p in [daily_path, monthly_path, ecg_path]:
            outputs.append({"path": p.relative_to(ROOT).as_posix(), "sizeBytes": p.stat().st_size})

    report = {
        "schemaVersion": "0.3.0-candidate",
        "generatedUTC": utc_now(),
        "mode": "apply" if args.apply else "audit only",
        "ecgDays": args.ecg_days,
        "rowsParsed": len(rows),
        "dailyRows": len(daily),
        "monthlyRows": len(monthly),
        "ecgSourcePath": ecg_source_path,
        "ecgSourceRows": len(ecg_rows),
        "ecgRows": len(ecg),
        "ecgSources": ecg_source_audit,
        "sources": source_audit,
        "outputs": outputs,
        "browserRule": "The ECG hot tier stores all technologies for the rolling window at 30 minute grain. The chart must filter client side by selected technology and must not draw all technology traces by default.",
        "notes": "Candidate first. Daily and monthly facts may use wider repository source files. The browser safe ECG hot tier is restricted to the 30 minute recent source so the chart does not fetch the legacy 5 minute bulk file.",
    }

    REPORT_DIR.mkdir(parents=True, exist_ok=True)
    REPORT_JSON_DIR.mkdir(parents=True, exist_ok=True)
    s = stamp()
    md_path = REPORT_DIR / f"GENERATION_ECG_ALL_TECH_MVP_{s}.md"
    js_path = REPORT_JSON_DIR / f"GENERATION_ECG_ALL_TECH_MVP_{s}.json"
    latest_md = REPORT_DIR / "GENERATION_ECG_ALL_TECH_MVP_LATEST.md"
    latest_js = REPORT_JSON_DIR / "GENERATION_ECG_ALL_TECH_MVP_LATEST.json"

    md_text = render_report(report)
    js_text = json.dumps(report, indent=2, ensure_ascii=False) + "\n"
    md_path.write_text(md_text, encoding="utf-8")
    js_path.write_text(js_text, encoding="utf-8")
    latest_md.write_text(md_text, encoding="utf-8")
    latest_js.write_text(js_text, encoding="utf-8")

    print(f"Parsed {len(rows)} rows for daily and monthly candidates")
    print(f"Daily candidate rows {len(daily)}")
    print(f"Monthly candidate rows {len(monthly)}")
    print(f"Selected ECG source {ecg_source_path or 'none'}")
    print(f"ECG source rows {len(ecg_rows)}")
    print(f"All technology ECG candidate rows {len(ecg)}")
    return 0


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