GLOBALGRID2050 / EXPLORE CODE

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

Renewable Energy Planning Database (REPD) Clean and 1 more file (part 1)

A Python command-line tool in the automation folder of GlobalGrid2050 that hashes paths, builds log and verifies against official, covering official, REPD cleaned and cleaning log, using SHA-256.

700 lines of Python from globalgrid2050, in 2 files. Topic: Electricity markets and data pipelines. Section 819 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) Build V6 storage · globalgrid2050 / automation/repd/build_v6.py lines 1–241
  2. Renewable Energy Planning Database (REPD) Clean storage · globalgrid2050 / automation/repd/clean.py lines 1–459

Renewable Energy Planning Database (REPD) Build V6

A Python command-line tool in the automation folder of GlobalGrid2050 that reads project identity, major projects, major project news and the REPD register, using SHA-256.

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

What it does
It loads project identity, major projects, major project news and the REPD register. Defines 7 functions or classes, including sha256_file, hash_manifest, compare_manifests, load_json, spine_population. Uses libraries __future__, argparse, glob, hashlib, json. 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: the REPD register.
Inputs & outputs
In: JSON file project_identity_v6.json; JSON file major_projects_v6.json; JSON file major_project_news_v6.json; command-line arguments.
Downstream impact
Used directly by 1 file: Test Build V6 (globalgrid2050). Reached from 1 other entry point, including GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
What it achieves
It hashes manifest (`hash_manifest`), compares manifests (`compare_manifests`) and loads JSON (`load_json`). Run the EXISTING V6 identity chain for a new REPD release, additively. Its code works with 1 MW, 1.0 MW and 100 MW. It accepts `--descriptor`, `--out` and `--input-root`.
Why it matters
Checked by Test Build V6.
Application
globalgrid2050 · automation/repd · Python CLI
Uses
__future__, argparse, glob, hashlib, json, os, subprocess, sys
Used by
imported by Test Build V6 (sys.path import)
Produces
sha256_file, hash_manifest, compare_manifests, load_json, spine_population, stability_report, main
Defines here
sha256_file, hash_manifest, compare_manifests, load_json, spine_population, stability_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 automation/repd/build_v6.py:1-241 · blob 0d040bc5d4683884bc6a801c3cbf56676aefa332 · 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
"""Run the EXISTING V6 identity chain for a new REPD release, additively.

Stages (unchanged scripts, parameterised by a release descriptor through env vars):
  scripts/validate_repd_sources_v6.py      reconcile official CSV+XLSX (offline bytes or fetch)
  scripts/validate_v6_manifest_provenance.py
  scripts/build_project_identity_v6.py      identity registry + major projects (solar >1 MW, BESS >100 MW)
  scripts/validate_project_identity_v6.py   integrity gates (frozen V6 news/links read, never written)
then an identity-stability report against the previous release.

Every output goes to --out/{dist,data}/ with the descriptor's suffix (e.g. 2026q3). The frozen
*_v6 files are never written. A sha256 manifest of every protected file under --input-root
is taken before and after; any difference fails the run ("no truncation of previous work").
News headlines are NOT regenerated.
"""
from __future__ import annotations

import argparse
import glob
import hashlib
import json
import os
import subprocess
import sys
from pathlib import Path

HERE = Path(__file__).resolve()
DEFAULT_SCRIPTS = HERE.parents[2] / "scripts"
DEFAULT_PROTECTED = [
    "dist/*",
    "repd*.csv",
    "uk_renewables_pipeline/dashboard*.html",
    "uk_renewables_pipeline/v9.5.1/**/*",
    "uk_renewables_pipeline/202609082224/**/*",
]
STAGES = [
    "validate_repd_sources_v6.py",
    "validate_v6_manifest_provenance.py",
    "build_project_identity_v6.py",
    "validate_project_identity_v6.py",
]
SPINE_TECH = {"Solar Photovoltaics", "Battery", "Wind Onshore", "Wind Offshore"}


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


def hash_manifest(root: Path, patterns: list[str]) -> dict[str, str]:
    files = set()
    for pattern in patterns:
        for name in glob.glob(str(root / pattern), recursive=True):
            if Path(name).is_file():
                files.add(Path(name))
    return {str(p.relative_to(root)): sha256_file(p) for p in sorted(files)}


def compare_manifests(before: dict, after: dict) -> list[str]:
    problems = [f"changed: {k}" for k in before if k in after and before[k] != after[k]]
    problems += [f"removed: {k}" for k in before if k not in after]
    return problems


def load_json(path: Path):
    return json.loads(path.read_text(encoding="utf-8"))


def spine_population(records: list[dict]) -> dict:
    rows = [r for r in records if r.get("technology") in SPINE_TECH
            and r.get("capacity_mw") is not None and r["capacity_mw"] >= 1.0]
    by_tech = {t: sum(r["technology"] == t for r in rows) for t in sorted(SPINE_TECH)}
    return {"count": len(rows), "by_technology": by_tech,
            "capacity_mw": round(sum(r["capacity_mw"] for r in rows), 2),
            "rule": "technology in {Solar Photovoltaics, Battery, Wind Onshore, Wind Offshore} and capacity >= 1.0 MW (release.v9.1 spine rule; informational, spine not built here)"}


def stability_report(old_identity: dict, new_identity: dict, old_projects: dict, new_projects: dict,
                     news: dict | None = None) -> dict:
    old = {r["repd_ref"]: r for r in old_identity["records"] if r.get("repd_ref")}
    new = {r["repd_ref"]: r for r in new_identity["records"] if r.get("repd_ref")}
    retained = sorted(set(old) & set(new), key=lambda v: (len(v), v))
    project_id_changed = [ref for ref in retained if old[ref]["gg_project_id"] != new[ref]["gg_project_id"]]
    dev_changed = [
        {"repd_ref": ref, "site_name": new[ref]["site_name"],
         "old_gg_development_id": old[ref]["gg_development_id"],
         "new_gg_development_id": new[ref]["gg_development_id"],
         "old_development_repd_refs": old[ref]["development_repd_refs"],
         "new_development_repd_refs": new[ref]["development_repd_refs"]}
        for ref in retained if old[ref]["gg_development_id"] != new[ref]["gg_development_id"]
    ]
    old_devs = {r["gg_development_id"] for r in old.values()}
    new_devs = {r["gg_development_id"] for r in new.values()}
    old_p = {p["repd_ref"]: p for p in old_projects["projects"]}
    new_p = {p["repd_ref"]: p for p in new_projects["projects"]}
    news_refs = sorted({i.get("repd_ref") for i in (news or {}).get("items", []) if i.get("repd_ref")})
    return {
        "schema": "globalgrid2050.identity-stability.v1",
        "baseline": {"source_dataset_title": old_identity.get("source_dataset_title"),
                     "source_hashes": old_identity.get("source_hashes"), "records": len(old)},
        "candidate": {"source_dataset_title": new_identity.get("source_dataset_title"),
                      "source_hashes": new_identity.get("source_hashes"), "records": len(new)},
        "gg_project_id": {
            "preserved": len(retained) - len(project_id_changed),
            "changed": len(project_id_changed),
            "new": len(set(new) - set(old)),
            "retired": len(set(old) - set(new)),
            "retired_refs": sorted(set(old) - set(new), key=lambda v: (len(v), v)),
            "rule": "GG2050-REPD-<Ref ID>: deterministic, so every retained Ref keeps its ID",
        },
        "gg_development_id": {
            "retained_refs_preserved": len(retained) - len(dev_changed),
            "retained_refs_changed": len(dev_changed),
            "changed": dev_changed,
            "distinct_ids_baseline": len(old_devs),
            "distinct_ids_candidate": len(new_devs),
            "distinct_ids_kept": len(old_devs & new_devs),
            "distinct_ids_new": len(new_devs - old_devs),
            "distinct_ids_retired": len(old_devs - new_devs),
        },
        "major_projects": {
            "baseline_count": len(old_p), "candidate_count": len(new_p),
            "baseline_projects_sha256": old_projects.get("projects_sha256"),
            "candidate_projects_sha256": new_projects.get("projects_sha256"),
            "retained": len(set(old_p) & set(new_p)),
            "entered": len(set(new_p) - set(old_p)),
            "exited": len(set(old_p) - set(new_p)),
            "exited_refs": sorted(set(old_p) - set(new_p), key=lambda v: (len(v), v)),
            "entered_existing_refs": sorted((set(new_p) - set(old_p)) & set(old), key=lambda v: (len(v), v)),
        },
        "frozen_v6_news_bindings": {
            "refs": news_refs,
            "still_in_identity": [r for r in news_refs if r in new],
            "still_in_major_projects": [r for r in news_refs if r in new_p],
            "development_id_changed": [r for r in news_refs if r in old and r in new
                                       and old[r]["gg_development_id"] != new[r]["gg_development_id"]],
        },
        "spine_population_baseline": spine_population(list(old.values())),
        "spine_population_candidate": spine_population(list(new.values())),
    }


def main(argv=None) -> int:
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument("--descriptor", required=True, help="release descriptor JSON (e.g. releases_v6/v6_2026q3.json)")
    parser.add_argument("--out", required=True, help="output directory (dist/ and data/ are created inside)")
    parser.add_argument("--input-root", required=True, help="read-only repo checkout (frozen V6 baseline, news inputs)")
    parser.add_argument("--csv", default="", help="offline mode: local official CSV")
    parser.add_argument("--xlsx", default="", help="offline mode: local official XLSX")
    parser.add_argument("--scripts", default=str(DEFAULT_SCRIPTS), help="directory holding the V6 scripts")
    parser.add_argument("--validated-at", default="", help="pin validated_at for byte-reproducible reruns")
    parser.add_argument("--protect", action="append", default=None, help="glob (relative to input root) of files that must not change")
    args = parser.parse_args(argv)

    descriptor_path = Path(args.descriptor).resolve()
    descriptor = load_json(descriptor_path)
    suffix = descriptor["output_suffix"]
    out = Path(args.out).resolve()
    root = Path(args.input_root).resolve()
    scripts = Path(args.scripts).resolve()
    if suffix == "v6":
        raise SystemExit("descriptor output_suffix 'v6' would overwrite frozen V6 files")
    out.mkdir(parents=True, exist_ok=True)
    planned = [out / "dist" / f"{stem}_{suffix}.json" for stem in
               ("repd_source_reconciliation", "manifest", "project_identity", "major_projects")]
    for path in planned:
        if path.exists() and root in path.parents and out == root:
            raise SystemExit(f"refusing to overwrite an existing file in the input root: {path}")

    protected = args.protect or DEFAULT_PROTECTED
    before = hash_manifest(root, protected)
    env = dict(os.environ)
    env.update({"REPD_RELEASE_DESCRIPTOR": str(descriptor_path), "REPD_OUT_DIR": str(out),
                "REPD_INPUT_ROOT": str(root)})
    if args.validated_at:
        env["REPD_VALIDATED_AT"] = args.validated_at
    if bool(args.csv) != bool(args.xlsx):
        raise SystemExit("offline mode needs both --csv and --xlsx")
    if args.csv:
        env["REPD_SOURCE_CSV_FILE"] = str(Path(args.csv).resolve())
        env["REPD_SOURCE_XLSX_FILE"] = str(Path(args.xlsx).resolve())

    results = []
    ok = True
    for stage in STAGES:
        proc = subprocess.run([sys.executable, str(scripts / stage)], cwd=str(scripts), env=env,
                              capture_output=True, text=True)
        tail = (proc.stdout + proc.stderr).strip().splitlines()[-12:]
        results.append({"stage": stage, "returncode": proc.returncode, "output_tail": tail})
        print(f"[{'PASS' if proc.returncode == 0 else 'FAIL'}] {stage}: {tail[-1] if tail else ''}")
        if proc.returncode != 0:
            ok = False
            break

    after = hash_manifest(root, protected)
    problems = compare_manifests(before, after)
    report = {
        "schema": "globalgrid2050.repd-build-v6-run.v1",
        "release_id": descriptor["release_id"],
        "descriptor": str(descriptor_path),
        "descriptor_sha256": sha256_file(descriptor_path),
        "offline_sources": {"csv": env.get("REPD_SOURCE_CSV_FILE"), "xlsx": env.get("REPD_SOURCE_XLSX_FILE")},
        "stages": results,
        "protected_files": {"patterns": protected, "count": len(before), "unchanged": not problems,
                            "problems": problems, "sha256_before": before},
        "outputs": {},
    }
    baseline_identity = root / descriptor.get("baseline_identity", "dist/project_identity_v6.json")
    baseline_projects = root / descriptor.get("baseline_projects", "dist/major_projects_v6.json")
    if ok and not (baseline_identity.exists() and baseline_projects.exists()):
        print(f"[SKIP] stability report: baseline missing under {root}")
    elif ok:
        dist = out / "dist"
        news_path = root / descriptor.get("news_input", "dist/major_project_news_v6.json")
        stability = stability_report(
            load_json(baseline_identity),
            load_json(dist / f"project_identity_{suffix}.json"),
            load_json(baseline_projects),
            load_json(dist / f"major_projects_{suffix}.json"),
            load_json(news_path) if news_path.exists() else None,
        )
        (dist / f"project_identity_{suffix}_stability.json").write_text(json.dumps(stability, indent=2), encoding="utf-8")
        g, d = stability["gg_project_id"], stability["gg_development_id"]
        print(f"[INFO] gg_project_id preserved={g['preserved']} changed={g['changed']} new={g['new']} retired={g['retired']}; "
              f"gg_development_id changed={d['retained_refs_changed']} {[c['repd_ref'] for c in d['changed']]}")
    for sub in ("dist", "data"):
        for path in sorted((out / sub).glob("*")) if (out / sub).exists() else []:
            report["outputs"][f"{sub}/{path.name}"] = {"sha256": sha256_file(path), "bytes": path.stat().st_size}
    (out / f"build_v6_run_{suffix}.json").write_text(json.dumps(report, indent=2), encoding="utf-8")
    if problems:
        print("[FAIL] protected files changed:", problems[:20])
        return 2
    print(f"[{'PASS' if ok else 'FAIL'}] protected files unchanged ({len(before)} hashed)")
    return 0 if ok else 1


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

Renewable Energy Planning Database (REPD) Clean

A Python command-line tool in the automation folder of GlobalGrid2050 that hashes paths, builds log and verifies against official, covering official, REPD cleaned and cleaning log, using SHA-256.

storageglobalgrid2050 / automation/repd/clean.py · lines 1–459 of 848 · Entry point · pattern hash_paths (shared by 2 files)

What it does
It lists and searches official, REPD cleaned, cleaning log and the REPD register. Defines 21 functions or classes, including CleaningRejected, __init__, CleanOptions, CleanResult, sha256. Uses libraries __future__, argparse, csv, hashlib, io. 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: CSV file official.csv; Excel file official.xlsx; CSV file REPD_cleaned.csv; JSON file cleaning_log.json; command-line arguments. Out: JSON file cleaning_log.json.
Downstream impact
Used directly by 1 file: Conftest (globalgrid2050). Reached from 4 other entry points, including GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050); Test Clean (globalgrid2050); Test Date Rule (globalgrid2050).
What it achieves
It cleans options (`CleanOptions`), cleans result (`CleanResult`) and cleans text (`clean_text`). REPD cleaning step: official CSV + XLSX -> canonical cleaned CSV + complete cleaning log. Its code works with 0.0050001 MW. It accepts `--csv`, `--xlsx` and `--out`.
Why it matters
Checked by Conftest.
Application
globalgrid2050 · automation/repd · Python CLI
Uses
Renewable Energy Planning Database (REPD) Date Rule (relative import), __future__, argparse, csv, hashlib, io, json, math, os
Used by
imported by Conftest (sys.path import)
Produces
CleaningRejected, CleanOptions, CleanResult, sha256, clean_text, parse_number, format_number, excel_text, hash_paths, manifest_diff, serialise, clean
Defines here
CleaningRejected, __init__, CleanOptions, CleanResult, sha256, clean_text, parse_number, format_number, excel_text, _cmp_norm, hash_paths, manifest_diff, serialise, clean
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/clean.py:1-459 · blob a2cc23b0ee8f567a7c7f071eb864077cda66d530 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
"""REPD cleaning step: official CSV + XLSX -> canonical cleaned CSV + complete cleaning log.

Policy (every change is counted and listed cell by cell in the log; nothing else changes):

* Rows: identical duplicate records (all fields byte-equal in the CSV, and the same record
  repeated the same number of times in the workbook) are kept once.  A conflicting
  duplicate Ref ID, a blank Ref ID, or a different Ref ID set between CSV and workbook
  rejects the release.
* Columns: the official CSV column order and header text are kept.  ``--normalise-headers``
  collapses whitespace runs in header names (logged).
* Date columns (the 16 official date columns are required by default, plus any column the
  workbook typing proves to be a date column): the general date rule in ``date_rule.py``.
  The typed Excel date wins; CSV month-first text is accepted only where that cell's own
  Excel number format is explicitly month-first; no ref allow-list.  Output is strict
  dd/mm/yyyy.  Blank-equivalent text (whitespace, NA, N/A) becomes blank and is counted.
  Any unexplained cell rejects the release.
* Numbers stored as dates (a non-date column whose workbook cell is a number before
  1 March 1900 carrying a date format, e.g. "Offshore Wind Round" 1, 2, 2.5, 3 printed in
  the CSV as 01/01/1900 ...): restored to the workbook number, after checking the CSV text
  is exactly that serial rendered as a date.
* Other text: an edge run of whitespace at the start or end of a cell that contains a tab,
  CR or LF is removed (edge runs of plain spaces are left alone); inside the cell each line
  break run (with the spaces/tabs around it) becomes one space.  Text ``NA`` and
  whitespace-only cells outside date columns are data and are kept exactly.
* Installed Capacity: kept exactly as the official CSV text.  ``--capacity-source excel``
  substitutes the workbook value (.15g) where it agrees with the CSV within 0.0050001 MW.
* Output: UTF-8 without BOM, LF line endings, csv.QUOTE_MINIMAL.

The log ends with a self-verification: the written file is re-read and compared cell by
cell with the official CSV; every difference must be a logged change and every logged
change a difference.  A hash manifest of the inputs and of any ``--protect`` path is taken
before and after the run; any difference fails the run.
"""
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 dataclasses import dataclass, field
from datetime import date, datetime, timezone
from pathlib import Path

try:  # package import (automation.repd.clean) or standalone script
    from . import date_rule as dr
except ImportError:  # pragma: no cover - exercised when run as a script
    sys.path.insert(0, str(Path(__file__).resolve().parent))
    import date_rule as dr  # type: ignore

from openpyxl.utils.datetime import to_excel

TOOL = "automation/repd/clean.py"
LOG_SCHEMA = "repd-cleaning-log/1"
CAPACITY_COLUMN = "Installed Capacity (MWelec)"
REF_COLUMN = "Ref ID"
CAPACITY_TOLERANCE_MW = 0.0050001
NUMERIC_TOLERANCE = 0.0050001

# Header names after whitespace collapse.  Required so that a column that happens to be
# wholly blank in the workbook is still validated as a date column.
DEFAULT_REQUIRED_DATE_COLUMNS = (
    "Record Last Updated (dd/mm/yyyy)",
    "Judicial Review",
    "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",
)
# Columns whose dates are legitimately in the future (not flagged against --as-of).
DEFAULT_FUTURE_OK_COLUMNS = ("Planning Permission Expired",)

# Change kinds (the complete vocabulary; every changed cell carries one or more).
K_HEADER = "header_whitespace_normalised"
K_DUP = "identical_duplicate_row_removed"
K_EDGE = "edge_control_whitespace_trimmed"
K_BREAK = "embedded_line_break_replaced"
K_DATE_MF = "date_month_first_corrected"
K_DATE_NA = "date_na_text_blanked"
K_DATE_WS = "date_whitespace_blanked"
K_DATE_OTHER = "date_text_normalised"
K_NUM_DATE = "number_stored_as_date_restored"
K_CAPACITY = "capacity_excel_precision"
K_EDGE_SPACE = "edge_space_trimmed"              # only with --whitespace all
K_WS_BLANK = "whitespace_only_cell_blanked"      # only with --whitespace all
CELL_KINDS = (K_EDGE, K_BREAK, K_EDGE_SPACE, K_WS_BLANK, K_DATE_MF, K_DATE_NA, K_DATE_WS, K_DATE_OTHER, K_NUM_DATE, K_CAPACITY)
ALL_KINDS = (K_HEADER, K_DUP) + CELL_KINDS

_EDGE_LEAD = re.compile(r"\A[ \t\r\n]+")
_EDGE_TRAIL = re.compile(r"[ \t\r\n]+\Z")
_BREAK = re.compile(r"[ \t]*[\r\n]+[ \t]*")
_STRICT_DATE = re.compile(r"\d{2}/\d{2}/\d{4}")


class CleaningRejected(RuntimeError):
    """The release cannot be cleaned without inventing or guessing data."""

    def __init__(self, reasons: list[str]):
        super().__init__("; ".join(reasons))
        self.reasons = reasons


@dataclass
class CleanOptions:
    capacity_source: str = "csv"            # csv | excel
    whitespace: str = "control"             # control (default) | all
    normalise_headers: bool = False
    required_date_columns: tuple[str, ...] = DEFAULT_REQUIRED_DATE_COLUMNS
    sheet: str | None = None
    as_of: date | None = None
    future_ok_columns: tuple[str, ...] = DEFAULT_FUTURE_OK_COLUMNS
    expected_csv_sha256: str | None = None
    expected_xlsx_sha256: str | None = None


@dataclass
class CleanResult:
    header: list[str]
    rows: list[list[str]]
    log: dict
    csv_bytes: bytes = b""
    changes: list[dict] = field(default_factory=list)


# --------------------------------------------------------------------------
# Small helpers
# --------------------------------------------------------------------------
def sha256(raw: bytes) -> str:
    return hashlib.sha256(raw).hexdigest()


def clean_text(value: str, whitespace: str = "control") -> tuple[str, list[str]]:
    """Apply the whitespace policy to one non-date cell.  Returns (text, kinds).

    control: edge runs containing tab/CR/LF removed, internal line-break runs -> one space.
    all:     additionally every leading/trailing whitespace character (spaces, NBSP, ...) is
             removed and whitespace-only cells become blank (each counted separately)."""
    kinds: list[str] = []
    text = value
    lead = _EDGE_LEAD.match(text)
    if lead and re.search(r"[\t\r\n]", lead.group()):
        text = text[lead.end():]
        kinds.append(K_EDGE)
    trail = _EDGE_TRAIL.search(text)
    if trail and re.search(r"[\t\r\n]", trail.group()):
        text = text[:trail.start()]
        if K_EDGE not in kinds:
            kinds.append(K_EDGE)
    replaced = _BREAK.sub(" ", text)
    if replaced != text:
        text = replaced
        kinds.append(K_BREAK)
    if whitespace == "all":
        if text and not text.strip():
            text = ""
            kinds.append(K_WS_BLANK)
        elif text.strip() != text:
            text = text.strip()
            kinds.append(K_EDGE_SPACE)
    return text, kinds


def parse_number(text) -> float | None:
    if text is None:
        return None
    if isinstance(text, bool):
        return None
    if isinstance(text, (int, float)):
        return float(text) if math.isfinite(float(text)) else None
    stripped = str(text).strip().replace(",", "")
    if not stripped:
        return None
    try:
        number = float(stripped)
    except ValueError:
        return None
    return number if math.isfinite(number) else None


def format_number(value: float) -> str:
    if float(value).is_integer():
        return str(int(value))
    return format(float(value), ".15g")


def excel_text(cell: "dr.XCell") -> str:
    """Render a workbook value as text for comparison (not for output)."""
    value = cell.value
    if value is None:
        return ""
    if isinstance(value, bool):
        return str(value).upper()
    if isinstance(value, (int, float)) and not isinstance(value, bool):
        return format_number(value)
    if isinstance(value, datetime):
        return value.isoformat(sep=" ")
    if isinstance(value, date):
        return value.isoformat()
    return str(value)


def _cmp_norm(text: str) -> str:
    return re.sub(r"\s+", " ", text.replace("_x000D_", " ")).strip()


def hash_paths(paths: list[Path]) -> dict[str, str]:
    """sha256 of every file under the given files/directories (sorted, recursive)."""
    manifest: dict[str, str] = {}
    for root in paths:
        root = Path(root)
        if root.is_file():
            manifest[str(root.resolve())] = sha256(root.read_bytes())
        elif root.is_dir():
            for path in sorted(p for p in root.rglob("*") if p.is_file()):
                manifest[str(path.resolve())] = sha256(path.read_bytes())
        else:
            manifest[str(root.resolve())] = "MISSING"
    return manifest


def manifest_diff(before: dict[str, str], after: dict[str, str]) -> list[dict]:
    diffs = []
    for path in sorted(set(before) | set(after)):
        if before.get(path) != after.get(path):
            diffs.append({"path": path, "before": before.get(path), "after": after.get(path)})
    return diffs


def serialise(header: list[str], rows: list[list[str]]) -> bytes:
    buffer = io.StringIO(newline="")
    writer = csv.writer(buffer, lineterminator="\n", quoting=csv.QUOTE_MINIMAL)
    writer.writerow(header)
    writer.writerows(rows)
    return buffer.getvalue().encode("utf-8")


# --------------------------------------------------------------------------
# The cleaning step
# --------------------------------------------------------------------------
def clean(csv_raw: bytes, xlsx_raw: bytes, options: CleanOptions | None = None,
          csv_name: str = "official.csv", xlsx_name: str = "official.xlsx") -> CleanResult:
    """Pure function: official bytes in, cleaned table + log out.  Raises CleaningRejected."""
    opts = options or CleanOptions()
    reasons: list[str] = []
    if opts.capacity_source not in ("csv", "excel"):
        raise CleaningRejected([f"capacity_source must be csv or excel, not {opts.capacity_source!r}"])
    if opts.whitespace not in ("control", "all"):
        raise CleaningRejected([f"whitespace must be control or all, not {opts.whitespace!r}"])

    inputs = {
        "csv": {"name": csv_name, "bytes": len(csv_raw), "sha256": sha256(csv_raw)},
        "xlsx": {"name": xlsx_name, "bytes": len(xlsx_raw), "sha256": sha256(xlsx_raw)},
    }
    for label, expected in (("csv", opts.expected_csv_sha256), ("xlsx", opts.expected_xlsx_sha256)):
        if expected and expected.lower() != inputs[label]["sha256"]:
            reasons.append(f"{label} sha256 {inputs[label]['sha256']} != expected {expected.lower()}")
    if reasons:
        raise CleaningRejected(reasons)

    # ---- read (csv module + openpyxl: keeps text NA and number formats) --------------------
    try:
        c_header, c_rows, encoding = dr.read_csv_table(csv_raw)
    except (ValueError, csv.Error) as exc:
        raise CleaningRejected([f"CSV unreadable: {exc}"]) from exc
    try:
        x_header, x_rows, sheet = dr.read_xlsx_table(xlsx_raw, sheet=opts.sheet)
    except (ValueError, KeyError) as exc:
        raise CleaningRejected([f"XLSX unreadable: {exc}"]) from exc
    inputs["csv"].update({
        "encoding": encoding, "bom": csv_raw.startswith(b"\xef\xbb\xbf"), "records": len(c_rows),
        "columns": len(c_header), "crlf_count": csv_raw.count(b"\r\n"),
        "lf_count": csv_raw.count(b"\n"),
    })
    inputs["xlsx"].update({"sheet": sheet, "records": len(x_rows), "columns": len(x_header)})

    names = [dr.collapse_header(h) for h in c_header]
    x_names = [dr.collapse_header(h) for h in x_header]
    if names != x_names:
        reasons.append(f"CSV and XLSX headers differ: csv_only={sorted(set(names) - set(x_names))} "
                       f"xlsx_only={sorted(set(x_names) - set(names))} (or order differs)")
    dupe_headers = [n for n, k in Counter(names).items() if k > 1]
    if dupe_headers:
        reasons.append(f"duplicate CSV headers after whitespace collapse: {dupe_headers}")
    if REF_COLUMN not in names:
        reasons.append("CSV has no Ref ID column")
    if reasons:
        raise CleaningRejected(reasons)
    ref_pos = names.index(REF_COLUMN)

    # ---- duplicates (strict: raw CSV text of every field) ---------------------------------
    occurrences: dict[str, list[int]] = defaultdict(list)
    first_row: dict[str, list[str]] = {}
    for number, row in enumerate(c_rows, start=1):
        ref = dr.clean_ref(row[ref_pos])
        if not ref:
            reasons.append(f"CSV data record {number} has a blank Ref ID")
            continue
        occurrences[ref].append(number)
        if ref in first_row and first_row[ref] != row:
            differing = [c_header[i] for i, (a, b) in enumerate(zip(first_row[ref], row)) if a != b]
            reasons.append(f"conflicting duplicate Ref ID {ref} (CSV data records {occurrences[ref]}; "
                           f"fields differ: {differing})")
        first_row.setdefault(ref, row)
    x_ref_pos = x_names.index(REF_COLUMN)
    x_occ = Counter(dr.clean_ref(r[x_ref_pos].value) for r in x_rows)
    c_occ = Counter({ref: len(v) for ref, v in occurrences.items()})
    if set(c_occ) != set(x_occ):
        only_c, only_x = sorted(set(c_occ) - set(x_occ)), sorted(set(x_occ) - set(c_occ))
        reasons.append(f"CSV and XLSX Ref ID sets differ: csv_only={only_c[:20]} ({len(only_c)}) "
                       f"xlsx_only={only_x[:20]} ({len(only_x)})")
    else:
        count_diff = sorted(ref for ref in c_occ if c_occ[ref] != x_occ[ref])
        if count_diff:
            reasons.append(f"Ref IDs repeated a different number of times in CSV and XLSX: {count_diff[:20]}")
    if reasons:
        raise CleaningRejected(reasons)

    # ---- the date rule over the whole table -----------------------------------------------
    rule = dr.apply_rule(c_header, c_rows, x_header, x_rows,
                         required_date_columns=opts.required_date_columns, as_of=opts.as_of,
                         future_ok_columns=opts.future_ok_columns)
    if not rule.ok:
        raise CleaningRejected(rule.failure_messages(limit=25))
    date_cols = set(rule.date_columns)
    prov = {(p["ref"], p["column"]): p for p in rule.provenance}

    # workbook rows by ref (first occurrence; duplicates already proved identical by the rule)
    x_by_ref: dict[str, list] = {}
    for r in x_rows:
        x_by_ref.setdefault(dr.clean_ref(r[x_ref_pos].value), r)

    # ---- header ------------------------------------------------------------------------
    changes: list[dict] = []
    header_changes: list[dict] = []
    if opts.normalise_headers:
        out_header = list(names)
        for i, (a, b) in enumerate(zip(c_header, out_header)):
            if a != b:
                header_changes.append({"column_index": i, "before": a, "after": b, "kinds": [K_HEADER]})
    else:
        out_header = list(c_header)

    # ---- rows and cells ------------------------------------------------------------------
    removed_rows: list[dict] = []
    out_rows: list[list[str]] = []
    out_refs: list[str] = []
    na_preserved: Counter = Counter()
    ws_preserved: Counter = Counter()
    stray_dates: list[dict] = []
    num_date_columns: Counter = Counter()
    seen: set[str] = set()
    for number, row in enumerate(c_rows, start=1):
        ref = dr.clean_ref(row[ref_pos])
        if ref in seen:
            removed_rows.append({"ref": ref, "csv_record": number,
                                 "kept_csv_record": occurrences[ref][0], "kinds": [K_DUP]})
            continue
        seen.add(ref)
        xrow = x_by_ref[ref]
        out_row_number = len(out_rows) + 1
        new_row: list[str] = []
        for i, (name, before) in enumerate(zip(names, row)):
            kinds: list[str] = []
            detail: dict = {}
            xcell = xrow[i]
            if name in date_cols:
                after = rule.output.get((ref, name), "")
                if after != before:
                    p = prov.get((ref, name), {})
                    code = p.get("rule", "")
                    if code in dr.MONTH_FIRST_RULES:
                        kinds.append(K_DATE_MF)
                    elif code == dr.OK_BLANK_EQUIVALENT:
                        kinds.append(K_DATE_WS if p.get("blank_token") == "<whitespace>" else K_DATE_NA)
                    else:
                        kinds.append(K_DATE_OTHER)
                    detail = {"date_rule": code, "excel_value": p.get("excel_value"),
                              "excel_number_format": p.get("excel_number_format")}
                    if p.get("blank_token") is not None:
                        detail["blank_token"] = p.get("blank_token")
            elif (xcell.is_date and isinstance(xcell.value, datetime)
                  and xcell.value.date() < dr.EARLIEST_PLAUSIBLE):
                serial = float(to_excel(xcell.value))
                rendered = xcell.value.strftime("%d/%m/%Y")
                if before.strip() != rendered:
                    reasons.append(f"ref {ref} column {name!r}: workbook holds number {serial!r} with a date "
                                   f"format, but CSV text {before!r} is not its date rendering {rendered!r}")
                    after = before
                else:
                    after = format_number(serial)
                    kinds.append(K_NUM_DATE)
                    num_date_columns[name] += 1
                    detail = {"excel_serial": serial, "excel_number_format": xcell.number_format,
                              "csv_rendering": rendered}
            else:
                after, kinds = clean_text(before, opts.whitespace)
                if xcell.is_date and isinstance(xcell.value, (datetime, date)):
                    stray_dates.append({"ref": ref, "column": name, "csv_text": before,
                                        "excel_value": excel_text(xcell),
                                        "action": "NOT_ALTERED_REPORTED_ONLY"})
                if name == CAPACITY_COLUMN and opts.capacity_source == "excel":
                    x_num, c_num = parse_number(xcell.value), parse_number(after)
                    if x_num is None and c_num is None:
                        pass
                    elif x_num is None or c_num is None or abs(x_num - c_num) > CAPACITY_TOLERANCE_MW:
                        reasons.append(f"ref {ref}: capacity CSV {before!r} vs XLSX {xcell.value!r} disagree")
                    else:
                        precise = format(x_num, ".15g")
                        if precise != after:
                            detail = {"excel_value": xcell.value, "csv_value": after}
                            after = precise
                            kinds.append(K_CAPACITY)
                if after.strip().casefold() in dr.DEFAULT_BLANK_TOKENS:
                    na_preserved[name] += 1
                if after and not after.strip():
                    ws_preserved[name] += 1
            if after != before and not kinds:
                reasons.append(f"internal: unlogged change ref {ref} column {name!r}")
            if kinds:
                if after == before:
                    kinds = []
                else:
                    changes.append({"ref": ref, "column": c_header[i], "column_index": i,
                                    "csv_record": number, "out_row": out_row_number,
                                    "before": before, "after": after, "kinds": kinds, **detail})
            new_row.append(after)
        out_rows.append(new_row)
        out_refs.append(ref)
    if reasons:
        raise CleaningRejected(reasons)
    if len(set(out_refs)) != len(out_refs) or set(out_refs) != set(x_by_ref):
        raise CleaningRejected(["internal: output Ref IDs are not the unique workbook Ref IDs"])

    # ---- strict format check of every date cell -------------------------------------------
    date_idx = [i for i, n in enumerate(names) if n in date_cols]
    bad = []
    for r_no, row in enumerate(out_rows, start=1):
        for i in date_idx:
            v = row[i]
            if v and not (_STRICT_DATE.fullmatch(v) and _valid_dmy(v)):
                bad.append((out_refs[r_no - 1], names[i], v))
    if bad:
        raise CleaningRejected([f"internal: non-strict dates in output {bad[:10]}"])