GLOBALGRID2050 / EXPLORE CODE

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

Acceptance and 1 more file

A Python command-line tool in the tests folder of GlobalGrid2050 that tests Renewable Energy Planning Database (REPD) grid batteries, REPD solar operational over 4MW and REPD master, using SHA-256.

700 lines of Python from globalgrid2050, in 2 files. Topic: Electricity markets and data pipelines. Section 827 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. Automation — Renewable Energy Planning Database (REPD) energy-data · globalgrid2050 / automation/repd/run.py lines 1080–1377
  2. Acceptance test · globalgrid2050 / automation/repd/tests/acceptance.py lines 1–402

Automation — Renewable Energy Planning Database (REPD)

A Python command-line tool in GlobalGrid2050 that fetches REPD publication q3, REPD grid batteries, REPD solar operational over 4MW and REPD master, using SHA-256.

energy-dataglobalgrid2050 / automation/repd/run.py · lines 1080–1377 of 1377 (continued from section 825) · Entry point · pattern compare_manifests (shared by 2 files)

What it does
It fetches REPD publication q3, REPD grid batteries, REPD solar operational over 4MW and REPD master. Defines 68 functions or classes, including utc_now, sha256_file, sha256_bytes, write_json, StageError. Uses libraries __future__, argparse, dataclasses, datetime, fnmatch. Side effects: reads or writes files; makes network requests; 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.
Inputs & outputs
In: CSV file REPD_Publication_Q3_2026.csv; Excel file REPD_Publication_Q3_2026.xlsx; CSV file repd.csv; CSV file repd-grid-batteries.csv; CSV file repd-solar-operational.csv; CSV file repd-solar-operational-over-4mw.csv; JSON file repd_master.json; JSON file manifest_v4.json. Out: CSV file.
Downstream impact
Used directly by 4 files: Test Hardening Nl013 (globalgrid2050); Test Run (globalgrid2050); GlobalGrid2050 Renewable Energy Planning Database (REPD) Monthly Workflow (globalgrid2050); GlobalGrid2050 Renewable Energy Planning Database (REPD) Release Candidate Workflow (globalgrid2050). Reached from 1 other entry point, including GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
What it achieves
It writes JSON (`write_json`), runs context (`RunContext`) and loads module (`load_module`). REPD release-candidate orchestrator. It writes `detect_report.json`. It accepts `--label`, `--release-folder` and `--descriptor`.
Why it matters
Run by GlobalGrid2050 Renewable Energy Planning Database (REPD) Monthly Workflow and GlobalGrid2050 Renewable Energy Planning Database (REPD) Release Candidate Workflow. Checked by 2 tests, including Test Hardening Nl013.
Application
globalgrid2050 · automation/repd · Python CLI
Uses
__future__, argparse, dataclasses, datetime, fnmatch, hashlib, importlib, inspect
Used by
imported by Test Hardening Nl013 (import), imported by Test Run (import), run by GlobalGrid2050 Renewable Energy Planning Database (REPD) Monthly Workflow (workflow run), run by GlobalGrid2050 Renewable Energy Planning Database (REPD) Release Candidate Workflow (workflow run)
Produces
utc_now, sha256_file, sha256_bytes, write_json, StageError, RunContext, load_module, find_component, call_component, normalise_result, first_path, common_pool
Defines here
resolve_descriptor, run_pipeline, render_markdown, detect_only, build_arg_parser, 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/run.py:1080-1377 · blob 447c8d05339e438dfa138881ede3f645efad8853 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, network, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
    """Copy allow-listed NEW paths into out/pr and write pr_manifest.json."""
    files: dict[str, str] = dict(ctx.artifacts.get("pr_files", {}))
    docs = f"docs/repd/releases/{ctx.label}/"
    data = f"data/repd/{ctx.label}/"
    if ctx.artifacts.get("canonical_csv"):
        files[f"{data}REPD_canonical_{ctx.label}.csv"] = str(ctx.artifacts["canonical_csv"])
    if ctx.artifacts.get("cleaning_log"):
        files[f"{docs}cleaning_log_{ctx.label}.json"] = str(ctx.artifacts["cleaning_log"])
    if ctx.artifacts.get("validation_json"):
        files[f"{docs}validation_{ctx.label}.json"] = str(ctx.artifacts["validation_json"])
    for rep_path in ctx.artifacts.get("validation_reports", []):
        files[docs + Path(rep_path).name] = rep_path
    diff = ctx.artifacts.get("diff") or {}
    for key, name in (("markdown", f"changelog_{ctx.label}.md"), ("json", f"diff_{ctx.label}.json"),
                      ("md", f"diff_{ctx.label}.md"), ("report_md", f"diff_{ctx.label}.md"),
                      ("report_json", f"diff_{ctx.label}.json")):
        if diff.get(key) and Path(diff[key]).is_file():
            files[docs + name] = diff[key]
    rejected = {r: "not on the allow-list of new paths" for r in files if not is_allowed_new_path(r, ctx.label, ctx.folder)}
    existing = paths_existing_in_repo(ctx.repo_root, [r for r in files if r not in rejected])
    for rel in existing:
        rejected[rel] = "path already exists in the repository (additive only)"
    if release_folder_exists(ctx.repo_root, ctx.folder):
        rejected[f"uk_renewables_pipeline/{ctx.folder}/"] = "release folder already exists (never replace a release in place)"
    if rejected:
        raise StageError("PR tree refused: " + "; ".join(f"{k}: {v}" for k, v in sorted(rejected.items())))
    allow = load_large_file_allowlist(ctx.repo_root)
    if ctx.pr_dir.exists():
        shutil.rmtree(ctx.pr_dir)
    manifest, oversize = [], []
    for rel, src in sorted(files.items()):
        size = Path(src).stat().st_size
        if size > MAX_PR_FILE_BYTES and not large_file_allowed(rel, allow):
            oversize.append({"path": rel, "bytes": size})
            continue
        dest = ctx.pr_dir / rel
        dest.parent.mkdir(parents=True, exist_ok=True)
        shutil.copyfile(src, dest)
        manifest.append({"path": rel, "bytes": size, "sha256": sha256_file(dest)})
    proposed = ctx.out_dir / "proposed_large_files_allowlist_additions.txt"
    if oversize:
        proposed.write_text(
            f"# REPD {ctx.label} candidate files over 5 MB (pr-file-size-guard). Proposed exact entries;\n"
            "# the owner adds them in a separate reviewed PR. They are NOT in the candidate PR.\n"
            + "".join(f"{o['path']}\n" for o in oversize), encoding="utf-8")
    write_json(ctx.out_dir / "pr_manifest.json", {
        "label": ctx.label, "release_folder": ctx.folder, "branch": f"repd/{ctx.label}-candidate",
        "allowed_patterns": allowed_new_path_patterns(ctx.label, ctx.folder),
        "files": manifest, "excluded_oversize": oversize})
    return {"impl": "run.py assemble (orchestrator)", "status_override": "ran", "pr_files": len(manifest), "pr_bytes": sum(m["bytes"] for m in manifest),
            "excluded_oversize": oversize}


# ---------------------------------------------------------------------- driver
PIPELINE: list[tuple[str, Callable[[RunContext], dict[str, Any]]]] = [
    ("detect", stage_detect),
    ("fetch", stage_fetch),
    ("clean", stage_clean),
    ("validate", stage_validate),
    ("diff", stage_diff),
    ("build_root", stage_build_root),
    ("build_v6", stage_build_v6),
    ("build_news", stage_build_news),
    ("acceptance", stage_acceptance),
    ("assemble_pr", stage_assemble),
]


def resolve_descriptor(label: str | None, descriptor_file: Path | None, overrides: dict[str, Any]
                       ) -> tuple[dict[str, Any], Any]:
    """Return (flat descriptor dict, config.ReleaseDescriptor or None)."""
    d: dict[str, Any] = {}
    obj = None
    cfg = load_module("config")
    source = "built-in KNOWN_RELEASES"
    if descriptor_file:
        d = json.loads(Path(descriptor_file).read_text(encoding="utf-8"))
        source = str(descriptor_file)
        if cfg is not None and d.get("schema") == getattr(cfg, "SCHEMA", None):
            obj = cfg.ReleaseDescriptor.from_dict(d)
            d = descriptor_from_config(obj)
    elif cfg is not None and label and _has(cfg, "load", "RELEASES_DIR"):
        path = Path(cfg.RELEASES_DIR) / f"{label}.json"
        if path.is_file():
            obj = cfg.load(path)
            d = descriptor_from_config(obj)
            source = f"automation.repd.config ({path.name})"
    if not d and label in KNOWN_RELEASES:
        d = json.loads(json.dumps(KNOWN_RELEASES[label]))
    d.update({k: v for k, v in overrides.items() if v not in (None, "")})
    if not d.get("label"):
        raise StageError("no release label: pass --label (e.g. 2026q3) or --descriptor")
    if not d.get("release_folder"):
        d["release_folder"] = dt.datetime.now(dt.timezone.utc).strftime("%Y%m%d%H%M")
    if not LABEL_RE.match(d["label"]):
        raise StageError(f"label {d['label']!r} must look like 2026q3")
    if not FOLDER_RE.match(str(d["release_folder"])):
        raise StageError(f"release folder {d['release_folder']!r} must be a 12-digit UTC stamp")
    for key in ("expected_csv_sha256", "expected_xlsx_sha256"):
        if d.get(key) and not SHA_RE.match(str(d[key]).lower()):
            raise StageError(f"{key} is not a sha256 hex digest")
    if obj is not None:
        # CLI overrides of URLs/hashes must reach the component descriptor too
        for key, attr in (("csv_url", "csv_url"), ("xlsx_url", "xlsx_url")):
            if overrides.get(key):
                setattr(obj, attr, overrides[key])
        for kind in ("csv", "xlsx"):
            if overrides.get(f"expected_{kind}_sha256"):
                setattr(obj.expected, f"{kind}_sha256", overrides[f"expected_{kind}_sha256"])
        obj.validate()
    d["_descriptor_source"] = source
    return d, obj


def run_pipeline(ctx: RunContext, stop_after: str | None = None) -> dict[str, Any]:
    started = utc_now()
    out = ctx.out_dir
    repo = ctx.repo_root.resolve()
    if out.resolve() == repo or repo in out.resolve().parents:
        raise StageError(f"--out {out} is inside the repository {repo}; write outside the repo")
    out.mkdir(parents=True, exist_ok=True)
    pin_problems = check_known_pins(repo) if ctx.check_pins else []
    before = hash_manifest(repo, ctx.protected_globs)
    write_json(out / "hash_manifest_before.json", before)
    overall = "ok"
    for name, fn in PIPELINE:
        rec: dict[str, Any] = {"stage": name, "started_utc": utc_now()}
        t0 = time.monotonic()
        try:
            if pin_problems:
                raise StageError("baseline pin check failed before running: " + "; ".join(pin_problems))
            res = fn(ctx)
            rec["status"] = res.pop("status_override", None) or ("fallback" if str(res.get("impl", "")).startswith(("run.py", "fallback", "offline")) else "ran")
            rec["impl"] = res.get("impl")
            rec["result"] = res
        except (Exception, SystemExit) as exc:  # noqa: BLE001 - every failure is reported and fails closed
            # SystemExit too: reused repository scripts (e.g. scripts/repd_updater.py) call sys.exit /
            # raise SystemExit on a missing input. Without this the run aborted with no run report and
            # without the post-run hash guard.
            rec["status"] = "failed"
            rec["error"] = str(exc) if not isinstance(exc, SystemExit) else f"SystemExit({exc.code!r})"
            if not isinstance(exc, StageError):
                rec["traceback"] = traceback.format_exc(limit=8)
        rec["seconds"] = round(time.monotonic() - t0, 2)
        ctx.stages.append(rec)
        if rec["status"] == "failed":
            overall = "failed"
            break
        if rec["status"] == "missing":
            overall = "incomplete" if overall == "ok" else overall
        if stop_after and name == stop_after:
            break
    after = hash_manifest(repo, ctx.protected_globs)
    write_json(out / "hash_manifest_after.json", after)
    delta = compare_manifests(before, after)
    guard = {"stage": "hash_guard", "protected_files": before["file_count"], **delta,
             "known_pin_problems": pin_problems}
    guard["status"] = "failed" if any(delta.values()) else "ran"
    if guard["status"] == "failed":
        overall = "failed"
    ctx.stages.append(guard)
    if overall == "incomplete" and ctx.allow_partial:
        overall = "partial"
    report = {
        "schema": RUN_SCHEMA, "started_utc": started, "finished_utc": utc_now(),
        "overall": overall, "label": ctx.label, "release_folder": ctx.folder,
        "branch": f"repd/{ctx.label}-candidate", "offline": ctx.offline,
        "repo_root": str(repo), "out_dir": str(out),
        "descriptor": dict(ctx.descriptor),
        "news_contract_expected_accepted_from_builder": ctx.news_accept_expected,
        "stages": ctx.stages,
    }
    write_json(out / "run_report.json", report)
    (out / "run_report.md").write_text(render_markdown(report), encoding="utf-8")
    return report


def render_markdown(report: dict[str, Any]) -> str:
    lines = [
        f"# REPD release candidate {report['label']} ({report['overall'].upper()})",
        "",
        "Draft candidate generated by `automation/repd/run.py`. It adds new files only; nothing existing is "
        "changed. The owner reviews and merges. Merging a new `uk_renewables_pipeline/` folder to main deploys it.",
        "",
        f"- Release folder: `uk_renewables_pipeline/{report['release_folder']}/`",
        f"- Branch: `{report['branch']}`",
        f"- Offline: {report['offline']}",
        f"- Pipeline News contract `expected` figures taken from builder output: "
        f"{report.get('news_contract_expected_accepted_from_builder')} (review them in contracts/release.v9.*.json)",
        f"- Started {report['started_utc']}, finished {report['finished_utc']}",
        "",
        "| stage | status | implementation | seconds |",
        "|---|---|---|---|",
    ]
    for s in report["stages"]:
        lines.append(f"| {s['stage']} | {s['status']} | {str(s.get('impl', '')).replace('|', '/')} | {s.get('seconds', '')} |")
    lines.append("")
    for s in report["stages"]:
        if s.get("error"):
            lines += [f"**{s['stage']} failed:** {s['error']}", ""]
        if s["stage"] == "hash_guard":
            lines += [f"Hash guard: {s['protected_files']} protected files; changed {len(s['changed'])}, "
                      f"removed {len(s['removed'])}, added in protected area {len(s['added_in_protected_area'])}.", ""]
        if s["stage"] == "assemble_pr" and s.get("result"):
            r = s["result"]
            lines += [f"PR tree: {r['pr_files']} files, {r['pr_bytes']} bytes.", ""]
            for o in r.get("excluded_oversize", []):
                lines.append(f"- EXCLUDED (over 5 MB, not allow-listed): `{o['path']}` ({o['bytes']} bytes)")
            lines.append("")
    return "\n".join(lines) + "\n"


def detect_only(args: argparse.Namespace, fetcher: Callable[[str], bytes] | None = None) -> int:
    """Report-only: is there a release newer than the ones automation/repd knows? Never fails on 'new'."""
    det, cfg, fm = load_module("detect"), load_module("config"), load_module("fetch")
    if det is not None and cfg is not None and fm is not None and fetcher is None and _has(det, "detect"):
        known = cfg.load_all()
        baseline = known[max(known)] if known else None
        rep = det.detect(fm.urllib_fetcher(), "api", baseline)
        dd = rep["descriptor"]
        res = {"impl": "automation.repd.detect.detect", "status": rep["status"], "label": dd["release_id"],
               "csv_url": dd["csv_url"], "xlsx_url": dd["xlsx_url"],
               "public_updated_at": dd.get("govuk_public_updated_at") or dd.get("page_last_updated"),
               "known_labels": sorted(known),
               "new_release": rep["status"] in ("NEW_RELEASE", "REPLACED_SAME_QUARTER", "NO_BASELINE"),
               "detect_report": rep}
    else:
        res = fallback_detect(fetcher or default_fetcher)
        res["impl"] = "run.py fallback_detect"
        known_urls = {r.get("csv_url") for r in KNOWN_RELEASES.values()}
        res["known_labels"] = sorted(KNOWN_RELEASES)
        res["new_release"] = (bool(res.get("csv_url")) and res.get("csv_url") not in known_urls
                              and res.get("label") not in KNOWN_RELEASES)
    out = Path(args.out)
    out.mkdir(parents=True, exist_ok=True)
    write_json(out / "detect_report.json", res)
    print(json.dumps({k: v for k, v in res.items() if k != "detect_report"}, indent=2, default=str))
    return 0


def build_arg_parser() -> argparse.ArgumentParser:
    p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    p.add_argument("--label", help="release label, e.g. 2026q3")
    p.add_argument("--release-folder", help="12-digit UTC stamp for uk_renewables_pipeline/<stamp>/")
    p.add_argument("--descriptor", type=Path, help="release descriptor JSON (overrides config.py/built-ins)")
    p.add_argument("--csv-url"); p.add_argument("--xlsx-url")
    p.add_argument("--expected-csv-sha256"); p.add_argument("--expected-xlsx-sha256")
    p.add_argument("--out", type=Path, required=True, help="output directory, outside the repo")
    p.add_argument("--repo-root", type=Path, default=Path(__file__).resolve().parents[2])
    p.add_argument("--offline", action="store_true", help="no network: use --csv/--xlsx local files")
    p.add_argument("--csv", type=Path); p.add_argument("--xlsx", type=Path)
    p.add_argument("--previous", type=Path, help="previous-release CSV baseline (default from descriptor)")
    p.add_argument("--allow-partial", action="store_true", help="exit 0 even if a build component is missing")
    p.add_argument("--quick-guard", action="store_true", help="hash only top-level protected files (no release trees)")
    p.add_argument("--no-pin-check", action="store_true", help="skip the known sha256 baseline pins")
    p.add_argument("--news-review-expected", action="store_true",
                   help="do NOT pass --accept-expected to build_news (stop for a human when contract figures change)")
    p.add_argument("--stop-after", choices=[n for n, _ in PIPELINE])
    p.add_argument("--detect-only", action="store_true", help="report-only new-release check")
    return p


def main(argv: list[str] | None = None) -> int:
    args = build_arg_parser().parse_args(argv)
    if args.detect_only:
        return detect_only(args)
    try:
        descriptor, config_obj = resolve_descriptor(args.label, args.descriptor, {
            "label": args.label, "release_folder": args.release_folder,
            "csv_url": args.csv_url, "xlsx_url": args.xlsx_url,
            "expected_csv_sha256": (args.expected_csv_sha256 or "").lower() or None,
            "expected_xlsx_sha256": (args.expected_xlsx_sha256 or "").lower() or None,
        })
    except StageError as exc:
        print(f"ERROR: {exc}", file=sys.stderr)
        return 2
    ctx = RunContext(
        repo_root=args.repo_root.resolve(), out_dir=args.out.resolve(), descriptor=descriptor,
        offline=args.offline, local_csv=args.csv, local_xlsx=args.xlsx, previous_csv=args.previous,
        allow_partial=args.allow_partial, check_pins=not args.no_pin_check,
        protected_globs=list(QUICK_PROTECTED_GLOBS if args.quick_guard else PROTECTED_GLOBS),
        news_accept_expected=not args.news_review_expected,
    )
    if config_obj is not None:
        ctx.artifacts["config_descriptor"] = config_obj
    try:
        report = run_pipeline(ctx, stop_after=args.stop_after)
    except StageError as exc:
        print(f"ERROR: {exc}", file=sys.stderr)
        return 2
    for s in report["stages"]:
        print(f"{s['stage']:<12} {s['status']:<9} {s.get('impl', '') or ''} {s.get('error', '')}")
    print(f"overall: {report['overall']}  report: {ctx.out_dir / 'run_report.md'}")
    return {"ok": 0, "partial": 0, "incomplete": 3}.get(report["overall"], 1)


if __name__ == "__main__":
    sys.exit(main())

Acceptance

A Python command-line tool in the tests folder of GlobalGrid2050 that tests Renewable Energy Planning Database (REPD) grid batteries, REPD solar operational over 4MW and REPD master, using SHA-256.

testglobalgrid2050 / automation/repd/tests/acceptance.py · lines 1–402 of 1105 · Entry point · pattern _resolve (shared by 2 files)

What it does
It tests REPD grid batteries, REPD solar operational over 4MW, REPD master and the REPD register. Defines 43 functions or classes, including norm_ws, norm_header, demojibake, is_mojibake, to_float. Uses libraries __future__, argparse, csv, datetime, decimal. 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: CSV file repd.csv; CSV file repd-grid-batteries.csv; CSV file repd-solar-operational.csv; CSV file repd-solar-operational-over-4mw.csv; JSON file repd_master.json; command-line arguments. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid), WGS84 / EPSG:4326.
Downstream impact
Used directly by 1 file: Test Acceptance (globalgrid2050). Reached from 1 other entry point, including GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
What it achieves
It cleans ref (`clean_ref`), reads CSV (`read_csv`) and reads xlsx (`read_xlsx`). End-to-end acceptance harness for a REPD release candidate. Its code works with 1 MW and 4 MW. It accepts `--official-csv`, `--official-xlsx` and `--xlsx-sheet`.
Why it matters
Checked by Test Acceptance.
Application
globalgrid2050 · automation/repd/tests · Python CLI
Uses
__future__, argparse, csv, datetime, decimal, hashlib, io, json
Used by
imported by Test Acceptance (import)
Produces
norm_ws, norm_header, demojibake, is_mojibake, to_float, clean_ref, sha256_file, decimals, excel_serial, month_first_format, CsvFile, read_csv
Defines here
norm_ws, norm_header, demojibake, is_mojibake, to_float, clean_ref, sha256_file, decimals, excel_serial, month_first_format, CsvFile, nheader, index, read_csv, XlsxData, _unescape_ooxml, read_xlsx, Check, Report, __init__, add, skip, failed, to_json, text, _ex, file_hygiene
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/tests/acceptance.py:1-402 · blob e6d00c4aeb9bae7eed5a5351b70ad938f86276dc · 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
"""End-to-end acceptance harness for a REPD release candidate.

Independent of how the candidate was built: it re-derives every expectation from the
official files and checks the candidate from first principles.

Inputs
  --official-csv   official DESNZ CSV (cp1252 or UTF-8)
  --official-xlsx  official DESNZ XLSX (optional; without it the XLSX-backed change
                   classes cannot be verified and fail closed)
  --cleaned        cleaned canonical CSV (one row per Ref ID)
  --root-dir       directory of root-format outputs, with file names given by
                   --full --batteries --solar-op --over4 --master (relative to
                   --root-dir or absolute)
  --baseline-master existing dist/repd_master.json (property-key superset check)

Checks (ids are stable; see CHECK_IDS)
  official.*   the official files read cleanly; duplicate refs are identical
  cleaned.*    every official ref exactly once; header; every changed cell belongs
               to a documented change class; month-first cells corrected; text
               agrees with the Excel; file hygiene
  full.* batteries.* solar_op.* over4.*   UTF-8, no mojibake, no bare CR, no
               embedded line breaks, field counts, content == filter(cleaned)
  master.*     GeoJSON parses, one feature per viable geocoded record under the
               scripts/repd_updater.py refine_dataset rules, property keys superset
  inputs.unchanged  sha256 of every input (and --pin) identical before and after

Usage
  python3 acceptance.py --official-csv X.csv --official-xlsx X.xlsx --cleaned C.csv \
      --root-dir OUT --full repd-2026q3.csv --batteries repd-grid-batteries-2026q3.csv \
      --solar-op repd-solar-operational-2026q3.csv --over4 repd-solar-operational-over-4mw-2026q3.csv \
      --master dist/repd_master_2026q3.json --baseline-master REPO/dist/repd_master.json \
      [--expect-month-first 25] [--json report.json]
  Exit 0 = all checks pass (SKIP allowed), 1 = at least one FAIL, 2 = bad arguments.

  As pytest:  REPD_ACCEPT_ARGS="<same arguments>" pytest -q automation/repd/tests/acceptance.py
  (every check becomes one test; all are skipped when REPD_ACCEPT_ARGS is unset).

Standard library only, plus openpyxl (XLSX) and pyproj (GeoJSON rules), both imported lazily.
"""
from __future__ import annotations

import argparse
import csv
import datetime as _dt
from decimal import ROUND_HALF_EVEN, ROUND_HALF_UP, Decimal
import hashlib
import io
import json
import math
import os
import re
import shlex
import sys
from dataclasses import dataclass, field
from pathlib import Path

# --------------------------------------------------------------------------------------
# Documented vocabulary
# --------------------------------------------------------------------------------------

REF = "Ref ID"
TECH = "Technology Type"
STATUS_SHORT = "Development Status (short)"
CAPACITY = "Installed Capacity (MWelec)"
MOUNTING = "Mounting Type for Solar"
SOLAR = "Solar Photovoltaics"

BATTERY_STATUSES = frozenset({
    "Operational", "Under Construction", "Awaiting Construction",
    "Application Submitted", "Appeal Lodged", "No Application Required",
})

# Header of the January root repd-solar-operational.csv, byte for byte (43 columns,
# including the official double space and trailing space).
SOLAR_OP_HEADER = [
    "Old Ref ID", "Ref ID", "Record Last Updated (dd/mm/yyyy)", "Operator (or Applicant)", "Site Name",
    "Technology Type", "Storage Co-location REPD Ref ID", "Installed Capacity (MWelec)", "CHP Enabled",
    "CfD Allocation Round", "RO Banding (ROC/MWh)", "FiT Tariff (p/kWh)", "CfD Capacity (MW)",
    "Mounting Type for Solar", "Development Status", "Development Status (short)",
    "Are they re-applying (New REPD Ref)", "Are they re-applying (Old REPD Ref) ", "Address", "County",
    "Region", "Country", "Post Code", "X-coordinate", "Y-coordinate", "Planning Authority",
    "Planning Application Reference", "Appeal Reference", "Secretary of State Reference",
    "Type of Secretary of State Intervention", "Judicial Review", "Planning Application Submitted",
    "Planning Application Withdrawn", "Planning Permission Refused", "Appeal Lodged", "Appeal Granted",
    "Planning Permission  Granted", "Secretary of State - Intervened", "Secretary of State - Granted",
    "Planning Permission Expired", "Under Construction", "Operational", "Solar Site Area (sqm)",
]

# Official 53-column header (identical in the January 2026 and October 2026 CSVs).
OFFICIAL_HEADER = [
    "Old Ref ID", "Ref ID", "Record Last Updated (dd/mm/yyyy)", "Operator (or Applicant)", "Site Name",
    "Technology Type", "Storage Type", "Storage Co-location REPD Ref ID", "Installed Capacity (MWelec)",
    "Share Community Scheme", "CHP Enabled", "CfD Allocation Round", "RO Banding (ROC/MWh)",
    "FiT Tariff (p/kWh)", "CfD Capacity (MW)", "Turbine Capacity (MW)", "No. of Turbines",
    "Height of Turbines (m)", "Mounting Type for Solar", "Development Status", "Development Status (short)",
    "Are they re-applying (New REPD Ref)", "Are they re-applying (Old REPD Ref) ", "Address", "County",
    "Region", "Country", "Post Code", "X-coordinate", "Y-coordinate", "Planning Authority",
    "Planning Application Reference", "Appeal Reference", "Secretary of State Reference",
    "Type of Secretary of State Intervention", "Judicial Review", "Offshore Wind Round",
    "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", "Heat Network Ref",
    "Solar Site Area (sqm)",
]

DATE_COLUMNS = frozenset({
    "Record Last Updated (dd/mm/yyyy)", "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",
})  # whitespace-normalised names

TEXT_COLUMNS = ("Site Name", "Operator (or Applicant)", "Address", "County", "Region", "Country",
                "Post Code", "Planning Authority")

# Change classes. The first five are the ones documented for October 2026; the other three
# are policies of the cleaner that the harness can still verify against the XLSX.
CHANGE_CLASSES = {
    "month_first_date": "m/d/yyyy CSV date corrected to dd/mm/yyyy from the typed Excel cell",
    "na_date": "text NA in a date column blanked",
    "whitespace_control": "leading/trailing/repeated whitespace, NBSP, tab or control characters normalised",
    "embedded_line_break": "CR/LF inside a field removed",
    "number_as_date": "number stored with a date format (CSV shows dd/mm/1900) restored to the number",
    "na_text": "text NA in a non-date column blanked (cleaner policy, not in the documented list)",
    "xlsx_precision": "CSV-rounded number replaced by the full-precision Excel value (cleaner policy)",
    "excel_text": "CSV text differs from the Excel text cell (e.g. lost leading zero); Excel text used (cleaner policy)",
}
DEFAULT_ALLOWED = frozenset(CHANGE_CLASSES)

FILE_ROLES = ("full", "batteries", "solar_op", "over4")
FILE_CHECKS = ("utf8", "no_mojibake", "no_bare_cr", "no_embedded_breaks", "field_count")

CHECK_IDS = (
    ["official.read", "official.duplicates_identical", "official.xlsx_agrees"]
    + ["cleaned.refs_exactly_once", "cleaned.header", "cleaned.cells_classified",
       "cleaned.month_first_corrected", "cleaned.text_matches_excel"]
    + [f"cleaned.{c}" for c in FILE_CHECKS]
    + [f"{r}.{c}" for r in FILE_ROLES for c in FILE_CHECKS]
    + ["full.equals_cleaned", "batteries.filter", "solar_op.header", "solar_op.filter",
       "over4.header", "over4.filter"]
    + ["master.parses", "master.features", "master.keys_superset"]
    + ["inputs.unchanged"]
)

# --------------------------------------------------------------------------------------
# Small helpers
# --------------------------------------------------------------------------------------

_WS_RE = re.compile(r"[\s\u00a0\u200b-\u200d\u2060\ufeff\x00-\x1f\x7f-\x9f]+")
_MOJI_RE = re.compile("[\u00c2\u00c3][\u0080-\u00bf\u0152\u0153\u0160\u0161\u0178\u017d\u017e\u0192\u02c6\u02dc"
                      "\u2013\u2014\u2018-\u201e\u2020-\u2022\u2026\u2030\u2039\u203a\u20ac\u2122]"
                      "|\u00e2\u0080|\u00e2\u20ac")
_DMY_RE = re.compile(r"^(\d{1,2})/(\d{1,2})/(\d{4})$")


def norm_ws(s: str) -> str:
    return _WS_RE.sub(" ", s).strip()


def norm_header(h: str) -> str:
    return re.sub(r"\s+", " ", h.replace("\ufeff", "")).strip()


def demojibake(s: str):
    """Return the repaired string if s is UTF-8 text that was decoded as cp1252/latin-1."""
    for enc in ("cp1252", "latin-1"):
        try:
            t = s.encode(enc).decode("utf-8")
        except (UnicodeEncodeError, UnicodeDecodeError):
            continue
        if t != s:
            return t
    return None


def is_mojibake(s: str) -> bool:
    return bool(_MOJI_RE.search(s)) or demojibake(s) is not None


def to_float(s):
    if s is None:
        return None
    t = str(s).replace(",", "").strip()
    if not t:
        return None
    try:
        v = float(t)
    except ValueError:
        return None
    return v if math.isfinite(v) else None


def clean_ref(v) -> str:
    s = "" if v is None else str(v).strip()
    if re.fullmatch(r"\d+\.0", s):
        s = s[:-2]
    return s


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


def decimals(s: str) -> int:
    t = s.strip()
    return len(t.split(".", 1)[1]) if "." in t else 0


def excel_serial(d: _dt.datetime) -> float:
    """Excel 1900-system serial (openpyxl maps serials below 60 from 1899-12-31: 1 -> 1900-01-01)."""
    base = _dt.datetime(1899, 12, 31) if d < _dt.datetime(1900, 3, 1) else _dt.datetime(1899, 12, 30)
    delta = d - base
    return delta.days + delta.seconds / 86400.0


def month_first_format(fmt: str) -> bool:
    """True for an explicit custom number format that writes the month before the day."""
    if not fmt or fmt.lower() in ("general", "mm-dd-yy"):  # mm-dd-yy = builtin 14, rendered in locale order
        return False
    f = re.sub(r"\[[^\]]*\]", "", fmt.split(";")[0]).lower()
    f = re.sub(r'"[^"]*"', "", f)
    toks = [c for c in f if c in "dmy"]
    if "d" not in toks or "m" not in toks:
        return False
    return toks.index("m") < toks.index("d")


# --------------------------------------------------------------------------------------
# Reading
# --------------------------------------------------------------------------------------

@dataclass
class CsvFile:
    path: Path
    raw: bytes
    encoding: str
    utf8_ok: bool
    bom: bool
    header: list
    rows: list  # list of lists, exactly as parsed (no padding)
    utf8_error: str = ""

    @property
    def nheader(self):
        return [norm_header(h) for h in self.header]

    def index(self):
        return {h: i for i, h in enumerate(self.nheader)}


def read_csv(path: Path, prefer: str = "utf-8") -> CsvFile:
    raw = Path(path).read_bytes()
    bom = raw.startswith(b"\xef\xbb\xbf")
    utf8_ok, err = True, ""
    try:
        text = raw.decode("utf-8-sig")
        enc = "utf-8"
    except UnicodeDecodeError as e:
        utf8_ok, err = False, f"byte 0x{raw[e.start]:02x} at offset {e.start}"
        try:
            text, enc = raw.decode("cp1252"), "cp1252"
        except UnicodeDecodeError:
            text, enc = raw.decode("latin-1"), "latin-1"
    rdr = csv.reader(io.StringIO(text, newline=""))
    try:
        header = next(rdr)
    except StopIteration:
        header = []
    rows = [r for r in rdr if r != []]
    return CsvFile(Path(path), raw, enc, utf8_ok, bom, header, rows, err)


@dataclass
class XlsxData:
    header: list
    cells: dict  # ref -> list of (value, number_format)
    duplicates: dict


_OOXML_ESC = re.compile(r"_x([0-9A-Fa-f]{4})_")


def _unescape_ooxml(s: str) -> str:
    """openpyxl leaves OOXML escapes such as _x000D_ (a CR) in shared strings."""
    return _OOXML_ESC.sub(lambda m: chr(int(m.group(1), 16)), s) if "_x" in s else s


def read_xlsx(path: Path, sheet: str = "REPD") -> XlsxData:
    import openpyxl  # lazy
    wb = openpyxl.load_workbook(path, read_only=True, data_only=True)
    if sheet not in wb.sheetnames:
        raise ValueError(f"sheet {sheet!r} not in {wb.sheetnames}")
    it = wb[sheet].iter_rows()
    header = ["" if c.value is None else str(c.value) for c in next(it)]
    nh = [norm_header(h) for h in header]
    if REF not in nh:
        raise ValueError("XLSX has no Ref ID column")
    ri = nh.index(REF)
    cells, dups = {}, {}
    for r in it:
        vals = [(_unescape_ooxml(c.value) if isinstance(c.value, str) else c.value, c.number_format) for c in r]
        if not vals or ri >= len(vals) or vals[ri][0] is None:
            continue
        ref = clean_ref(vals[ri][0])
        if ref in cells:
            dups[ref] = dups.get(ref, 1) + 1
            continue
        cells[ref] = vals
    wb.close()
    return XlsxData(header, cells, dups)


# --------------------------------------------------------------------------------------
# Results
# --------------------------------------------------------------------------------------

@dataclass
class Check:
    id: str
    status: str  # PASS / FAIL / SKIP
    summary: str
    details: dict = field(default_factory=dict)


class Report:
    def __init__(self):
        self.checks: dict[str, Check] = {}

    def add(self, cid, ok, summary, **details):
        status = "SKIP" if ok is None else ("PASS" if ok else "FAIL")
        self.checks[cid] = Check(cid, status, summary, details)

    def skip(self, cid, why):
        self.add(cid, None, why)

    @property
    def failed(self):
        return [c for c in self.checks.values() if c.status == "FAIL"]

    def to_json(self):
        return {"checks": [c.__dict__ for c in self.checks.values()],
                "failed": [c.id for c in self.failed],
                "passed": sum(c.status == "PASS" for c in self.checks.values()),
                "skipped": sum(c.status == "SKIP" for c in self.checks.values())}

    def text(self):
        out = []
        for cid in list(CHECK_IDS) + [k for k in self.checks if k not in CHECK_IDS]:
            c = self.checks.get(cid)
            if c:
                out.append(f"{c.status:4}  {c.id:34} {c.summary}")
        out.append(f"-- {len(self.failed)} FAIL, {self.to_json()['passed']} PASS, {self.to_json()['skipped']} SKIP")
        return "\n".join(out)


def _ex(lst, n=8):
    return lst[:n]


# --------------------------------------------------------------------------------------
# File hygiene (applies to cleaned and every root CSV)
# --------------------------------------------------------------------------------------

def file_hygiene(rep: Report, prefix: str, f: CsvFile, reference: dict | None, official: dict | None = None):
    """reference: ref -> {column: correct text (Excel string, else official CSV)} used to name mojibake;
    official: ref -> {column: official CSV value}; mojibake already present in the official cell is
    reported as upstream and does not fail (repairing it would be an undocumented change)."""
    rep.add(f"{prefix}.utf8", f.utf8_ok,
            "valid UTF-8" + (" (with BOM)" if f.bom else "") if f.utf8_ok
            else f"not UTF-8 ({f.utf8_error}); decoded as {f.encoding} for the other checks",
            encoding=f.encoding, bom=f.bom)

    ix = f.index()
    ri = ix.get(REF)
    moj, fffd, named, upstream = [], [], [], []
    for n, r in enumerate(f.rows, start=2):
        rid = r[ri] if ri is not None and ri < len(r) else f"line {n}"
        for j, v in enumerate(r):
            if not v or v.isascii():
                continue
            col = f.nheader[j] if j < len(f.nheader) else f"#{j}"
            src = ((official or {}).get(rid) or {}).get(col)
            if src is not None and norm_ws(src) == norm_ws(v):
                if "\ufffd" in v or is_mojibake(v):
                    upstream.append((rid, col, v[:60]))
                continue
            if "\ufffd" in v:
                fffd.append((rid, col, v[:60]))
            elif is_mojibake(v):
                moj.append((rid, col, v[:60], (demojibake(v) or "")[:60]))
    if reference and ri is not None:
        for r in f.rows:
            if ri >= len(r) or r[ri] not in reference:
                continue
            exp = reference[r[ri]]
            for col in TEXT_COLUMNS: