GLOBALGRID2050 / EXPLORE CODE

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

GlobalGrid2050 Update UK Frequency V5 and 1 more file

A Python command-line tool in the scripts folder that fetches grid frequency history, live grid frequency weekly health and grid frequency weekly health from Elexon Balancing Mechanism Reporting Service (BMRS).

611 lines of Python from globalgrid2050, in 2 files. Topic: Automation and CI. Section 1781 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 Update UK Frequency Daily V5 storage · globalgrid2050 / scripts/update_uk_frequency_daily_v5.py lines 1–239
  2. GlobalGrid2050 Update UK Frequency V5 storage · globalgrid2050 / scripts/update_uk_frequency_v5.py lines 1–372

GlobalGrid2050 Update UK Frequency Daily V5

A Python command-line tool in the scripts folder that reads rows and daily existing and reads validation history, covering grid frequency history and live grid frequency daily health.

storageglobalgrid2050 / scripts/update_uk_frequency_daily_v5.py · lines 1–239 of 239 · Entry point · pattern write_report (shared by 52 files)

What it does
Defines 10 functions or classes, including date_key, read_raw_rows, read_daily_existing, summarise_daily, write_daily. Uses libraries __future__, csv, json, datetime, pathlib. Side effects: reads or writes files.
Inputs & outputs
In: CSV file grid_frequency_history.csv; CSV file grid_frequency_daily_health.csv; JSON file live_grid_frequency_daily_health.json; CSV file grid_frequency_validation.csv; JSON file live_grid_frequency_validation.json.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Update UK Frequency Daily V5 Workflow (globalgrid2050).
What it achieves
It reads raw rows (`read_raw_rows`), reads daily existing (`read_daily_existing`) and summarises daily (`summarise_daily`). GlobalGrid2050 V5 daily frequency health and validation layer.
Why it matters
Run by GlobalGrid2050 Update UK Frequency Daily V5 Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
GlobalGrid2050 Update UK Frequency V5 (import), __future__, csv, json, datetime, pathlib, statistics
Used by
run by GlobalGrid2050 Update UK Frequency Daily V5 Workflow (workflow run)
Produces
date_key, read_raw_rows, read_daily_existing, summarise_daily, write_daily, read_validation_history, validate_latest, write_validation, write_report, main
Defines here
date_key, read_raw_rows, read_daily_existing, summarise_daily, write_daily, read_validation_history, validate_latest, write_validation, 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/update_uk_frequency_daily_v5.py:1-239 · blob 02329fe39303c0a64806cdc5725f6332c9c139d4 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: unknown · users: none · canonical: production_core
#!/usr/bin/env python3
"""
GlobalGrid2050 V5 daily frequency health and validation layer.

Reads the rolling 24 hour frequency CSV, updates a long term daily summary CSV,
and cross checks the latest stored sample against a fresh Elexon pull.
"""

from __future__ import annotations

import csv
import json
from datetime import datetime, timezone
from pathlib import Path
from statistics import mean

from update_uk_frequency_v5 import (
    fetch_frequency_rows,
    iso_z,
    parse_time,
    utc_now,
)

ROOT = Path(__file__).resolve().parent.parent
FOLDER = ROOT / "uk_energy_tracking_v5"
RAW_CSV = FOLDER / "grid_frequency_history.csv"
DAILY_CSV = FOLDER / "grid_frequency_daily_health.csv"
DAILY_JSON = FOLDER / "live_grid_frequency_daily_health.json"
VALIDATION_CSV = FOLDER / "grid_frequency_validation.csv"
VALIDATION_JSON = FOLDER / "live_grid_frequency_validation.json"
REPORT_DIR = ROOT / "gridbot_reports"
REPORT_FILE = REPORT_DIR / "uk_frequency_daily_validation_v5_report.md"


def date_key(dt: datetime) -> str:
    return dt.astimezone(timezone.utc).strftime("%Y-%m-%d")


def read_raw_rows() -> list[dict]:
    if not RAW_CSV.exists():
        return []
    rows = []
    with RAW_CSV.open("r", encoding="utf-8", newline="") as handle:
        reader = csv.DictReader(handle)
        for row in reader:
            dt = parse_time(row.get("source_time_utc"))
            if not dt:
                continue
            try:
                hz = float(row.get("frequency_hz") or 0)
            except ValueError:
                continue
            rows.append({
                "source_time_utc": iso_z(dt),
                "frequency_hz": hz,
                "captured_utc": row.get("captured_utc") or "",
                "source": row.get("source") or "Elexon",
                "status": row.get("status") or "ok",
            })
    return sorted(rows, key=lambda r: r["source_time_utc"])


def read_daily_existing() -> dict[str, dict]:
    if not DAILY_CSV.exists():
        return {}
    out = {}
    with DAILY_CSV.open("r", encoding="utf-8", newline="") as handle:
        reader = csv.DictReader(handle)
        for row in reader:
            key = row.get("date_utc")
            if key:
                out[key] = row
    return out


def summarise_daily(rows: list[dict]) -> dict[str, dict]:
    buckets: dict[str, list[float]] = {}
    for row in rows:
        dt = parse_time(row.get("source_time_utc"))
        if not dt:
            continue
        buckets.setdefault(date_key(dt), []).append(float(row["frequency_hz"]))

    summaries = {}
    for day, values in buckets.items():
        if not values:
            continue
        min_hz = min(values)
        max_hz = max(values)
        avg_hz = mean(values)
        summaries[day] = {
            "date_utc": day,
            "sample_count": len(values),
            "avg_hz": round(avg_hz, 4),
            "min_hz": round(min_hz, 4),
            "max_hz": round(max_hz, 4),
            "samples_below_49_9": sum(1 for value in values if value < 49.9),
            "samples_above_50_1": sum(1 for value in values if value > 50.1),
            "largest_deviation_hz": round(max(abs(value - 50.0) for value in values), 4),
            "data_health": "ok" if len(values) >= 20 else "thin_sample",
            "last_updated_utc": iso_z(utc_now()),
        }
    return summaries


def write_daily(rows: list[dict]) -> list[dict]:
    existing = read_daily_existing()
    merged = {**existing, **summarise_daily(rows)}
    final = [merged[key] for key in sorted(merged.keys())]
    fields = [
        "date_utc",
        "sample_count",
        "avg_hz",
        "min_hz",
        "max_hz",
        "samples_below_49_9",
        "samples_above_50_1",
        "largest_deviation_hz",
        "data_health",
        "last_updated_utc",
    ]
    FOLDER.mkdir(parents=True, exist_ok=True)
    with DAILY_CSV.open("w", encoding="utf-8", newline="") as handle:
        writer = csv.DictWriter(handle, fieldnames=fields)
        writer.writeheader()
        writer.writerows(final)

    DAILY_JSON.write_text(json.dumps({
        "updated_utc": iso_z(utc_now()),
        "record_count": len(final),
        "latest_day": final[-1] if final else None,
        "source": "GlobalGrid2050 aggregation of Elexon frequency samples",
        "health": "ok" if final else "awaiting_daily_rows",
        "rows": final[-370:],
    }, indent=2), encoding="utf-8")
    return final


def read_validation_history() -> list[dict]:
    if not VALIDATION_CSV.exists():
        return []
    with VALIDATION_CSV.open("r", encoding="utf-8", newline="") as handle:
        return list(csv.DictReader(handle))


def validate_latest(raw_rows: list[dict]) -> dict:
    stored = raw_rows[-1] if raw_rows else None
    source_rows, errors = fetch_frequency_rows()
    source_latest = source_rows[-1] if source_rows else None

    status = "awaiting_rows"
    delta_hz = None
    timestamp_match = False
    age_seconds = None
    if stored and source_latest:
        stored_dt = parse_time(stored.get("source_time_utc"))
        source_dt = parse_time(source_latest.get("source_time_utc"))
        if stored_dt and source_dt:
            age_seconds = int(abs((source_dt - stored_dt).total_seconds()))
            timestamp_match = stored_dt == source_dt
        delta_hz = round(abs(float(source_latest["frequency_hz"]) - float(stored["frequency_hz"])), 6)
        status = "ok" if delta_hz <= 0.0001 and age_seconds is not None and age_seconds <= 300 else "check_source_lag"
    elif stored:
        status = "source_fetch_failed"
    elif source_latest:
        status = "local_store_empty"

    return {
        "checked_utc": iso_z(utc_now()),
        "status": status,
        "stored_time_utc": stored.get("source_time_utc") if stored else None,
        "stored_hz": stored.get("frequency_hz") if stored else None,
        "source_time_utc": source_latest.get("source_time_utc") if source_latest else None,
        "source_hz": source_latest.get("frequency_hz") if source_latest else None,
        "delta_hz": delta_hz,
        "timestamp_match": timestamp_match,
        "source_lag_seconds": age_seconds,
        "errors": " | ".join(errors[-3:]),
    }


def write_validation(row: dict) -> list[dict]:
    history = read_validation_history()
    history.append(row)
    history = history[-500:]
    fields = [
        "checked_utc",
        "status",
        "stored_time_utc",
        "stored_hz",
        "source_time_utc",
        "source_hz",
        "delta_hz",
        "timestamp_match",
        "source_lag_seconds",
        "errors",
    ]
    with VALIDATION_CSV.open("w", encoding="utf-8", newline="") as handle:
        writer = csv.DictWriter(handle, fieldnames=fields)
        writer.writeheader()
        writer.writerows(history)
    VALIDATION_JSON.write_text(json.dumps({
        "updated_utc": iso_z(utc_now()),
        "latest": row,
        "history_count": len(history),
        "health": row["status"],
    }, indent=2), encoding="utf-8")
    return history


def write_report(daily_rows: list[dict], validation: dict) -> None:
    REPORT_DIR.mkdir(parents=True, exist_ok=True)
    latest_day = daily_rows[-1] if daily_rows else None
    REPORT_FILE.write_text("\n".join([
        "# UK Frequency Daily Validation V5 Report",
        "",
        f"Updated UTC: {iso_z(utc_now())}",
        f"Daily records retained: {len(daily_rows)}",
        f"Latest daily row: {json.dumps(latest_day, ensure_ascii=False)}",
        f"Validation: {json.dumps(validation, ensure_ascii=False)}",
        "",
    ]), encoding="utf-8")


def main() -> None:
    raw_rows = read_raw_rows()
    daily_rows = write_daily(raw_rows)
    validation = validate_latest(raw_rows)
    write_validation(validation)
    write_report(daily_rows, validation)
    print(json.dumps({
        "raw_rows": len(raw_rows),
        "daily_rows": len(daily_rows),
        "validation": validation,
    }, indent=2))


if __name__ == "__main__":
    main()

GlobalGrid2050 Update UK Frequency V5

A Python command-line tool in the scripts folder that fetches grid frequency history, live grid frequency weekly health and grid frequency weekly health from Elexon Balancing Mechanism Reporting Service (BMRS).

storageglobalgrid2050 / scripts/update_uk_frequency_v5.py · lines 1–372 of 372 · Entry point · pattern fetch_frequency_rows_for_window (shared by 2 files)

What it does
It fetches grid frequency history, live grid frequency weekly health and grid frequency weekly health. Defines 17 functions or classes, including utc_now, iso_z, parse_time, week_start, http_json. Uses libraries __future__, csv, json, os, time. Side effects: reads or writes files; makes network requests.
Inputs & outputs
In: data source: Elexon BMRS; CSV file grid_frequency_history.csv; JSON file live_grid_frequency.json; CSV file grid_frequency_weekly_health.csv; JSON file live_grid_frequency_weekly_health.json.
Downstream impact
Used directly by 3 files: GlobalGrid2050 Fetch UK Frequency V5 Workflow (globalgrid2050); GlobalGrid2050 Backfill UK Frequency Weekly V5 (globalgrid2050); GlobalGrid2050 Update UK Frequency Daily V5 (globalgrid2050). Reached from 2 other entry points, including GlobalGrid2050 Backfill UK Frequency Weekly V5 Workflow (globalgrid2050); GlobalGrid2050 Update UK Frequency Daily V5 Workflow (globalgrid2050).
What it achieves
It parses time (`parse_time`), extracts rows (`extract_rows`) and fetches frequency rows window (`fetch_frequency_rows_for_window`). GlobalGrid2050 V5 UK grid frequency collector.
Why it matters
Imported by GlobalGrid2050 Backfill UK Frequency Weekly V5 and GlobalGrid2050 Update UK Frequency Daily V5. Run by GlobalGrid2050 Fetch UK Frequency V5 Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
__future__, csv, json, os, time, datetime, pathlib, statistics
Used by
run by GlobalGrid2050 Fetch UK Frequency V5 Workflow (workflow run), imported by GlobalGrid2050 Backfill UK Frequency Weekly V5 (import), imported by GlobalGrid2050 Update UK Frequency Daily V5 (import)
Produces
utc_now, iso_z, parse_time, week_start, http_json, candidate_urls, extract_rows, fetch_frequency_rows_for_window, fetch_frequency_rows, read_existing_raw, read_weekly_existing, weekly_summary_from_rows
Defines here
utc_now, iso_z, parse_time, week_start, http_json, candidate_urls, extract_rows, fetch_frequency_rows_for_window, fetch_frequency_rows, read_existing_raw, read_weekly_existing, weekly_summary_from_rows, write_weekly_outputs, write_outputs, write_report, run_once, 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/update_uk_frequency_v5.py:1-372 · blob c208367642bf9eb242a4a5e08039410753435b5c · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, network · domain stage: unknown · users: none · canonical: production_core
#!/usr/bin/env python3
"""
GlobalGrid2050 V5 UK grid frequency collector.

Keeps a rolling 24 hour UK grid frequency dataset and a compact weekly
frequency health summary for the V5 tracker.
"""

from __future__ import annotations

import csv
import json
import os
import time
from datetime import datetime, timedelta, timezone
from pathlib import Path
from statistics import mean
from typing import Any
from urllib.parse import urlencode

import requests

ROOT = Path(__file__).resolve().parent.parent
FOLDER = ROOT / "uk_energy_tracking_v5"
CSV_FILE = FOLDER / "grid_frequency_history.csv"
JSON_FILE = FOLDER / "live_grid_frequency.json"
WEEKLY_CSV_FILE = FOLDER / "grid_frequency_weekly_health.csv"
WEEKLY_JSON_FILE = FOLDER / "live_grid_frequency_weekly_health.json"
REPORT_DIR = ROOT / "gridbot_reports"
REPORT_FILE = REPORT_DIR / "uk_frequency_v5_report.md"

ELEXON = "https://data.elexon.co.uk/bmrs/api/v1"
TIMEOUT = 18
ROLLING_HOURS = int(os.getenv("GG_FREQUENCY_ROLLING_HOURS", "24"))
LOOKBACK_MINUTES = int(os.getenv("GG_FREQUENCY_LOOKBACK_MINUTES", "180"))
BURST_SAMPLES = max(1, min(int(os.getenv("GG_FREQUENCY_BURST_SAMPLES", "1")), 12))
SLEEP_SECONDS = max(0, min(int(os.getenv("GG_FREQUENCY_SLEEP_SECONDS", "120")), 300))
WEEKLY_HISTORY_WEEKS = int(os.getenv("GG_FREQUENCY_WEEKLY_HISTORY_WEEKS", "52"))
USER_AGENT = "GlobalGrid2050 V5 frequency collector using public Elexon data"


def utc_now() -> datetime:
    return datetime.now(timezone.utc)


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


def parse_time(value: Any) -> datetime | None:
    if value is None:
        return None
    if isinstance(value, (int, float)):
        return datetime.fromtimestamp(float(value), timezone.utc)
    text = str(value).strip()
    if not text:
        return None
    if text.endswith("Z"):
        text = text[:-1] + "+00:00"
    try:
        dt = datetime.fromisoformat(text)
    except ValueError:
        for fmt in ("%Y-%m-%d %H:%M:%S", "%Y-%m-%dT%H:%M:%S", "%Y-%m-%dT%H:%M"):
            try:
                dt = datetime.strptime(text, fmt).replace(tzinfo=timezone.utc)
                break
            except ValueError:
                dt = None
        if dt is None:
            return None
    if dt.tzinfo is None:
        dt = dt.replace(tzinfo=timezone.utc)
    return dt.astimezone(timezone.utc)


def week_start(dt: datetime) -> datetime:
    day = dt.astimezone(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0)
    return day - timedelta(days=day.weekday())


def http_json(url: str) -> Any:
    response = requests.get(
        url,
        timeout=TIMEOUT,
        headers={"Accept": "application/json", "User-Agent": USER_AGENT},
    )
    response.raise_for_status()
    return response.json()


def candidate_urls(start: datetime, end: datetime) -> list[str]:
    start_min = start.strftime("%Y-%m-%dT%H:%MZ")
    end_min = end.strftime("%Y-%m-%dT%H:%MZ")
    start_sec = iso_z(start)
    end_sec = iso_z(end)
    return [
        f"{ELEXON}/datasets/FREQ?" + urlencode({"publishDateTimeFrom": start_min, "publishDateTimeTo": end_min, "format": "json"}),
        f"{ELEXON}/datasets/FREQ?" + urlencode({"from": start_min, "to": end_min, "format": "json"}),
        f"{ELEXON}/balancing/system-frequency?" + urlencode({"from": start_sec, "to": end_sec, "format": "json"}),
        f"{ELEXON}/balancing/system/frequency?" + urlencode({"from": start_sec, "to": end_sec, "format": "json"}),
    ]


def extract_rows(payload: Any) -> list[dict[str, Any]]:
    if isinstance(payload, dict):
        rows = payload.get("data") or payload.get("items") or payload.get("results") or []
    else:
        rows = payload
    if isinstance(rows, dict):
        rows = [rows]
    if not isinstance(rows, list):
        return []

    output: list[dict[str, Any]] = []
    for row in rows:
        if not isinstance(row, dict):
            continue
        lower = {str(k).lower(): v for k, v in row.items()}
        frequency = None
        for key in ("frequency", "systemfrequency", "frequencyhz", "systemfrequencyhz", "value", "frequencyvalue"):
            value = lower.get(key)
            if value in (None, ""):
                continue
            try:
                candidate = float(value)
            except (TypeError, ValueError):
                continue
            if 45 <= candidate <= 55:
                frequency = candidate
                break
        if frequency is None:
            for value in row.values():
                try:
                    candidate = float(value)
                except (TypeError, ValueError):
                    continue
                if 45 <= candidate <= 55:
                    frequency = candidate
                    break
        if frequency is None:
            continue

        source_dt = None
        for key in ("publishtime", "publishdatetime", "starttime", "datetime", "time", "timestamp"):
            source_dt = parse_time(lower.get(key))
            if source_dt:
                break
        if source_dt is None:
            source_dt = utc_now()

        output.append({
            "source_time_utc": iso_z(source_dt),
            "frequency_hz": round(float(frequency), 4),
            "captured_utc": iso_z(utc_now()),
            "source": "Elexon",
            "status": "ok",
        })
    return output


def fetch_frequency_rows_for_window(start: datetime, end: datetime) -> tuple[list[dict[str, Any]], list[str]]:
    errors: list[str] = []
    for url in candidate_urls(start, end):
        try:
            rows = extract_rows(http_json(url))
            if rows:
                return rows, errors
            errors.append(f"no rows from {url}")
        except Exception as exc:  # noqa: BLE001
            errors.append(f"{type(exc).__name__}: {exc} from {url}")
    return [], errors


def fetch_frequency_rows() -> tuple[list[dict[str, Any]], list[str]]:
    end = utc_now()
    start = end - timedelta(minutes=LOOKBACK_MINUTES)
    return fetch_frequency_rows_for_window(start, end)


def read_existing_raw() -> list[dict[str, Any]]:
    if not CSV_FILE.exists():
        return []
    rows = []
    with CSV_FILE.open("r", encoding="utf-8", newline="") as handle:
        reader = csv.DictReader(handle)
        for row in reader:
            try:
                rows.append({
                    "source_time_utc": row.get("source_time_utc") or "",
                    "frequency_hz": round(float(row.get("frequency_hz") or 0), 4),
                    "captured_utc": row.get("captured_utc") or "",
                    "source": row.get("source") or "Elexon",
                    "status": row.get("status") or "ok",
                })
            except ValueError:
                continue
    return rows


def read_weekly_existing() -> dict[str, dict[str, Any]]:
    if not WEEKLY_CSV_FILE.exists():
        return {}
    rows: dict[str, dict[str, Any]] = {}
    with WEEKLY_CSV_FILE.open("r", encoding="utf-8", newline="") as handle:
        reader = csv.DictReader(handle)
        for row in reader:
            key = row.get("week_start_utc")
            if key:
                rows[key] = row
    return rows


def weekly_summary_from_rows(rows: list[dict[str, Any]]) -> dict[str, dict[str, Any]]:
    buckets: dict[str, list[float]] = {}
    for row in rows:
        dt = parse_time(row.get("source_time_utc"))
        if not dt:
            continue
        key = iso_z(week_start(dt))
        buckets.setdefault(key, []).append(float(row["frequency_hz"]))

    out: dict[str, dict[str, Any]] = {}
    for key, values in buckets.items():
        if not values:
            continue
        min_hz = min(values)
        max_hz = max(values)
        avg_hz = mean(values)
        below_49_9 = sum(1 for v in values if v < 49.9)
        above_50_1 = sum(1 for v in values if v > 50.1)
        largest_dev = max(abs(v - 50.0) for v in values)
        out[key] = {
            "week_start_utc": key,
            "sample_count": len(values),
            "avg_hz": round(avg_hz, 4),
            "min_hz": round(min_hz, 4),
            "max_hz": round(max_hz, 4),
            "samples_below_49_9": below_49_9,
            "samples_above_50_1": above_50_1,
            "largest_deviation_hz": round(largest_dev, 4),
            "data_health": "ok" if len(values) >= 10 else "thin_sample",
        }
    return out


def write_weekly_outputs(new_rows: list[dict[str, Any]]) -> None:
    existing = read_weekly_existing()
    new_weekly = weekly_summary_from_rows(new_rows)
    merged = {**existing, **new_weekly}

    cutoff = week_start(utc_now()) - timedelta(weeks=WEEKLY_HISTORY_WEEKS - 1)
    final = []
    for key, row in merged.items():
        dt = parse_time(key)
        if dt and dt >= cutoff:
            final.append(row)
    final.sort(key=lambda r: r["week_start_utc"])

    fields = [
        "week_start_utc",
        "sample_count",
        "avg_hz",
        "min_hz",
        "max_hz",
        "samples_below_49_9",
        "samples_above_50_1",
        "largest_deviation_hz",
        "data_health",
    ]
    with WEEKLY_CSV_FILE.open("w", encoding="utf-8", newline="") as handle:
        writer = csv.DictWriter(handle, fieldnames=fields)
        writer.writeheader()
        writer.writerows(final)

    WEEKLY_JSON_FILE.write_text(json.dumps({
        "updated_utc": iso_z(utc_now()),
        "window_weeks": WEEKLY_HISTORY_WEEKS,
        "record_count": len(final),
        "latest_week": final[-1] if final else None,
        "source": "Elexon plus GlobalGrid2050 weekly aggregation",
        "health": "ok" if final else "awaiting_weekly_rows",
        "rows": final,
    }, indent=2), encoding="utf-8")


def write_outputs(rows: list[dict[str, Any]], errors: list[str]) -> list[dict[str, Any]]:
    FOLDER.mkdir(parents=True, exist_ok=True)
    cutoff = utc_now() - timedelta(hours=ROLLING_HOURS)
    dedup: dict[str, dict[str, Any]] = {}
    for row in rows:
        dt = parse_time(row.get("source_time_utc") or row.get("captured_utc"))
        if not dt or dt < cutoff:
            continue
        key = iso_z(dt)
        row["source_time_utc"] = key
        dedup[key] = row

    final = [dedup[key] for key in sorted(dedup.keys())]
    with CSV_FILE.open("w", encoding="utf-8", newline="") as handle:
        writer = csv.DictWriter(handle, fieldnames=["source_time_utc", "frequency_hz", "captured_utc", "source", "status"])
        writer.writeheader()
        writer.writerows(final)

    values = [float(row["frequency_hz"]) for row in final]
    latest = final[-1] if final else None
    snapshot = {
        "updated_utc": iso_z(utc_now()),
        "window_hours": ROLLING_HOURS,
        "record_count": len(final),
        "latest": latest,
        "min_hz": round(min(values), 4) if values else None,
        "max_hz": round(max(values), 4) if values else None,
        "avg_hz": round(mean(values), 4) if values else None,
        "source": "Elexon",
        "health": "ok" if latest else "awaiting_source_rows",
        "errors": errors[-4:],
    }
    JSON_FILE.write_text(json.dumps(snapshot, indent=2), encoding="utf-8")
    print(f"Retained {len(final)} frequency records")
    if latest:
        print(f"Latest frequency {latest['frequency_hz']} Hz at {latest['source_time_utc']}")
    if errors:
        print("::warning::" + " | ".join(errors[-2:]))
    return final


def write_report(errors: list[str]) -> None:
    REPORT_DIR.mkdir(parents=True, exist_ok=True)
    live = json.loads(JSON_FILE.read_text(encoding="utf-8")) if JSON_FILE.exists() else {}
    weekly = json.loads(WEEKLY_JSON_FILE.read_text(encoding="utf-8")) if WEEKLY_JSON_FILE.exists() else {}
    lines = [
        "# UK Frequency V5 GridBot Report",
        "",
        f"Updated UTC: {iso_z(utc_now())}",
        f"Rolling window hours: {ROLLING_HOURS}",
        f"24 hour records retained: {live.get('record_count', 0)}",
        f"Latest: {json.dumps(live.get('latest'), ensure_ascii=False)}",
        f"Min Hz: {live.get('min_hz')}",
        f"Max Hz: {live.get('max_hz')}",
        f"Average Hz: {live.get('avg_hz')}",
        f"24 hour health: {live.get('health')}",
        f"Weekly records retained: {weekly.get('record_count', 0)}",
        f"Latest weekly row: {json.dumps(weekly.get('latest_week'), ensure_ascii=False)}",
        "",
        "## Recent fetch issues",
    ]
    lines.extend([f"- {error}" for error in errors[-8:]] or ["- none"])
    REPORT_FILE.write_text("\n".join(lines) + "\n", encoding="utf-8")


def run_once() -> list[str]:
    existing = read_existing_raw()
    fetched, errors = fetch_frequency_rows()
    if not fetched:
        errors.append("No source rows fetched this pass. Existing 24 hour file preserved and trimmed.")
    final_24h = write_outputs(existing + fetched, errors)
    write_weekly_outputs(final_24h)
    return errors


def main() -> None:
    all_errors: list[str] = []
    for index in range(BURST_SAMPLES):
        print(f"Frequency sample pass {index + 1} of {BURST_SAMPLES}")
        all_errors.extend(run_once())
        if index < BURST_SAMPLES - 1:
            time.sleep(SLEEP_SECONDS)
    write_report(all_errors)


if __name__ == "__main__":
    main()