GLOBALGRID2050 / EXPLORE CODE

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

Renewable Energy Planning Database (REPD) Diff and 1 more file

A Python command-line tool in the automation folder of GlobalGrid2050 that reads solar and the REPD register, using SHA-256. It cleans ref (`clean_ref`), parses num (`parse_num`) and parses date (`parse_date`).

700 lines of Python from globalgrid2050, in 2 files. Topic: Electricity markets and data pipelines. Section 822 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. Renewable Energy Planning Database (REPD) Detect storage · globalgrid2050 / automation/repd/detect.py lines 1–227
  2. Renewable Energy Planning Database (REPD) Diff energy-data · globalgrid2050 / automation/repd/diff.py lines 1–473

Renewable Energy Planning Database (REPD) Detect

A Python command-line tool in the automation folder of GlobalGrid2050 that detects error and parses publication and content API, covering detect report and the REPD register, using SHA-256.

storageglobalgrid2050 / automation/repd/detect.py · lines 1–227 of 227 · Entry point · pattern detect (shared by 2 files)

What it does
It lists and searches detect report and the REPD register. Defines 14 functions or classes, including DetectError, _Links, __init__, handle_starttag, handle_endtag. Uses libraries __future__, argparse, json, re, sys. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'repd'): 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: the REPD register.
Inputs & outputs
In: command-line arguments. Out: JSON file detect_report.json.
Downstream impact
Used directly by 2 files: Renewable Energy Planning Database (REPD) Monthly (globalgrid2050); Test Detect Fetch (globalgrid2050). Reached from 3 other entry points, including GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050); GlobalGrid2050 Renewable Energy Planning Database (REPD) Monthly Workflow (globalgrid2050); Test Monthly (globalgrid2050).
What it achieves
It detects error (`DetectError`), parses publication HTML (`parse_publication_html`) and parses content API (`parse_content_api`). Discover the current REPD release on GOV.UK and emit a release descriptor. It accepts `--kind`, `--from-file` and `--baseline`.
Why it matters
Imported by Renewable Energy Planning Database (REPD) Monthly. Checked by Test Detect Fetch.
Application
globalgrid2050 · automation/repd · Python CLI
Uses
Automation — Renewable Energy Planning Database (REPD) (relative import), Renewable Energy Planning Database (REPD) Fetch (relative import), __future__, argparse, json, re, sys, datetime, html.parser, pathlib
Used by
imported by Renewable Energy Planning Database (REPD) Monthly (import), imported by Test Detect Fetch (import)
Produces
DetectError, parse_publication_html, parse_content_api, build_descriptor, compare, detect, main
Defines here
DetectError, _Links, __init__, handle_starttag, handle_endtag, handle_data, _attachment, parse_publication_html, parse_content_api, _pick, build_descriptor, compare, detect, 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 automation/repd/detect.py:1-227 · blob a2402558ba79e2c7f39dfd3688f076fe6f78b04a · 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
"""Discover the current REPD release on GOV.UK and emit a release descriptor.

Two sources, both read through an injectable fetcher (see fetch.Response):
  * GOV.UK Content API JSON (as pipelinenews tooling/check-repd-source-v2.mjs:
    details.attachments[], public_updated_at);
  * the publication page HTML (as scripts/repd_updater.py discover_latest_sources:
    attachment links + "Last updated <d Month yyyy>").

Differences from repd_updater.py, deliberately:
  * no silent fall-back to hard-coded July URLs; failure is an error;
  * /csv-preview/ links and non-asset hosts are ignored (the first-match rule in
    repd_updater could pick the preview page);
  * quarter is read from the file names and cross-checked against the attachment
    title month; any disagreement fails closed;
  * "already current" compares URLs AND quarter against a baseline descriptor
    (repd_updater compared only manifest_v4 source_url).
Detection never assigns an expected sha256: hashes are pinned only after fetch +
review (see fetch.py).
"""
from __future__ import annotations

import argparse
import json
import re
import sys
from datetime import datetime
from html.parser import HTMLParser
from pathlib import Path
from typing import Optional
from urllib.parse import urljoin, urlparse

try:
    from . import config
    from .fetch import Fetcher, Response, file_name, urllib_fetcher, utc_now
except ImportError:
    sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
    from automation.repd import config  # type: ignore
    from automation.repd.fetch import Fetcher, Response, file_name, urllib_fetcher, utc_now  # type: ignore

ASSET_HOST = "assets.publishing.service.gov.uk"


class DetectError(RuntimeError):
    pass


# ---------------------------------------------------------------- parsing
class _Links(HTMLParser):
    def __init__(self):
        super().__init__(convert_charrefs=True)
        self.links: list[dict] = []
        self.text: list[str] = []
        self._a: Optional[dict] = None
        self._skip = 0

    def handle_starttag(self, tag, attrs):
        if tag in ("script", "style"):
            self._skip += 1
        if tag == "a":
            self._a = {"href": dict(attrs).get("href") or "", "text": []}

    def handle_endtag(self, tag):
        if tag in ("script", "style") and self._skip:
            self._skip -= 1
        if tag == "a" and self._a is not None:
            self._a["text"] = " ".join(" ".join(self._a["text"]).split())
            self.links.append(self._a)
            self._a = None

    def handle_data(self, data):
        if self._skip:
            return
        s = data.strip()
        if s:
            self.text.append(s)
            if self._a is not None:
                self._a["text"].append(s)


def _attachment(url: str, title: str) -> Optional[dict]:
    p = urlparse(url)
    if p.netloc != ASSET_HOST or "/csv-preview/" in p.path:
        return None
    name = file_name(url)
    low = name.lower()
    role = "csv" if low.endswith(".csv") else "xlsx" if low.endswith(".xlsx") else None
    if not role or ("repd" not in low and "repd" not in (title or "").lower()):
        return None
    return {"role": role, "url": url, "title": title or "", "file_name": name}


def parse_publication_html(html: str, base: str = config.SOURCE_PAGE) -> dict:
    p = _Links()
    p.feed(html)
    atts, seen = [], set()
    for a in p.links:
        url = urljoin(base, a["href"].strip())
        att = _attachment(url, a["text"])
        if att and url not in seen:
            seen.add(url)
            atts.append(att)
    text = " ".join(p.text)
    last = None
    m = re.search(r"Last updated:?\s+(\d{1,2}\s+[A-Za-z]+\s+\d{4})", text, re.I)
    if m:
        last = datetime.strptime(m.group(1), "%d %B %Y").strftime("%Y-%m-%d")
    return {"source": "publication_html", "attachments": atts, "page_last_updated": last,
            "govuk_public_updated_at": None}


def parse_content_api(payload) -> dict:
    meta = json.loads(payload) if isinstance(payload, (str, bytes)) else payload
    atts = []
    for item in (meta.get("details") or {}).get("attachments") or []:
        url = item.get("url") or ""
        att = _attachment(urljoin("https://www.gov.uk", url), item.get("title") or "")
        if att:
            atts.append(att)
    pua = meta.get("public_updated_at")
    return {"source": "content_api", "attachments": atts,
            "page_last_updated": pua[:10] if pua else None, "govuk_public_updated_at": pua}


# ---------------------------------------------------------------- descriptor
def _pick(atts: list[dict], role: str) -> dict:
    cands = [a for a in atts if a["role"] == role]
    if not cands:
        raise DetectError(f"no REPD .{role} attachment found on the publication")
    by_q = {}
    for a in cands:
        yq = config.quarter_from_filename(a["file_name"]) or config.quarter_from_label(a["title"])
        if yq is None:
            raise DetectError(f"cannot tell the quarter of attachment {a['url']}")
        a["yq"] = yq
        by_q.setdefault(yq, []).append(a)
    latest = max(by_q)
    if len({a["url"] for a in by_q[latest]}) > 1:
        raise DetectError(f"ambiguous: several .{role} attachments for {config.quarter_text(*latest)}: "
                          + ", ".join(a["url"] for a in by_q[latest]))
    return by_q[latest][0]


def build_descriptor(parsed: dict) -> config.ReleaseDescriptor:
    csv, xlsx = _pick(parsed["attachments"], "csv"), _pick(parsed["attachments"], "xlsx")
    if csv["yq"] != xlsx["yq"]:
        raise DetectError(f"CSV is {config.quarter_text(*csv['yq'])} but XLSX is {config.quarter_text(*xlsx['yq'])}")
    yq = csv["yq"]
    for a in (csv, xlsx):
        tq = config.quarter_from_label(a["title"])
        if tq is not None and tq != yq:
            raise DetectError(f"attachment title {a['title']!r} names {config.quarter_text(*tq)} "
                              f"but file {a['file_name']} is {config.quarter_text(*yq)}")
    m = re.search(r"(January|April|July|October)\s+20\d\d", csv["title"] + " " + xlsx["title"], re.I)
    if m:
        label = m.group(0).title()
    else:  # derive from quarter: Q1->April, Q2->July, Q3->October, Q4->January next year
        month = {1: "April", 2: "July", 3: "October", 4: "January"}[yq[1]]
        label = f"{month} {yq[0] + 1 if yq[1] == 4 else yq[0]}"
    desc = config.ReleaseDescriptor(
        release_id=config.release_id_for(*yq), label=label, quarter=config.quarter_text(*yq),
        csv_url=csv["url"], xlsx_url=xlsx["url"], page_last_updated=parsed.get("page_last_updated"),
        govuk_public_updated_at=parsed.get("govuk_public_updated_at"),
        dataset_title=csv["title"] or None,
        provenance=[f"detected from {parsed['source']} at {utc_now()}"],
    )
    return desc.validate()


def compare(candidate: config.ReleaseDescriptor, baseline: Optional[config.ReleaseDescriptor]) -> str:
    if baseline is None:
        return "NO_BASELINE"
    cq, bq = candidate.release_id, baseline.release_id
    if (candidate.csv_url, candidate.xlsx_url) == (baseline.csv_url, baseline.xlsx_url):
        return "UNCHANGED"
    if cq == bq:
        return "REPLACED_SAME_QUARTER"   # correction re-upload: new URLs, needs a new review
    if cq > bq:                          # '2026q3' > '2026q2' sorts correctly for 20xx
        return "NEW_RELEASE"
    raise DetectError(f"publication shows {cq}, older than baseline {bq}")


def detect(fetcher: Fetcher, kind: str = "api", baseline: Optional[config.ReleaseDescriptor] = None) -> dict:
    url = config.CONTENT_API if kind == "api" else config.SOURCE_PAGE
    resp = fetcher(url)
    if not resp.status_chain or resp.status_chain[-1][0] != 200:
        raise DetectError(f"{url}: final status {resp.status_chain}")
    body = resp.body.decode("utf-8")
    parsed = parse_content_api(body) if kind == "api" else parse_publication_html(body, resp.final_url)
    desc = build_descriptor(parsed)
    return {"schema": "globalgrid2050.repd-detect-report.v1", "detected_at": utc_now(),
            "source_url": url, "source_final_url": resp.final_url, "status_chain": resp.status_chain,
            "status": compare(desc, baseline),
            "baseline_release_id": baseline.release_id if baseline else None,
            "descriptor": desc.to_dict()}


def main(argv=None) -> int:
    ap = argparse.ArgumentParser(description="Detect the current REPD release")
    ap.add_argument("--kind", choices=["api", "html"], default="api")
    ap.add_argument("--from-file", help="offline: saved Content API JSON or page HTML")
    ap.add_argument("--baseline", help="descriptor of the last ingested release")
    ap.add_argument("--out", help="write detect_report.json and detected_<id>.json here")
    a = ap.parse_args(argv)
    if a.from_file:
        raw = Path(a.from_file).read_bytes()
        fetcher = lambda url: Response(url, url, [[200, url]], raw)  # noqa: E731
    else:
        fetcher = urllib_fetcher()
    baseline = config.load(a.baseline) if a.baseline else None
    try:
        report = detect(fetcher, a.kind, baseline)
    except (DetectError, config.DescriptorError) as exc:
        print(f"DETECT FAILED: {exc}", file=sys.stderr)
        return 2
    if a.out:
        out = Path(a.out)
        out.mkdir(parents=True, exist_ok=True)
        (out / "detect_report.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
        rid = report["descriptor"]["release_id"]
        (out / f"detected_{rid}.json").write_text(json.dumps(report["descriptor"], indent=2) + "\n", encoding="utf-8")
    d = report["descriptor"]
    print(f"{report['status']}: {d['release_id']} {d['label']} csv={d['csv_url']} xlsx={d['xlsx_url']}")
    return 0


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

Renewable Energy Planning Database (REPD) Diff

A Python command-line tool in the automation folder of GlobalGrid2050 that reads solar and the REPD register, using SHA-256. It cleans ref (`clean_ref`), parses num (`parse_num`) and parses date (`parse_date`).

energy-dataglobalgrid2050 / automation/repd/diff.py · lines 1–473 of 1003 · Entry point · pattern compare_hashes (shared by 2 files)

What it does
It loads solar and the REPD register. Defines 45 functions or classes, including DiffError, collapse, clean_ref, parse_num, parse_date. Uses libraries __future__, argparse, csv, hashlib, io. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'repd'): 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, the REPD register.
Inputs & outputs
In: JSON file diff.json; command-line arguments. Out: JSON file diff.json.
Downstream impact
Used directly by 6 files: Binder (globalgrid2050); Build Feed (globalgrid2050); Events (globalgrid2050); Test Binder (globalgrid2050); and 2 more. Reached from 4 other entry points, including GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (globalgrid2050); GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050); Test Events (globalgrid2050).
What it achieves
REPD release-over-release change report. Its code works with 1 MW and 0.0051 MW. It accepts `--previous`, `--new` and `--out`.
Why it matters
Imported by Binder, Build Feed and Events. Checked by 3 tests, including Test Binder.
Application
globalgrid2050 · automation/repd · Python CLI
Uses
__future__, argparse, csv, hashlib, io, json, math, os
Used by
imported by Binder (import), imported by Build Feed (import), imported by Events (import), imported by Test Binder (import), imported by Test Real Data (import), imported by Test Diff (import)
Produces
DiffError, collapse, clean_ref, parse_num, parse_date, norm_value, values_differ, r3, ref_key, sha256_file, load_csv, load_identity_json
Defines here
DiffError, collapse, clean_ref, parse_num, parse_date, norm_value, values_differ, r3, ref_key, sha256_file, _canon_header, _finish, load_csv, load_identity_json, load_previous, Agg, __init__, add, out, cap_of, text, total, group, compare_groups, brief, by_mw_desc, build_diff, ranked
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/repd/diff.py:1-473 · blob 5c42f0ebc8b8c6738261840b43b03b6dd382290d · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
"""automation/repd/diff.py - REPD release-over-release change report.

    python -m automation.repd.diff --previous PREV --new NEW --out DIR \
        [--previous-label "July 2026 (Q2)"] [--new-label "October 2026 (Q3)"] \
        [--capacity-tolerance 0.0051] [--protect PATH ...]

PREV  either an official-layout REPD CSV (53 columns, utf-8-sig or cp1252)
      or the derived globalgrid2050 dist/project_identity_v6.json (all records,
      ~20 of the 53 official columns; only those columns are compared).
NEW   the cleaned canonical CSV from clean.py (official 53-column layout;
      dd/mm/yyyy or ISO dates). An official raw CSV also works.

Writes DIR/changelog.md (concise, human-readable) and DIR/diff.json (full lists).
Both are deterministic: stable ordering, no timestamps, no absolute paths, so they can
be committed and re-generated byte-identically. Inputs are identified by file name,
size and sha256 only.

Conventions (repeated in the outputs):
  * Comparison basis is unique Ref IDs; where a Ref ID repeats, the first row is kept
    and the duplicate is reported (identical or conflicting).
  * Capacity = "Installed Capacity (MWelec)". Blank / non-numeric = UNKNOWN, never zero:
    MW totals sum known capacities only and carry the unknown count alongside.
  * A capacity edit is |new - old| > --capacity-tolerance (default 0.0051 MW) so that a
    2-decimal CSV compared with an Excel-precision file does not report rounding noise.
  * Milestone categories (status-based, as in the July->October prototype):
      newly consented          new status Awaiting Construction, previous status not
                               Awaiting Construction / Under Construction / Operational
      newly under construction new Under Construction, previous not Under Construction / Operational
      newly operational        new Operational, previous not Operational
      newly refused            new Application Refused / Appeal Refused, previous not refused
      newly withdrawn          new Application Withdrawn / Appeal Withdrawn, previous not withdrawn
    "transition" = ref in both releases whose status moved; "new record" = ref absent
    from the previous release that first appears already in that status. MW = new capacity.

Hash guard ("no truncation of previous work"): the inputs and every --protect path
(file or directory, recursively) are sha256-hashed before and after the run; the run
fails (exit 3) if any differs, and refuses an --out directory inside a protected path.

Standard library only. No network.
"""
from __future__ import annotations

import argparse
import csv
import hashlib
import io
import json
import math
import os
import re
import sys
from collections import Counter, defaultdict
from datetime import date, datetime
from pathlib import Path

TOOL = "automation/repd/diff.py"
SCHEMA = "globalgrid2050.repd-release-diff.v1"

REF = "Ref ID"
CAP = "Installed Capacity (MWelec)"
TECH = "Technology Type"
STATUS = "Development Status (short)"
SITE = "Site Name"
OPER = "Operator (or Applicant)"
UPDATED = "Record Last Updated (dd/mm/yyyy)"
COUNTRY = "Country"
REGION = "Region"
COUNTY = "County"

SOLAR = "Solar Photovoltaics"
BATTERY = "Battery"

DATE_COLS = {
    UPDATED, "Planning Application Submitted", "Planning Application Withdrawn",
    "Planning Permission Refused", "Appeal Lodged", "Appeal Withdrawn", "Appeal Refused",
    "Appeal Granted", "Planning Permission Granted", "Secretary of State - Intervened",
    "Secretary of State - Refusal", "Secretary of State - Granted",
    "Planning Permission Expired", "Under Construction", "Operational",
}
NUM_COLS = {
    CAP, "CfD Capacity (MW)", "Turbine Capacity (MW)", "No. of Turbines",
    "Height of Turbines (m)", "X-coordinate", "Y-coordinate", "Solar Site Area (sqm)",
}
REQUIRED = [REF, CAP, TECH, STATUS, SITE, OPER]
HEADER_ALIASES = {"record last updated": UPDATED}

# project_identity_v6.json key -> official column (from work4/jul_vs_oct_all_tech.py)
IDENTITY_MAPPING = [
    ("repd_ref", REF),
    ("repd_old_ref", "Old Ref ID"),
    ("repd_record_updated", UPDATED),
    ("operator", OPER),
    ("site_name", SITE),
    ("technology", TECH),
    ("capacity_mw", CAP),
    ("status", STATUS),
    ("county", COUNTY),
    ("region", REGION),
    ("country", COUNTRY),
    ("planning_authority", "Planning Authority"),
    ("planning_application_reference", "Planning Application Reference"),
    ("planning_application_submitted", "Planning Application Submitted"),
    ("planning_application_withdrawn", "Planning Application Withdrawn"),
    ("planning_permission_refused", "Planning Permission Refused"),
    ("planning_permission_granted", "Planning Permission Granted"),
    ("planning_permission_expired", "Planning Permission Expired"),
    ("under_construction", "Under Construction"),
    ("operational", "Operational"),
]

ST_CONSENTED = "Awaiting Construction"
ST_UC = "Under Construction"
ST_OP = "Operational"
REFUSED = {"Application Refused", "Appeal Refused"}
WITHDRAWN = {"Application Withdrawn", "Appeal Withdrawn"}
# statuses counted as "live" for the top-50 solar list (solar_bess_focus.py buckets)
LIVE = {"Operational", "Under Construction", "Awaiting Construction", "No Application Required",
        "Application Submitted", "Appeal Lodged"}

MILESTONES = [
    ("consented", "Newly consented",
     lambda o, n: n == ST_CONSENTED and o not in (ST_CONSENTED, ST_UC, ST_OP)),
    ("under_construction", "Newly under construction",
     lambda o, n: n == ST_UC and o not in (ST_UC, ST_OP)),
    ("operational", "Newly operational", lambda o, n: n == ST_OP and o != ST_OP),
    ("refused", "Newly refused (application or appeal)",
     lambda o, n: n in REFUSED and o not in REFUSED),
    ("withdrawn", "Newly withdrawn (application or appeal)",
     lambda o, n: n in WITHDRAWN and o not in WITHDRAWN),
]
MILESTONE_DEFINITIONS = {
    "consented": "new status 'Awaiting Construction'; previous status not Awaiting Construction / Under Construction / Operational",
    "under_construction": "new status 'Under Construction'; previous status not Under Construction / Operational",
    "operational": "new status 'Operational'; previous status not Operational",
    "refused": "new status Application Refused or Appeal Refused; previous status neither",
    "withdrawn": "new status Application Withdrawn or Appeal Withdrawn; previous status neither",
    "basis": "transition = ref in both releases whose status moved; new record = ref absent from the previous release, first seen already in that status. MW = new-release capacity; blank capacity unknown.",
}

DEFAULT_CAP_TOL = 0.0051
_WS = re.compile(r"\s+")


class DiffError(Exception):
    """Fail-closed error with a clear message."""


# --------------------------------------------------------------------------- normalisation

def collapse(value) -> str:
    if value is None:
        return ""
    return _WS.sub(" ", str(value).replace("_x000D_", " ")).strip()


def clean_ref(value) -> str:
    text = collapse(value)
    if re.fullmatch(r"\d+\.0+", text):
        text = text.split(".")[0]
    return text


def parse_num(value):
    """float or None. Blank / non-numeric -> None (unknown, never zero)."""
    if isinstance(value, (int, float)) and not isinstance(value, bool):
        return float(value) if math.isfinite(value) else None
    text = collapse(value).replace(",", "").replace(" ", "")
    if not text:
        return None
    try:
        number = float(text)
    except ValueError:
        return None
    return number if math.isfinite(number) else None


_DATE_PATTERNS = ("%d/%m/%Y", "%Y-%m-%d", "%Y-%m-%d %H:%M:%S", "%Y-%m-%dT%H:%M:%S",
                  "%d/%m/%Y %H:%M:%S", "%d/%m/%Y %H:%M")


def parse_date(value):
    """date or None (blank or unparseable). Month-first is NOT accepted."""
    text = collapse(value)
    if not text:
        return None
    for pattern in _DATE_PATTERNS:
        try:
            return datetime.strptime(text, pattern).date()
        except ValueError:
            continue
    return None


def norm_value(col: str, raw) -> str:
    text = collapse(raw)
    if not text:
        return ""
    if col in DATE_COLS:
        parsed = parse_date(text)
        return parsed.isoformat() if parsed else text
    if col in NUM_COLS:
        number = parse_num(text)
        return repr(number) if number is not None else text
    return text


def values_differ(col: str, a, b, tol: float) -> bool:
    """Normalised comparison; numeric columns equal within an absolute tolerance."""
    va, vb = norm_value(col, a), norm_value(col, b)
    if va == vb:
        return False
    if col in NUM_COLS:
        x, y = parse_num(a), parse_num(b)
        if x is not None and y is not None and abs(x - y) <= tol:
            return False
    return True


def r3(x):
    return None if x is None else round(float(x) + 0.0, 3)


def ref_key(ref: str):
    return (0, int(ref), "") if ref.isdigit() else (1, 0, ref)


def sha256_file(path) -> str:
    h = hashlib.sha256()
    with open(path, "rb") as f:
        for chunk in iter(lambda: f.read(1 << 20), b""):
            h.update(chunk)
    return h.hexdigest()


# --------------------------------------------------------------------------- loading

def _canon_header(name: str) -> str:
    text = collapse(str(name).replace("\ufeff", ""))
    return HEADER_ALIASES.get(text.casefold(), text)


def _finish(records: list, header: list, info: dict) -> dict:
    """Index records by Ref ID (first kept), report duplicates."""
    groups = defaultdict(list)
    blank_refs = 0
    for rec in records:
        ref = clean_ref(rec.get(REF, ""))
        rec["__ref"] = ref
        if not ref:
            blank_refs += 1
            continue
        groups[ref].append(rec)
    by_ref, dups = {}, []
    for ref in sorted(groups, key=ref_key):
        recs = groups[ref]
        by_ref[ref] = recs[0]
        if len(recs) > 1:
            conflicting = sorted({c for other in recs[1:] for c in header
                                  if collapse(other.get(c)) != collapse(recs[0].get(c))})
            dups.append({"ref": ref, "rows": len(recs), "site": collapse(recs[0].get(SITE)),
                         "kind": "conflicting" if conflicting else "identical",
                         "conflicting_fields": conflicting})
    upd = [parse_date(r.get(UPDATED, "")) for r in by_ref.values()]
    upd = [d for d in upd if d]
    info.update({
        "source_rows": len(records),
        "unique_refs": len(by_ref),
        "blank_ref_rows": blank_refs,
        "duplicate_refs": dups,
        "max_record_last_updated": max(upd).isoformat() if upd else None,
    })
    return {"info": info, "by_ref": by_ref, "header": header}


def load_csv(path, header_reference=None) -> dict:
    raw = Path(path).read_bytes()
    text, encoding = None, None
    for enc in ("utf-8-sig", "cp1252"):
        try:
            text, encoding = raw.decode(enc), enc
            break
        except UnicodeDecodeError:
            continue
    if text is None:
        raise DiffError(f"{path}: cannot decode as utf-8-sig or cp1252")
    csv.field_size_limit(1 << 30)
    try:
        rows = list(csv.reader(io.StringIO(text, newline=""), strict=True))
    except csv.Error as exc:
        raise DiffError(f"{path}: CSV parse error ({exc}); refusing to diff a malformed file")
    if not rows:
        raise DiffError(f"{path}: empty file")
    header = [_canon_header(h) for h in rows[0]]
    if header_reference:
        by_fold = {h.casefold(): h for h in header_reference}
        header = [by_fold.get(h.casefold(), h) for h in header]
    dup_h = sorted(h for h, n in Counter(header).items() if n > 1)
    if dup_h:
        raise DiffError(f"{path}: duplicate headers after normalisation: {dup_h}")
    missing = [c for c in REQUIRED if c not in header]
    if missing:
        raise DiffError(f"{path}: required columns missing: {missing}")
    ncol = len(header)
    records, ragged = [], 0
    for row in rows[1:]:
        if not row or all(not c.strip() for c in row):
            continue
        if len(row) != ncol:
            ragged += 1
            row = (row + [""] * ncol)[:ncol]
        records.append(dict(zip(header, row)))
    if ragged:
        raise DiffError(f"{path}: {ragged} rows have the wrong number of fields (expected {ncol})")
    info = {"file": Path(path).name, "bytes": len(raw), "sha256": hashlib.sha256(raw).hexdigest(),
            "kind": "official-layout CSV", "encoding": encoding, "n_columns": ncol,
            "fidelity": "full official layout"}
    return _finish(records, header, info)


def load_identity_json(path) -> dict:
    raw = Path(path).read_bytes()
    try:
        doc = json.loads(raw.decode("utf-8"))
    except (UnicodeDecodeError, json.JSONDecodeError) as exc:
        raise DiffError(f"{path}: not valid UTF-8 JSON ({exc})")
    if not isinstance(doc, dict) or not isinstance(doc.get("records"), list):
        raise DiffError(f"{path}: expected an object with a 'records' list "
                        "(globalgrid2050 project_identity_v6.json layout)")
    if doc.get("schema") and "project-identity" not in str(doc["schema"]):
        raise DiffError(f"{path}: schema {doc['schema']!r} is not a project-identity file; "
                        "pre-thresholded files (major_projects) cannot be a full baseline")
    header = [col for _, col in IDENTITY_MAPPING]
    records = []
    for i, src in enumerate(doc["records"]):
        if "repd_ref" not in src:
            raise DiffError(f"{path}: record {i} has no repd_ref")
        if src.get("identity_status") not in (None, "REPD_BOUND"):
            continue  # globalgrid-only identities are not REPD records
        rec = {}
        for key, col in IDENTITY_MAPPING:
            value = src.get(key)
            if key == "capacity_mw" and src.get("capacity_known") is False:
                value = None
            rec[col] = "" if value is None else (repr(float(value)) if col == CAP else str(value))
        records.append(rec)
    declared = doc.get("raw_record_count")
    info = {"file": Path(path).name, "bytes": len(raw), "sha256": hashlib.sha256(raw).hexdigest(),
            "kind": f"derived JSON ({doc.get('schema', 'unknown schema')})",
            "encoding": "utf-8", "n_columns": len(header),
            "fidelity": (f"derived: {len(header)} of 53 official columns; other columns not compared; "
                         "raw previous CSV not used"),
            "declared_source_title": doc.get("source_dataset_title"),
            "declared_source_csv_sha256": (doc.get("source_hashes") or {}).get("csv_sha256"),
            "declared_raw_record_count": declared}
    snap = _finish(records, header, info)
    if declared is not None and declared != snap["info"]["unique_refs"]:
        raise DiffError(f"{path}: declares raw_record_count={declared} but holds "
                        f"{snap['info']['unique_refs']} unique REPD refs")
    return snap


def load_previous(path, header_reference=None) -> dict:
    with open(path, "rb") as f:
        head = f.read(64).lstrip(b"\xef\xbb\xbf").lstrip()
    if str(path).lower().endswith(".json") or head.startswith(b"{"):
        return load_identity_json(path)
    return load_csv(path, header_reference)


# --------------------------------------------------------------------------- aggregation

class Agg:
    __slots__ = ("n", "mw", "unknown")

    def __init__(self):
        self.n, self.mw, self.unknown = 0, 0.0, 0

    def add(self, mw):
        self.n += 1
        if mw is None:
            self.unknown += 1
        else:
            self.mw += mw

    def out(self):
        return {"n": self.n, "mw": r3(self.mw), "n_unknown_mw": self.unknown}


def cap_of(rec):
    return parse_num(rec.get(CAP, ""))


def text(rec, col):
    return collapse(rec.get(col, "")) or "(blank)"


def total(recs) -> dict:
    a = Agg()
    for r in recs:
        a.add(cap_of(r))
    return a.out()


def group(recs, keyf) -> dict:
    out = defaultdict(Agg)
    for r in recs:
        out[keyf(r)].add(cap_of(r))
    return {k: out[k].out() for k in sorted(out)}


def compare_groups(old_recs, new_recs, keyf) -> list:
    a, b = group(old_recs, keyf), group(new_recs, keyf)
    zero = Agg().out()
    rows = []
    for k in sorted(set(a) | set(b)):
        x, y = a.get(k, zero), b.get(k, zero)
        rows.append({"key": k, "old_n": x["n"], "new_n": y["n"], "delta_n": y["n"] - x["n"],
                     "old_mw": x["mw"], "new_mw": y["mw"], "delta_mw": r3(y["mw"] - x["mw"]),
                     "old_n_unknown_mw": x["n_unknown_mw"], "new_n_unknown_mw": y["n_unknown_mw"]})
    return rows


def brief(rec) -> dict:
    return {"ref": rec["__ref"], "site": collapse(rec.get(SITE)), "operator": collapse(rec.get(OPER)),
            "technology": text(rec, TECH), "status": text(rec, STATUS), "mw": r3(cap_of(rec)),
            "country": collapse(rec.get(COUNTRY)), "region": collapse(rec.get(REGION))}


def by_mw_desc(item_mw, ref):
    """sort key: known MW descending, unknown last, then ref."""
    return (item_mw is None, -(item_mw or 0.0), ref_key(ref))


# --------------------------------------------------------------------------- diff

def build_diff(old: dict, new: dict, old_label: str, new_label: str,
               cap_tol: float = DEFAULT_CAP_TOL) -> dict:
    O, N = old["by_ref"], new["by_ref"]
    oh, nh = old["header"], new["header"]
    shared = [c for c in nh if c in oh]
    added = sorted(set(N) - set(O), key=ref_key)
    removed = sorted(set(O) - set(N), key=ref_key)
    retained = sorted(set(O) & set(N), key=ref_key)
    old_recs = [O[r] for r in sorted(O, key=ref_key)]
    new_recs = [N[r] for r in sorted(N, key=ref_key)]
    added_recs = [N[r] for r in added]
    removed_recs = [O[r] for r in removed]

    # ---- totals
    totals = {
        "overall": compare_groups(old_recs, new_recs, lambda r: "ALL")[0],
        "by_technology": compare_groups(old_recs, new_recs, lambda r: text(r, TECH)),
        "by_status": compare_groups(old_recs, new_recs, lambda r: text(r, STATUS)),
        "by_country": compare_groups(old_recs, new_recs, lambda r: text(r, COUNTRY)),
        "by_technology_status": compare_groups(
            old_recs, new_recs, lambda r: text(r, TECH) + " | " + text(r, STATUS)),
    }

    # ---- added / removed
    def ranked(recs):
        return sorted((brief(r) for r in recs), key=lambda b: by_mw_desc(b["mw"], b["ref"]))

    records = {
        "added": {"total": total(added_recs),
                  "by_technology": group(added_recs, lambda r: text(r, TECH)),
                  "by_status": group(added_recs, lambda r: text(r, STATUS)),
                  "records_by_mw": ranked(added_recs)},
        "removed": {"total": total(removed_recs),
                    "by_technology": group(removed_recs, lambda r: text(r, TECH)),
                    "records_by_mw": ranked(removed_recs)},
        "retained": len(retained),
    }