GLOBALGRID2050 / EXPLORE CODE

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

GlobalGrid2050 Update UK Frequency V6 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).

590 lines of Python from globalgrid2050, in 2 files. Topic: Automation and CI. Section 1782 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 V6 storage · globalgrid2050 / scripts/update_uk_frequency_v6.py lines 1–368
  2. GlobalGrid2050 Update V5 V6 Granular Change Tracker render · globalgrid2050 / scripts/update_v5_v6_granular_change_tracker.py lines 1–222

GlobalGrid2050 Update UK Frequency V6

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_v6.py · lines 1–368 of 368 · 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 Compare UK Energy V5 V6 V3 (globalgrid2050); GlobalGrid2050 Fetch UK Frequency V6 Workflow (globalgrid2050); GlobalGrid2050 Update V5 V6 Granular Change Tracker (globalgrid2050). Reached from 2 other entry points, including GlobalGrid2050 Compare UK Energy V5 V6 V3 Workflow (globalgrid2050); GlobalGrid2050 Update V5 V6 Granular Change Tracker 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 V6 UK grid frequency collector.
Why it matters
Run by GlobalGrid2050 Compare UK Energy V5 V6 V3, GlobalGrid2050 Fetch UK Frequency V6 Workflow and GlobalGrid2050 Update V5 V6 Granular Change Tracker.
Application
globalgrid2050 · scripts · Python CLI
Uses
__future__, csv, json, os, time, datetime, pathlib, statistics
Used by
run by GlobalGrid2050 Compare UK Energy V5 V6 V3 (script call), run by GlobalGrid2050 Fetch UK Frequency V6 Workflow (workflow run), run by GlobalGrid2050 Update V5 V6 Granular Change Tracker (script call)
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_v6.py:1-368 · blob 1964124329126a9739a895e62126bd0ab0a825d9 · 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 V6 UK grid frequency collector.

Direct V6 port of the proven V5 collector. It writes only V6 frequency data files
and leaves the V5 collector untouched for rollback and comparison.
"""

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_v6"
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_v6_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 V6 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:
        dt = None
        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:
                pass
        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:
            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)
        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": sum(1 for v in values if v < 49.9),
            "samples_above_50_1": sum(1 for v in values if v > 50.1),
            "largest_deviation_hz": round(max(abs(v - 50.0) for v in values), 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
    JSON_FILE.write_text(json.dumps({
        "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:],
    }, 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 V6 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()

GlobalGrid2050 Update V5 V6 Granular Change Tracker

A Python command-line tool in the scripts folder that works with line count (`line_count`) and script sources (`script_sources`), using SHA-256.

renderglobalgrid2050 / scripts/update_v5_v6_granular_change_tracker.py · lines 1–222 of 222 · Entry point · pattern line_count (shared by 4 files)

What it does
It loads data. Defines 8 functions or classes, including read, sha, line_count, table, git. Uses libraries __future__, hashlib, json, re, subprocess. Side effects: changes the web page (DOM); reads or writes files; starts processes.
Downstream impact
Used directly by 2 files: GlobalGrid2050 Compare UK Energy V5 V6 V3 (globalgrid2050); GlobalGrid2050 Update V5 V6 Granular Change Tracker Workflow (globalgrid2050). Reached from 1 other entry point, including GlobalGrid2050 Compare UK Energy V5 V6 V3 Workflow (globalgrid2050).
What it achieves
It is built from the read step (`read`), the sha step (`sha`) and the table step (`table`). Generate a granular V5 to V6 change tracker before major V6 upgrades.
Why it matters
Run by GlobalGrid2050 Compare UK Energy V5 V6 V3 and GlobalGrid2050 Update V5 V6 Granular Change Tracker Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
GlobalGrid2050 Repair V6 Inpage Chart Real Estate (script call), GlobalGrid2050 Update UK Frequency V6 (script call), GlobalGrid2050 Update UK Price V5 (script call), GlobalGrid2050 Update UK Price V6 (script call), __future__, hashlib, json, re, subprocess, datetime, pathlib
Used by
run by GlobalGrid2050 Compare UK Energy V5 V6 V3 (script call), run by GlobalGrid2050 Update V5 V6 Granular Change Tracker Workflow (workflow run)
Produces
read, sha, line_count, table, git, recent_commits_for, script_sources, main
Defines here
read, sha, line_count, table, git, recent_commits_for, script_sources, 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_v5_v6_granular_change_tracker.py:1-222 · blob 0d114adaf6916bd4cb4da27e23f6f540a34e5387 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, process · domain stage: unknown · users: none · canonical: production_core
#!/usr/bin/env python3
"""
Generate a granular V5 to V6 change tracker before major V6 upgrades.

This report is intentionally procedural. It records exactly which V6 files are
currently carrying the live price, fullscreen, selector, frequency and workflow
changes so the next upgrade does not overwrite working code blindly.
"""

from __future__ import annotations

import hashlib
import json
import re
import subprocess
from datetime import datetime, timezone
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
V5 = ROOT / "uk_energy_tracking_v5"
V6 = ROOT / "uk_energy_tracking_v6"
OUT = V6 / "V5_V6_GRANULAR_CHANGE_TRACKER.md"
REPORT_V2 = V6 / "V5_V6_COMPARISON_REPORT_V2.md"

WATCH_FILES = [
    "uk_energy_tracking_v6/index.md",
    "uk_energy_tracking_v6/styles/app.css",
    "uk_energy_tracking_v6/price_history_chart/load_price_history_data/load_price_history_data.js",
    "uk_energy_tracking_v6/price_history_chart/render_price_chart/render_price_chart.js",
    "uk_energy_tracking_v6/price_history_chart/control_price_history/control_price_history.js",
    "uk_energy_tracking_v6/price_history_chart/fullscreen_period_menu/fullscreen_period_menu.js",
    "uk_energy_tracking_v6/app_bootstrap/start_v6_app/start_v6_app.js",
    "uk_energy_tracking_v6/frequency_history/frequency-history-ui.js",
    "uk_energy_tracking_v6/live_data_pipeline/live-config.js",
    "scripts/repair_v6_inpage_chart_real_estate.py",
    "scripts/update_uk_frequency_v6.py",
    "scripts/update_v5_v6_granular_change_tracker.py",
    ".github/workflows/fetch_uk_energy_and_prices_v5.yml",
    ".github/workflows/fetch_uk_energy_and_prices_v6.yml",
    ".github/workflows/fetch_uk_frequency_v6.yml",
    ".github/workflows/repair_v6_inpage_chart_real_estate.yml",
    ".github/workflows/update_v5_v6_granular_change_tracker.yml",
]

CONTRACT_TOKENS = [
    ("V6 index loads current stylesheet cache bust", "styles/app.css?v=20260604toolbargrid1", "uk_energy_tracking_v6/index.md"),
    ("V6 index loads working renderer", "render_price_chart.js", "uk_energy_tracking_v6/index.md"),
    ("V6 index loads control script", "control_price_history.js", "uk_energy_tracking_v6/index.md"),
    ("V6 index loads custom fullscreen period menu", "fullscreen_period_menu.js", "uk_energy_tracking_v6/index.md"),
    ("V6 app starts custom fullscreen period menu", "V6FullscreenPeriodMenu.start", "uk_energy_tracking_v6/app_bootstrap/start_v6_app/start_v6_app.js"),
    ("Native fullscreen select is hidden by custom menu", "price-history-native-hidden", "uk_energy_tracking_v6/price_history_chart/fullscreen_period_menu/fullscreen_period_menu.js"),
    ("Custom menu uses black background", "background:#05070c", "uk_energy_tracking_v6/price_history_chart/fullscreen_period_menu/fullscreen_period_menu.js"),
    ("Custom menu uses cyan text", "color:#00ffff", "uk_energy_tracking_v6/price_history_chart/fullscreen_period_menu/fullscreen_period_menu.js"),
    ("Fullscreen toolbar hard override exists", "V6 hard override: fullscreen toolbar grid", "uk_energy_tracking_v6/styles/app.css"),
    ("In page portrait chart height is current", "height:63dvh", "uk_energy_tracking_v6/styles/app.css"),
    ("V6 renderer keeps high and low event boxes", "drawV5StyleEvents", "uk_energy_tracking_v6/price_history_chart/render_price_chart/render_price_chart.js"),
    ("V6 renderer keeps pointer helper", "function drawPointer", "uk_energy_tracking_v6/price_history_chart/render_price_chart/render_price_chart.js"),
    ("V6 frequency collector exists", "GlobalGrid2050 V6 UK grid frequency collector", "scripts/update_uk_frequency_v6.py"),
    ("V6 frequency workflow exists", "fetch_uk_frequency_v6", ".github/workflows/fetch_uk_frequency_v6.yml"),
    ("V6 price workflow scheduled", "cron: '2-59/5 * * * *'", ".github/workflows/fetch_uk_energy_and_prices_v6.yml"),
    ("V5 price workflow manual only", "workflow_dispatch", ".github/workflows/fetch_uk_energy_and_prices_v5.yml"),
]


def read(rel: str) -> str:
    path = ROOT / rel
    return path.read_text(encoding="utf-8", errors="replace") if path.exists() else ""


def sha(path: Path) -> str:
    return hashlib.sha256(path.read_bytes()).hexdigest()[:16] if path.exists() else "missing"


def line_count(path: Path) -> int:
    if not path.exists():
        return 0
    return path.read_text(encoding="utf-8", errors="replace").count("\n") + 1


def table(headers: list[str], rows: list[list[object]]) -> list[str]:
    out = ["| " + " | ".join(headers) + " |", "|" + "|".join(["---"] * len(headers)) + "|"]
    for row in rows:
        out.append("| " + " | ".join(str(x).replace("\n", " ") for x in row) + " |")
    return out


def git(cmd: list[str]) -> str:
    try:
        return subprocess.check_output(cmd, cwd=ROOT, text=True, stderr=subprocess.DEVNULL).strip()
    except Exception:
        return ""


def recent_commits_for(rel: str, limit: int = 6) -> str:
    result = git(["git", "log", f"-{limit}", "--date=short", "--pretty=format:%h %ad %s", "--", rel])
    return result.replace("\n", "<br>") if result else "not available"


def script_sources(index_text: str) -> list[str]:
    return re.findall(r"<script[^>]+src=[\"']([^\"']+)[\"']", index_text, flags=re.I)


def main() -> None:
    required = [
        ROOT / "AI_START_HERE.md",
        V6 / "V6_ARCHITECTURAL_INTEGRITY_PROTOCOL.md",
        V6 / "V5_V6_COMPARISON_REPORT.md",
        REPORT_V2,
    ]
    for path in required:
        if not path.exists():
            raise FileNotFoundError(f"Missing guardrail file: {path.relative_to(ROOT)}")

    now = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
    index_v5 = read("uk_energy_tracking_v5/index.md")
    index_v6 = read("uk_energy_tracking_v6/index.md")

    lines: list[str] = []
    lines += [
        "# V5 to V6 Granular Change Tracker",
        "",
        f"Generated UTC: `{now}`",
        "",
        "## Purpose",
        "",
        "This file records the current V6 implementation at a granular level before the next major upgrade. It is not a marketing document. It is a procedural guardrail so working V6 files are not overwritten by broad repairs.",
        "",
        "## Hard rule before next major upgrade",
        "",
        "1. Read this tracker first.",
        "2. Read `V5_V6_COMPARISON_REPORT_V2.md` second.",
        "3. Change one feature at a time.",
        "4. Do not rewrite the renderer, control script or app bootstrap unless the exact affected lines are named first.",
        "5. Any UI repair must state whether it affects in page mode, fullscreen mode or both.",
        "6. V5 remains a protected reference and must not be patched by V6 repair workflows.",
        "",
        "## Watched file inventory",
        "",
    ]

    file_rows = []
    for rel in WATCH_FILES:
        path = ROOT / rel
        file_rows.append([rel, "yes" if path.exists() else "no", line_count(path), sha(path), recent_commits_for(rel)])
    lines += table(["File", "Exists", "Lines", "SHA", "Recent commits touching file"], file_rows)

    lines += ["", "## Current script load order", ""]
    rows = []
    for i, src in enumerate(script_sources(index_v5), 1):
        rows.append(["V5", i, src])
    for i, src in enumerate(script_sources(index_v6), 1):
        rows.append(["V6", i, src])
    lines += table(["App", "Order", "Script source"], rows)

    lines += ["", "## Current V6 contract tokens", ""]
    token_rows = []
    for name, token, rel in CONTRACT_TOKENS:
        text = read(rel)
        token_rows.append([name, rel, token, "yes" if token in text else "no"])
    lines += table(["Check", "File", "Token", "Pass"], token_rows)

    lines += ["", "## Current fullscreen period selector implementation", ""]
    lines += [
        "The native `select` remains in `index.md` for state compatibility. The visible fullscreen dropdown is now a custom SCADA menu generated by `fullscreen_period_menu.js`. This avoids mobile Safari and browser native option menus forcing a white dropdown that cannot be reliably styled by CSS.",
        "",
        "Current expected behaviour:",
        "",
        "1. Closed menu uses black background and cyan text.",
        "2. Open menu uses black background and cyan text.",
        "3. Active option uses dark cyan highlight.",
        "4. Native select is hidden only in fullscreen custom menu context.",
        "5. The underlying native select value still drives the existing V6 period logic.",
        "",
    ]

    lines += ["## Current electricity chart UI implementation", ""]
    lines += [
        "In page portrait height is controlled by the last hard override in `app.css`. Current target is `63dvh` and `470px` minimum height.",
        "",
        "Fullscreen chart drawing is controlled by `render_price_chart.js`; the toolbar position and selector appearance are controlled by `app.css` plus `fullscreen_period_menu.js`.",
        "",
        "The renderer currently keeps V5 style high and low event boxes with red markers and pointer lines. The bottom summary box has been removed from the render path.",
        "",
    ]

    lines += ["## Current live data migration status", ""]
    workflow_rows = []
    for rel in [
        ".github/workflows/fetch_uk_energy_and_prices_v5.yml",
        ".github/workflows/fetch_uk_energy_and_prices_v6.yml",
        ".github/workflows/fetch_uk_frequency_v6.yml",
    ]:
        text = read(rel)
        workflow_rows.append([
            rel,
            "yes" if text else "no",
            "yes" if "schedule:" in text else "no",
            "yes" if "workflow_dispatch" in text else "no",
            "yes" if "update_uk_price_v5.py" in text else "no",
            "yes" if "update_uk_price_v6.py" in text else "no",
            "yes" if "update_uk_frequency_v6.py" in text else "no",
        ])
    lines += table(["Workflow", "Exists", "Scheduled", "Manual", "V5 price", "V6 price", "V6 frequency"], workflow_rows)

    lines += ["", "## Next major upgrade gate", ""]
    failed = [row[0] for row in token_rows if row[-1] != "yes"]
    if failed:
        lines += ["Do not start the next major upgrade until these checks are understood:", ""]
        lines += [f"{i + 1}. {item}" for i, item in enumerate(failed)]
    else:
        lines += [
            "All tracked V6 guardrail tokens are present.",
            "",
            "Next upgrade may proceed only as a new isolated feature with a named target file list and a rollback commit plan.",
        ]

    OUT.write_text("\n".join(lines) + "\n", encoding="utf-8")
    print(f"Wrote {OUT.relative_to(ROOT)}")


if __name__ == "__main__":
    main()