GLOBALGRID2050 / EXPLORE CODE

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

Test Detect Fetch and 1 more file

A test in the tests folder of GlobalGrid2050 that checks Automation — Renewable Energy Planning Database (REPD) and Renewable Energy Planning Database (REPD) Detect, using SHA-256.

498 lines of Python from globalgrid2050, in 2 files. Topic: Electricity markets and data pipelines. Section 833 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. Test Detect Fetch test · globalgrid2050 / automation/repd/tests/test_detect_fetch.py lines 1–264
  2. Test Diff test · globalgrid2050 / automation/repd/tests/test_diff.py lines 1–234

Test Detect Fetch

A test in the tests folder of GlobalGrid2050 that checks Automation — Renewable Energy Planning Database (REPD) and Renewable Energy Planning Database (REPD) Detect, using SHA-256.

testglobalgrid2050 / automation/repd/tests/test_detect_fetch.py · lines 1–264 of 264 · Entry point · pattern do_GET (shared by 7 files)

What it does
It tests its inputs. Defines 26 functions or classes, including static, f, synthetic_desc, test_descriptors_load_and_registry, test_quarter_parsing. Uses libraries copy, http.server, json, sys, threading. 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.
Inputs & outputs
In: JSON file 2026q2.json; JSON file 2026q3.json; CSV file REPD_Publication_Q3_2026.csv; CSV file repd-q2-jul-2025.csv; CSV file repd-october-2023.csv; JSON file x.json; JSON file content_api_2026q3.json; JSON file detect_report.json. Out: CSV file repd.csv.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
What it achieves
It is built from the static step (`static`), the synthetic desc helper (`synthetic_desc`) and the do get helper (`do_GET`). Tests for `config.py`, `detect.py` and `fetch.py`.
Why it matters
Run by GlobalGrid2050 Project Signals Acid Workflow.
Application
globalgrid2050 · automation/repd/tests · test
Uses
Automation — Renewable Energy Planning Database (REPD) (import), Renewable Energy Planning Database (REPD) Detect (import), Renewable Energy Planning Database (REPD) Fetch (import), copy, http.server, json, sys, threading, pathlib, pytest
Used by
run by GlobalGrid2050 Project Signals Acid Workflow (workflow run)
Produces
static, synthetic_desc, test_descriptors_load_and_registry, test_quarter_parsing, test_descriptor_rejects_mislabel, test_registry_refuses_hash_pinned_twice, test_roundtrip, test_detect_content_api_fixture, test_detect_html_fixture_ignores_preview_script_and_foreign_links, test_detect_html_q2_fixture_vs_q3_baseline_is_older, test_detect_same_quarter_new_urls_is_replacement, test_detect_fails_closed_on_title_file_disagreement_and_missing
Defines here
static, f, synthetic_desc, test_descriptors_load_and_registry, test_quarter_parsing, test_descriptor_rejects_mislabel, test_registry_refuses_hash_pinned_twice, test_roundtrip, test_detect_content_api_fixture, test_detect_html_fixture_ignores_preview_script_and_foreign_links, test_detect_html_q2_fixture_vs_q3_baseline_is_older, test_detect_same_quarter_new_urls_is_replacement, test_detect_fails_closed_on_title_file_disagreement_and_missing, test_detect_cli_offline, test_fetch_writes_raw_and_receipt, test_unpinned_fetch_is_marked, test_trap_redirect_to_newer_quarter_refused_and_nothing_written, test_trap_silent_substitution_caught_by_hash_registry, test_expected_sha_mismatch_and_html_and_bad_xlsx_refused, test_same_quarter_redirect_accepted_with_warning, test_urllib_fetcher_records_real_redirect_chain, H, do_GET, log_message, test_hash_guard_detects_change, test_real_october_files
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/test_detect_fetch.py:1-264 · blob 08ba65ff40e8b0ab998c016923956ac3032ca27c · 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
"""Tests for config.py, detect.py and fetch.py. No network: fixtures are constructed
files and synthetic bytes; one test uses a loopback HTTP server to exercise the real
urllib redirect recorder. Real October files are used only if present (skipped otherwise)."""
import copy
import http.server
import json
import sys
import threading
from pathlib import Path

import pytest

sys.path.insert(0, str(Path(__file__).resolve().parents[3]))

from automation.repd import config, detect, fetch  # noqa: E402
from automation.repd.fetch import FetchRefused, Response  # noqa: E402

FIX = Path(__file__).resolve().parent / "fixtures" / "detect_fetch"
Q2 = config.load(config.RELEASES_DIR / "2026q2.json")
Q3 = config.load(config.RELEASES_DIR / "2026q3.json")
REAL = Path("/home/claude/repd-report/q3")

CSV_BYTES = b"Old Ref ID,Ref ID\r\n1,7679\r\n"
XLSX_BYTES = b"PK\x03\x04" + b"\x00" * 64


def static(mapping, redirects=None, status=200):
    """fetcher over an in-memory {url: bytes} map with optional {url: target} 301s."""
    redirects = redirects or {}

    def f(url):
        chain, cur = [], url
        while cur in redirects:
            chain.append([301, cur])
            cur = redirects[cur]
        chain.append([status, cur])
        return Response(url, cur, chain, mapping[cur])
    return f


def synthetic_desc(**exp):
    d = copy.deepcopy(Q3)
    d.expected = config.Expected(**exp)
    return d


# ---------------------------------------------------------------- config
def test_descriptors_load_and_registry():
    allr = config.load_all()
    assert set(allr) >= {"2026q2", "2026q3"}
    reg = config.known_hashes(allr)
    assert reg[Q3.expected.csv_sha256] == ("2026q3", "csv")
    assert reg[Q2.expected.xlsx_sha256] == ("2026q2", "xlsx")
    assert Q3.expected.csv_rows == 14968 and Q3.expected.duplicate_refs == ["7679"]


def test_quarter_parsing():
    assert config.quarter_from_filename("REPD_Publication_Q3_2026.csv") == (2026, 3)
    assert config.quarter_from_filename("repd-q2-jul-2025.csv") == (2025, 2)
    assert config.quarter_from_filename("repd-october-2023.csv") is None
    assert config.quarter_from_label("REPD: October 2026 (CSV)") == (2026, 3)
    assert config.quarter_from_label("January 2026") == (2025, 4)


def test_descriptor_rejects_mislabel():
    d = Q3.to_dict()
    d["label"] = "July 2026"
    with pytest.raises(config.DescriptorError, match="label"):
        config.ReleaseDescriptor.from_dict(d)
    d = Q2.to_dict()
    d["csv_url"] = Q3.csv_url  # Q3 file under a Q2 descriptor
    with pytest.raises(config.DescriptorError, match="names Q3 2026"):
        config.ReleaseDescriptor.from_dict(d)
    d = Q3.to_dict()
    d["surprise"] = 1
    with pytest.raises(config.DescriptorError, match="unknown"):
        config.ReleaseDescriptor.from_dict(d)


def test_registry_refuses_hash_pinned_twice():
    a, b = copy.deepcopy(Q2), copy.deepcopy(Q3)
    b.expected.csv_sha256 = a.expected.csv_sha256
    with pytest.raises(config.DescriptorError, match="pinned to both"):
        config.known_hashes([a, b])


def test_roundtrip(tmp_path):
    config.dump(Q3, tmp_path / "x.json")
    assert config.load(tmp_path / "x.json") == Q3


# ---------------------------------------------------------------- detect
def test_detect_content_api_fixture():
    raw = (FIX / "content_api_2026q3.json").read_bytes()
    rep = detect.detect(static({config.CONTENT_API: raw}), "api", baseline=Q2)
    d = rep["descriptor"]
    assert rep["status"] == "NEW_RELEASE"
    assert (d["release_id"], d["label"], d["quarter"]) == ("2026q3", "October 2026", "Q3 2026")
    assert d["csv_url"] == Q3.csv_url and d["xlsx_url"] == Q3.xlsx_url
    assert d["page_last_updated"] == "2026-11-13"
    assert d["expected"]["csv_sha256"] is None  # detection never pins hashes


def test_detect_html_fixture_ignores_preview_script_and_foreign_links():
    raw = (FIX / "publication_2026q3.html").read_bytes()
    rep = detect.detect(static({config.SOURCE_PAGE: raw}), "html", baseline=Q3)
    d = rep["descriptor"]
    assert rep["status"] == "UNCHANGED"
    assert d["csv_url"] == Q3.csv_url and "/csv-preview/" not in d["csv_url"]
    assert d["page_last_updated"] == "2026-11-13"   # not the 2099 date inside <script>


def test_detect_html_q2_fixture_vs_q3_baseline_is_older():
    raw = (FIX / "publication_2026q2.html").read_bytes()
    parsed = detect.parse_publication_html(raw.decode())
    d = detect.build_descriptor(parsed)
    assert (d.release_id, d.page_last_updated, d.csv_url) == ("2026q2", "2026-08-03", Q2.csv_url)
    with pytest.raises(detect.DetectError, match="older"):
        detect.compare(d, Q3)


def test_detect_same_quarter_new_urls_is_replacement():
    meta = json.loads((FIX / "content_api_2026q3.json").read_text())
    meta["details"]["attachments"][0]["url"] = meta["details"]["attachments"][0]["url"].replace("6af42ff0", "7bbbbbbb")
    d = detect.build_descriptor(detect.parse_content_api(meta))
    assert detect.compare(d, Q3) == "REPLACED_SAME_QUARTER"


def test_detect_fails_closed_on_title_file_disagreement_and_missing():
    meta = json.loads((FIX / "content_api_2026q3.json").read_text())
    meta["details"]["attachments"][1]["title"] = "REPD: July 2026 (Excel)"
    with pytest.raises(detect.DetectError, match="names Q2 2026"):
        detect.build_descriptor(detect.parse_content_api(meta))
    meta["details"]["attachments"] = meta["details"]["attachments"][:1]
    with pytest.raises(detect.DetectError, match="no REPD .xlsx"):
        detect.build_descriptor(detect.parse_content_api(meta))


def test_detect_cli_offline(tmp_path):
    rc = detect.main(["--kind", "api", "--from-file", str(FIX / "content_api_2026q3.json"),
                      "--baseline", str(config.RELEASES_DIR / "2026q2.json"), "--out", str(tmp_path)])
    assert rc == 0
    assert json.loads((tmp_path / "detect_report.json").read_text())["status"] == "NEW_RELEASE"
    config.load(tmp_path / "detected_2026q3.json")


# ---------------------------------------------------------------- fetch
def test_fetch_writes_raw_and_receipt(tmp_path):
    from automation.repd.fetch import sha256
    desc = synthetic_desc(csv_sha256=sha256(CSV_BYTES), xlsx_sha256=sha256(XLSX_BYTES))
    f = static({desc.csv_url: CSV_BYTES, desc.xlsx_url: XLSX_BYTES})
    rec = fetch.fetch_release(desc, tmp_path, f, registry={})
    assert rec["status"] == "FETCHED_VERIFIED"
    assert (tmp_path / "raw" / "REPD_Publication_Q3_2026.csv").read_bytes() == CSV_BYTES
    on_disk = json.loads((tmp_path / "fetch_receipt.json").read_text())
    c = on_disk["files"][0]
    assert c["bytes"] == len(CSV_BYTES) and c["sha256"] == sha256(CSV_BYTES)
    assert c["status_chain"] == [[200, desc.csv_url]] and c["retrieved_at"].endswith("Z")
    # second run with identical bytes is idempotent; different bytes refused
    fetch.fetch_release(desc, tmp_path, f, registry={})
    desc2 = synthetic_desc()
    with pytest.raises(FetchRefused, match="refusing to overwrite"):
        fetch.fetch_release(desc2, tmp_path, static({desc.csv_url: CSV_BYTES + b"x", desc.xlsx_url: XLSX_BYTES}), registry={})


def test_unpinned_fetch_is_marked(tmp_path):
    desc = synthetic_desc()
    rec = fetch.fetch_release(desc, tmp_path, static({desc.csv_url: CSV_BYTES, desc.xlsx_url: XLSX_BYTES}), registry={})
    assert rec["status"] == "FETCHED_UNPINNED" and rec["files"][0]["warnings"]


def test_trap_redirect_to_newer_quarter_refused_and_nothing_written(tmp_path):
    """July URL 301 -> October file: must not be labelled July."""
    f = static({Q3.csv_url: CSV_BYTES, Q3.xlsx_url: XLSX_BYTES},
               redirects={Q2.csv_url: Q3.csv_url, Q2.xlsx_url: Q3.xlsx_url})
    with pytest.raises(FetchRefused, match="redirected to a file for Q3 2026; refusing to label it Q2 2026"):
        fetch.fetch_release(Q2, tmp_path, f, registry={})
    assert not (tmp_path / "raw").exists() and not (tmp_path / "fetch_receipt.json").exists()


def test_trap_silent_substitution_caught_by_hash_registry(tmp_path):
    """Same URL, no visible redirect (CDN/proxy flattening), but bytes are October's pinned hash."""
    reg = {fetch.sha256(CSV_BYTES): ("2026q3", "csv")}
    f = static({Q2.csv_url: CSV_BYTES, Q2.xlsx_url: XLSX_BYTES})
    with pytest.raises(FetchRefused, match="pinned by release 2026q3"):
        fetch.fetch_release(Q2, tmp_path, f, registry=reg)


def test_expected_sha_mismatch_and_html_and_bad_xlsx_refused(tmp_path):
    desc = synthetic_desc(csv_sha256="0" * 64)
    with pytest.raises(FetchRefused, match="differs from pinned"):
        fetch.fetch_release(desc, tmp_path, static({desc.csv_url: CSV_BYTES, desc.xlsx_url: XLSX_BYTES}), registry={})
    desc = synthetic_desc()
    page = b"<!DOCTYPE html><html>publication page</html>"
    with pytest.raises(FetchRefused, match="HTML page"):
        fetch.fetch_release(desc, tmp_path, static({config.SOURCE_PAGE: page, desc.xlsx_url: XLSX_BYTES},
                                                   redirects={desc.csv_url: config.SOURCE_PAGE}), registry={})
    with pytest.raises(FetchRefused, match="not a zip"):
        fetch.fetch_release(desc, tmp_path, static({desc.csv_url: CSV_BYTES, desc.xlsx_url: CSV_BYTES}), registry={})
    with pytest.raises(FetchRefused, match="not 200"):
        fetch.fetch_release(desc, tmp_path, static({desc.csv_url: CSV_BYTES, desc.xlsx_url: XLSX_BYTES}, status=206), registry={})


def test_same_quarter_redirect_accepted_with_warning(tmp_path):
    new = Q3.csv_url.replace("6af42ff0", "7ccccccc")
    desc = synthetic_desc()
    f = static({new: CSV_BYTES, desc.xlsx_url: XLSX_BYTES}, redirects={desc.csv_url: new})
    rec = fetch.fetch_release(desc, tmp_path, f, registry={})
    c = rec["files"][0]
    assert c["redirected"] and c["final_url"] == new and c["status_chain"][0] == [301, desc.csv_url]


def test_urllib_fetcher_records_real_redirect_chain(tmp_path):
    """Loopback only: a real HTTP 301 -> 302 -> 200 chain is captured hop by hop."""
    class H(http.server.BaseHTTPRequestHandler):
        def do_GET(self):
            hops = {"/media/old/REPD_Publication_Q2_2026.csv": "/media/mid/x",
                    "/media/mid/x": "/media/new/REPD_Publication_Q3_2026.csv"}
            if self.path in hops:
                self.send_response(301 if "old" in self.path else 302)
                self.send_header("Location", hops[self.path])
                self.end_headers()
                return
            self.send_response(200)
            self.send_header("Content-Type", "text/csv")
            self.end_headers()
            self.wfile.write(CSV_BYTES)

        def log_message(self, *a):
            pass

    srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), H)
    threading.Thread(target=srv.serve_forever, daemon=True).start()
    try:
        base = f"http://127.0.0.1:{srv.server_address[1]}"
        r = fetch.urllib_fetcher(use_env_proxy=False, attempts=1, timeout=5)(base + "/media/old/REPD_Publication_Q2_2026.csv")
    finally:
        srv.shutdown()
    assert [s for s, _ in r.status_chain] == [301, 302, 200]
    assert r.final_url.endswith("/media/new/REPD_Publication_Q3_2026.csv") and r.body == CSV_BYTES
    with pytest.raises(FetchRefused, match="Q3 2026"):
        fetch.check_response(r, "csv", Q2, {})


def test_hash_guard_detects_change(tmp_path):
    prot = tmp_path / "prot"
    prot.mkdir()
    (prot / "repd.csv").write_bytes(b"a")
    before = fetch.hash_tree([prot])
    assert fetch.compare_hashes(before, fetch.hash_tree([prot])) == []
    (prot / "repd.csv").write_bytes(b"b")
    assert fetch.compare_hashes(before, fetch.hash_tree([prot]))[0].startswith("changed:")


# ---------------------------------------------------------------- real files (optional)
@pytest.mark.skipif(not (REAL / "REPD_Publication_Q3_2026.csv").exists(), reason="real October files not present")
def test_real_october_files(tmp_path):
    reg = config.known_hashes(config.load_all())
    rec = fetch.fetch_release(Q3, tmp_path / "q3", fetch.local_fetcher(REAL), registry=reg)
    assert rec["status"] == "FETCHED_VERIFIED"
    assert [f["bytes"] for f in rec["files"]] == [5219160, 5378656]
    trap = fetch.local_fetcher(REAL, redirects={Q2.csv_url: Q3.csv_url, Q2.xlsx_url: Q3.xlsx_url})
    with pytest.raises(FetchRefused):
        fetch.fetch_release(Q2, tmp_path / "q2", trap, registry=reg)

Test Diff

A test in the tests folder of GlobalGrid2050 that checks Renewable Energy Planning Database (REPD) Diff.

testglobalgrid2050 / automation/repd/tests/test_diff.py · lines 1–234 of 234 · Entry point · pattern files (shared by 6 files)

What it does
It tests its inputs. Defines 17 functions or classes, including row, write_csv, files, test_csv_to_csv_core_numbers, test_outputs_written_and_deterministic. Uses libraries csv, json, os, pathlib, pytest. 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.
Inputs & outputs
In: CSV file old.csv; CSV file new.csv; JSON file diff.json; JSON file project_identity_v6.json; JSON file p.json; JSON file major_projects_v6.json; CSV file bad.csv; CSV file ragged.csv. Out: JSON file keep.json.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
What it achieves
It writes CSV (`write_csv`) and is built from the row step (`row`) and the files step (`files`). Tests for `automation/repd/diff.py` using small synthetic fixtures (no network, no real data). Its code works with 100 MW. It writes `old.csv`.
Why it matters
Run by GlobalGrid2050 Project Signals Acid Workflow.
Application
globalgrid2050 · automation/repd/tests · test
Uses
Renewable Energy Planning Database (REPD) Diff (import), csv, json, os, pathlib, pytest, re
Used by
run by GlobalGrid2050 Project Signals Acid Workflow (workflow run)
Produces
row, write_csv, files, test_csv_to_csv_core_numbers, test_outputs_written_and_deterministic, test_identity_json_previous, test_identity_json_count_mismatch_fails, test_thresholded_json_rejected, test_duplicate_ref_first_kept, test_fail_closed_on_bad_inputs, test_month_first_dates_are_not_silently_accepted, test_hash_guard_refuses_out_inside_protected
Defines here
row, write_csv, files, test_csv_to_csv_core_numbers, test_outputs_written_and_deterministic, test_identity_json_previous, test_identity_json_count_mismatch_fails, test_thresholded_json_rejected, test_duplicate_ref_first_kept, test_fail_closed_on_bad_inputs, test_month_first_dates_are_not_silently_accepted, test_hash_guard_refuses_out_inside_protected, test_hash_guard_detects_modification, tampering, test_solar_movements_and_top50, test_cli, test_descriptor_entry
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/test_diff.py:1-234 · blob cd06a43e91f3bee3e59303a33feed7a7e6b4b1c0 · 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
"""Tests for automation/repd/diff.py using small synthetic fixtures (no network, no real data)."""
import csv
import json
import os
from pathlib import Path

import pytest

from automation.repd import diff as D

COLS = ["Old Ref ID", "Ref ID", "Record Last Updated (dd/mm/yyyy)", "Operator (or Applicant)", "Site Name",
        "Technology Type", "Installed Capacity (MWelec)", "Development Status (short)", "County", "Region",
        "Country", "Planning Authority", "Planning Application Reference", "Planning Application Submitted",
        "Planning Application Withdrawn", "Planning Permission Refused", "Planning Permission Granted",
        "Planning Permission Expired", "Under Construction", "Operational", "Solar Site Area (sqm)"]


def row(ref, tech="Solar Photovoltaics", mw="10", status="Application Submitted", upd="01/01/2026",
        site=None, op="Op Ltd", granted="", country="England", **kw):
    r = {c: "" for c in COLS}
    r.update({"Ref ID": str(ref), "Record Last Updated (dd/mm/yyyy)": upd, "Operator (or Applicant)": op,
              "Site Name": site or f"Site {ref}", "Technology Type": tech, "Installed Capacity (MWelec)": mw,
              "Development Status (short)": status, "Country": country, "Region": "South East",
              "Planning Permission Granted": granted})
    r.update(kw)
    return r


def write_csv(path, rows, encoding="utf-8-sig", cols=COLS):
    with open(path, "w", encoding=encoding, newline="") as f:
        w = csv.DictWriter(f, fieldnames=cols)
        w.writeheader()
        for r in rows:
            w.writerow({c: r.get(c, "") for c in cols})
    return path


OLD_ROWS = [
    row(1, mw="10.00", status="Application Submitted"),                       # -> consented
    row(2, mw="20.00", status="Awaiting Construction"),                       # -> under construction
    row(3, mw="", status="Under Construction"),                               # -> operational, unknown MW
    row(4, tech="Battery", mw="200.00", status="Application Submitted"),      # -> refused
    row(5, mw="5.00", status="Operational"),                                  # removed
    row(6, mw="49.80", status="Awaiting Construction"),                       # capacity edit +5.2
    row(7, mw="12.35", status="Awaiting Construction"),                       # rounding only
    row(8, tech="Wind Onshore", mw="30.00", status="Application Submitted"),  # withdrawn
]
NEW_ROWS = [
    row(1, mw="10", status="Awaiting Construction", granted="01/09/2026", upd="02/09/2026"),
    row(2, mw="20", status="Under Construction"),
    row(3, mw="", status="Operational"),
    row(4, tech="Battery", mw="200", status="Application Refused"),
    row(6, mw="55", status="Awaiting Construction"),
    row(7, mw="12.3456", status="Awaiting Construction"),
    row(8, tech="Wind Onshore", mw="30", status="Application Withdrawn"),
    row(9, mw="100", status="Awaiting Construction"),                         # added, consented
    row(10, tech="Battery", mw="", status="Application Submitted"),           # added, unknown MW
]


@pytest.fixture
def files(tmp_path):
    old = write_csv(tmp_path / "old.csv", OLD_ROWS, encoding="cp1252")
    new = write_csv(tmp_path / "new.csv", NEW_ROWS)
    return old, new, tmp_path


def test_csv_to_csv_core_numbers(files):
    old, new, tmp = files
    d = D.run(old, new, tmp / "out", "Old", "New")
    s = d["summary"]
    assert (s["added"], s["removed"], s["retained"]) == (2, 1, 7)
    assert s["added_mw"] == 100.0                     # unknown capacity is not zero
    assert d["records"]["added"]["total"]["n_unknown_mw"] == 1
    assert s["removed_mw"] == 5.0
    assert s["status_changes"] == 5
    m = s["milestones"]
    assert m["consented"] == {"n": 2, "mw": 110.0, "n_unknown_mw": 0}
    assert m["under_construction"]["n"] == 1
    assert m["operational"] == {"n": 1, "mw": 0.0, "n_unknown_mw": 1}
    assert m["refused"]["n"] == 1 and m["refused"]["mw"] == 200.0
    assert m["withdrawn"]["n"] == 1
    cat = d["milestones"]["categories"]["consented"]
    assert cat["transition"]["n"] == 1 and cat["new_record"]["n"] == 1
    assert cat["top"][0]["ref"] == "9"               # largest first
    assert cat["by_technology"]["Solar Photovoltaics"]["all"]["n"] == 2
    # capacity: one real edit, rounding ignored
    ce = d["capacity_edits"]
    assert ce["n"] == 1 and ce["edits_by_abs_delta"][0]["ref"] == "6"
    assert ce["net_mw"] == 5.2
    fc = {f["column"]: f["retained_changed"] for f in d["field_changes"]}
    assert fc["Installed Capacity (MWelec)"] == 1
    assert fc["Planning Permission Granted"] == 1


def test_outputs_written_and_deterministic(files):
    old, new, tmp = files
    D.run(old, new, tmp / "a", "Old", "New")
    D.run(old, new, tmp / "b", "Old", "New")
    for name in ("diff.json", "changelog.md"):
        a, b = (tmp / "a" / name).read_bytes(), (tmp / "b" / name).read_bytes()
        assert a == b
        assert str(tmp).encode() not in a            # no absolute paths
    md = (tmp / "a" / "changelog.md").read_text()
    import re
    assert "Generated by" in md
    assert not re.search(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}", md)   # no timestamps
    assert "Newly consented: 2" in md
    assert "## Solar: top 50 movements" in md
    j = json.loads((tmp / "a" / "diff.json").read_text())
    assert "generated" not in j and j["schema"] == D.SCHEMA


def test_identity_json_previous(tmp_path):
    recs = []
    for r in OLD_ROWS:
        cap = D.parse_num(r["Installed Capacity (MWelec)"])
        recs.append({"repd_ref": r["Ref ID"], "repd_old_ref": None, "repd_record_updated": "2026-01-01",
                     "operator": r["Operator (or Applicant)"], "site_name": r["Site Name"],
                     "technology": r["Technology Type"], "capacity_mw": cap, "capacity_known": cap is not None,
                     "status": r["Development Status (short)"], "county": None, "region": "South East",
                     "country": "England", "planning_permission_granted": None, "identity_status": "REPD_BOUND"})
    doc = {"schema": "globalgrid2050.project-identity.v6", "raw_record_count": len(recs), "records": recs,
           "source_hashes": {"csv_sha256": "abc"}}
    jp = tmp_path / "project_identity_v6.json"
    jp.write_text(json.dumps(doc))
    new = write_csv(tmp_path / "new.csv", NEW_ROWS)
    d = D.run(jp, new, tmp_path / "out", "July", "Oct")
    assert d["previous"]["kind"].startswith("derived JSON")
    assert d["summary"]["added"] == 2 and d["summary"]["status_changes"] == 5
    fc = {f["column"]: f["retained_changed"] for f in d["field_changes"]}
    # ISO date in JSON equals dd/mm/yyyy in CSV; only ref 1 changed Record Last Updated
    assert fc["Record Last Updated (dd/mm/yyyy)"] == 1
    assert "Solar Site Area (sqm)" not in fc         # column absent from derived file, not compared
    assert d["conventions"]["columns_only_in_new"] == ["Solar Site Area (sqm)"]


def test_identity_json_count_mismatch_fails(tmp_path):
    jp = tmp_path / "p.json"
    jp.write_text(json.dumps({"schema": "globalgrid2050.project-identity.v6", "raw_record_count": 5,
                              "records": [{"repd_ref": "1", "technology": "Battery", "status": "x"}]}))
    with pytest.raises(D.DiffError, match="raw_record_count"):
        D.load_identity_json(jp)


def test_thresholded_json_rejected(tmp_path):
    jp = tmp_path / "major_projects_v6.json"
    jp.write_text(json.dumps({"schema": "globalgrid2050.major-projects.v6", "records": []}))
    with pytest.raises(D.DiffError, match="not a project-identity"):
        D.load_identity_json(jp)


def test_duplicate_ref_first_kept(tmp_path):
    rows = NEW_ROWS + [NEW_ROWS[0]]
    new = write_csv(tmp_path / "new.csv", rows)
    snap = D.load_csv(new)
    assert snap["info"]["source_rows"] == len(rows)
    assert snap["info"]["unique_refs"] == len(NEW_ROWS)
    assert snap["info"]["duplicate_refs"][0]["kind"] == "identical"


def test_fail_closed_on_bad_inputs(tmp_path):
    bad = write_csv(tmp_path / "bad.csv", [row(1)], cols=[c for c in COLS if c != "Technology Type"])
    with pytest.raises(D.DiffError, match="required columns"):
        D.load_csv(bad)
    ragged = tmp_path / "ragged.csv"
    ragged.write_text(",".join(COLS) + "\n1,2,3\n", encoding="utf-8")
    with pytest.raises(D.DiffError, match="wrong number of fields"):
        D.load_csv(ragged)


def test_month_first_dates_are_not_silently_accepted():
    assert D.parse_date("13/02/2026").isoformat() == "2026-02-13"
    assert D.parse_date("02/13/2026") is None
    assert D.parse_num("") is None and D.parse_num("NA") is None and D.parse_num("1,234.5") == 1234.5


def test_hash_guard_refuses_out_inside_protected(files):
    old, new, tmp = files
    prot = tmp / "released"
    prot.mkdir()
    (prot / "keep.json").write_text("{}")
    with pytest.raises(D.DiffError, match="inside protected"):
        D.run(old, new, prot / "out", protect=[prot])


def test_hash_guard_detects_modification(files, monkeypatch):
    old, new, tmp = files
    prot = tmp / "released"
    prot.mkdir()
    target = prot / "keep.json"
    target.write_text("{}")
    real = D.build_diff

    def tampering(*a, **k):
        target.write_text('{"truncated": true}')
        return real(*a, **k)

    monkeypatch.setattr(D, "build_diff", tampering)
    with pytest.raises(D.DiffError, match="hash guard.*modified"):
        D.run(old, new, tmp / "out", protect=[prot])


def test_solar_movements_and_top50(files):
    old, new, tmp = files
    d = D.run(old, new, tmp / "out")
    so = d["solar"]
    refs = [m["ref"] for m in so["movements_by_mw"]]
    assert refs[0] == "9"                            # 100 MW added
    assert "7" not in refs                           # rounding is not a movement
    assert set(refs) == {"1", "2", "3", "5", "6", "9"}
    assert refs[-1] == "3"                           # unknown MW ranks last
    assert [x["ref"] for x in so["top50_left"]] == ["5"]
    assert so["top50_left"][0]["reason"] == "ref removed"


def test_cli(files, capsys):
    old, new, tmp = files
    rc = D.main(["--previous", str(old), "--new", str(new), "--out", str(tmp / "cli"),
                 "--previous-label", "A", "--new-label", "B", "--protect", str(old)])
    assert rc == 0
    assert (tmp / "cli" / "changelog.md").exists()
    assert "hash guard" in capsys.readouterr().out
    rc = D.main(["--previous", str(tmp / "missing.csv"), "--new", str(new), "--out", str(tmp / "x")])
    assert rc == 2


def test_descriptor_entry(files):
    old, new, tmp = files
    d = D.run_from_descriptor({"previous": str(old), "new": str(new), "out": str(tmp / "desc"),
                               "previous_label": "Q2", "label": "Q3"})
    assert d["new"]["label"] == "Q3"
    with pytest.raises(D.DiffError, match="lacks 'out'"):
        D.run_from_descriptor({"previous": "a", "new": "b"})