GLOBALGRID2050 / EXPLORE CODE

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

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

A Python command-line tool in the automation folder of GlobalGrid2050 that reads the REPD register, transformers and wind, using EPSG:27700 and EPSG:4326.

700 lines of Python from globalgrid2050, in 2 files. Topic: Electricity markets and data pipelines. Section 836 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 Validate test · globalgrid2050 / automation/repd/tests/test_validate.py lines 1–250
  2. Renewable Energy Planning Database (REPD) Validate geodesy · globalgrid2050 / automation/repd/validate.py lines 1–450

Test Validate

A test in the tests folder of GlobalGrid2050 that checks Renewable Energy Planning Database (REPD) Validate and Renewable Energy Planning Database (REPD) Verify Release.

testglobalgrid2050 / automation/repd/tests/test_validate.py · lines 1–250 of 250 · Entry point · pattern write_xlsx (shared by 2 files)

What it does
It tests its inputs. Defines 24 functions or classes, including row, rows_default, write_csv, to_date, write_xlsx. Uses libraries csv, datetime, io, json, os.
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 r.csv; JSON file b.json; JSON file rep.json; Excel file r.xlsx; JSON file k.json; CSV file x.csv; JSON file bb.json; CSV file missing.csv. Out: JSON file bad.json.
Downstream impact
Used directly by 2 files: Test Hardening Nl013 (globalgrid2050); GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
What it achieves
It writes CSV (`write_csv`), writes xlsx (`write_xlsx`) and writes baseline (`write_baseline`). Tests for `automation/repd/validate.py` on small synthetic fixtures (no network, no real data). It writes `r.csv`.
Why it matters
Run by GlobalGrid2050 Project Signals Acid Workflow. Checked by Test Hardening Nl013.
Application
globalgrid2050 · automation/repd/tests · test
Uses
Renewable Energy Planning Database (REPD) Validate (sys.path import), Renewable Energy Planning Database (REPD) Verify Release (sys.path import), csv, datetime, io, json, os, sys, pytest, openpyxl
Used by
imported by Test Hardening Nl013 (import), run by GlobalGrid2050 Project Signals Acid Workflow (workflow run)
Produces
row, rows_default, write_csv, to_date, write_xlsx, write_baseline, run, test_clean_release_passes, test_missing_column_fails, test_identical_duplicate_warns_conflicting_fails, test_ref_sets_differ_fails, test_row_floor_below_previous_release_fails
Defines here
row, rows_default, write_csv, to_date, write_xlsx, write_baseline, run, test_clean_release_passes, test_missing_column_fails, test_identical_duplicate_warns_conflicting_fails, test_ref_sets_differ_fails, test_row_floor_below_previous_release_fails, test_truncated_last_record_fails, test_impossible_date_without_excel_fallback_fails, test_month_first_csv_date_resolved_by_typed_excel, test_na_marker_and_future_dates_are_warnings_with_refs, test_new_vocabulary_value_warns_or_fails_strict, test_coordinates_non_numeric_and_out_of_bounds, test_known_anomalies_downgrade_bounds_and_report, test_tab_padded_coordinates_are_numeric_but_reported, test_csv_only_skip_and_xlsx_required, test_unusable_input_exit_2, test_make_baseline_from_csv_and_identity, test_reconciliation_v6_accepted_as_count_baseline
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_validate.py:1-250 · blob 536b344399c8afeaeda3279636114a9629df8c31 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
"""Tests for automation/repd/validate.py on small synthetic fixtures (no network, no real data)."""
import csv
import datetime
import io
import json
import os
import sys

import pytest

HERE = os.path.dirname(os.path.abspath(__file__))
PKG = os.path.dirname(HERE)
if PKG not in sys.path:
    sys.path.insert(0, PKG)

import validate as V  # noqa: E402
import verify_release as vr  # noqa: E402

COLS = vr.EXPECTED_COLUMNS
ASOF = '2026-11-13'


def row(ref, **kw):
    base = {c: '' for c in COLS}
    base.update({'Ref ID': str(ref), 'Record Last Updated (dd/mm/yyyy)': '01/09/2026', 'Site Name': f'Site {ref}',
                 'Technology Type': 'Solar Photovoltaics', 'Development Status (short)': 'Operational',
                 'Development Status': 'Operational', 'Installed Capacity (MWelec)': '5', 'Country': 'England',
                 'Region': 'South East', 'X-coordinate': str(450000 + int(ref) * 10), 'Y-coordinate': '150000',
                 'Planning Application Submitted': '01/02/2020', 'Operational': '01/03/2022'})
    for k, v in kw.items():
        base[k.replace('_', ' ') if k not in COLS else k] = v
    return base


def rows_default(n=12):
    return [row(i) for i in range(1, n + 1)]


def write_csv(path, rows, cols=COLS, truncate=0):
    buf = io.StringIO()
    w = csv.writer(buf, lineterminator='\r\n')
    w.writerow(cols)
    for r in rows:
        w.writerow([r.get(c, '') for c in cols])
    data = buf.getvalue().encode('cp1252')
    if truncate:
        data = data[:-truncate]
    path.write_bytes(data)
    return str(path)


def to_date(s):
    try:
        return datetime.datetime.strptime(s, '%d/%m/%Y')
    except ValueError:
        return s


def write_xlsx(path, rows, xlsx_dates=None):
    import openpyxl
    wb = openpyxl.Workbook()
    ws = wb.active
    ws.title = 'REPD'
    ws.append(COLS)
    for r in rows:
        vals = []
        for c in COLS:
            v = r.get(c, '')
            if vr.nh(c) in vr.DATE_COLUMNS and v:
                v = to_date(v)
            if xlsx_dates and (r['Ref ID'], c) in xlsx_dates:
                v = xlsx_dates[(r['Ref ID'], c)]
            if c == 'Ref ID':
                v = int(v)
            vals.append(v if v != '' else None)
        ws.append(vals)
    wb.save(path)
    return str(path)


def write_baseline(path, rows=10, tech=('Solar Photovoltaics',), status=('Operational',), refs=None):
    b = {'schema': V.BASELINE_SCHEMA, 'release_id': 'prev', 'rows': rows, 'unique_refs': rows,
         'refs': refs if refs is not None else [str(i) for i in range(1, rows + 1)],
         'vocab': {'Technology Type': {t: 1 for t in tech}, 'Development Status (short)': {s: 1 for s in status}}}
    path.write_text(json.dumps(b))
    return str(path)


def run(tmp_path, rows, xrows=None, baseline_kw=None, extra=(), xlsx_dates=None, truncate=0, xlsx=True, cols=COLS):
    c = write_csv(tmp_path / 'r.csv', rows, cols=cols, truncate=truncate)
    b = write_baseline(tmp_path / 'b.json', **(baseline_kw or {}))
    out = tmp_path / 'rep.json'
    args = ['check', '--csv', c, '--baseline', b, '--asof', ASOF, '--json', str(out), '--quiet', *extra]
    if xlsx:
        args += ['--xlsx', write_xlsx(tmp_path / 'r.xlsx', xrows if xrows is not None else rows, xlsx_dates)]
    code = V.main(args)
    rep = json.loads(out.read_text()) if out.exists() else None
    return code, rep, ({g['id']: g for g in rep['gates']} if rep else {})


def test_clean_release_passes(tmp_path):
    code, rep, g = run(tmp_path, rows_default())
    assert code == 0 and rep['result'] == 'PASS'
    for gid in ('S1_columns_53_in_order', 'S2_ref_ids_unique_after_identical_dedupe', 'S3_csv_xlsx_ref_sets_equal',
                'S4_row_floor_vs_previous_release', 'S5_last_record_complete', 'C1_dates_valid', 'C2_future_dates',
                'C3_vocabularies_vs_previous', 'C4_coordinates_numeric_and_in_bounds'):
        assert g[gid]['status'] == 'pass', (gid, g[gid])


def test_missing_column_fails(tmp_path):
    cols = [c for c in COLS if c != 'Heat Network Ref']
    code, rep, g = run(tmp_path, rows_default(), cols=cols, xlsx=False, extra=['--csv-only'])
    assert code == 1 and g['S1_columns_53_in_order']['status'] == 'fail'


def test_identical_duplicate_warns_conflicting_fails(tmp_path):
    rs = rows_default()
    code, rep, g = run(tmp_path, rs + [dict(rs[3])])
    assert code == 0 and g['S2_ref_ids_unique_after_identical_dedupe']['status'] == 'warn'
    assert g['S2_ref_ids_unique_after_identical_dedupe']['detail']['identical_duplicates'] == ['4']
    bad = dict(rs[3]); bad['Site Name'] = 'Different'
    code, rep, g = run(tmp_path, rs + [bad])
    assert code == 1 and g['S2_ref_ids_unique_after_identical_dedupe']['status'] == 'fail'


def test_ref_sets_differ_fails(tmp_path):
    rs = rows_default()
    code, rep, g = run(tmp_path, rs, xrows=rs[:-1])
    assert code == 1 and g['S3_csv_xlsx_ref_sets_equal']['status'] == 'fail'
    assert g['S3_csv_xlsx_ref_sets_equal']['detail']['refs_only_in_csv']['examples'] == ['12']


def test_row_floor_below_previous_release_fails(tmp_path):
    code, rep, g = run(tmp_path, rows_default(12), baseline_kw={'rows': 13, 'refs': [str(i) for i in range(1, 14)]})
    assert code == 1 and g['S4_row_floor_vs_previous_release']['status'] == 'fail'
    assert g['S4b_refs_dropped_since_previous_release']['detail']['refs'] == ['13']


def test_truncated_last_record_fails(tmp_path):
    code, rep, g = run(tmp_path, rows_default(), xlsx=False, extra=['--csv-only'], truncate=40)
    assert code == 1 and g['S5_last_record_complete']['status'] == 'fail'


def test_impossible_date_without_excel_fallback_fails(tmp_path):
    rs = rows_default(); rs[2]['Operational'] = '31/02/2022'
    code, rep, g = run(tmp_path, rs, xlsx=False, extra=['--csv-only'])
    assert code == 1 and g['C1_dates_valid']['status'] == 'fail'
    assert g['C1_dates_valid']['detail']['invalid'][0]['ref'] == '3'


def test_month_first_csv_date_resolved_by_typed_excel(tmp_path):
    rs = rows_default()
    rs[4]['Planning Application Submitted'] = '9/14/2026'   # impossible as d/m
    rs[5]['Planning Application Submitted'] = '09/11/2026'  # valid as d/m but swapped
    xd = {('5', 'Planning Application Submitted'): datetime.datetime(2026, 9, 14),
          ('6', 'Planning Application Submitted'): datetime.datetime(2026, 9, 11)}
    code, rep, g = run(tmp_path, rs, xlsx_dates=xd)
    assert code == 0
    c1 = g['C1_dates_valid']
    assert c1['status'] == 'warn' and sorted(i['ref'] for i in c1['detail']['resolvable_non_canonical']) == ['5', '6']


def test_na_marker_and_future_dates_are_warnings_with_refs(tmp_path):
    rs = rows_default()
    rs[0]['Operational'] = 'NA'
    rs[1]['Planning Permission  Granted'] = '15/12/2026'
    rs[2]['Planning Permission Expired'] = '01/01/2030'   # expiry may be in the future
    code, rep, g = run(tmp_path, rs, xlsx=False, extra=['--csv-only'])
    assert code == 0
    assert g['C1b_date_na_markers']['status'] == 'warn' and g['C1b_date_na_markers']['detail']['cells'][0]['ref'] == '1'
    fut = g['C2_future_dates']['detail']['future']
    assert [f['ref'] for f in fut] == ['2'] and g['C2_future_dates']['detail']['expiry_dates_in_future'] == {'Planning Permission Expired': 1}


def test_new_vocabulary_value_warns_or_fails_strict(tmp_path):
    rs = rows_default(); rs[0]['Technology Type'] = 'Fusion'
    code, rep, g = run(tmp_path, rs, xlsx=False, extra=['--csv-only'])
    c3 = g['C3_vocabularies_vs_previous']
    assert code == 0 and c3['status'] == 'warn' and c3['detail']['Technology Type']['new_values'] == {'Fusion': 1}
    assert c3['detail']['Technology Type']['new_value_refs'] == {'Fusion': ['1']}
    code, rep, g = run(tmp_path, rs, xlsx=False, extra=['--csv-only', '--strict-vocab'])
    assert code == 1


def test_coordinates_non_numeric_and_out_of_bounds(tmp_path):
    rs = rows_default(); rs[0]['X-coordinate'] = 'abc'; rs[1]['Y-coordinate'] = '9999999'
    code, rep, g = run(tmp_path, rs, xlsx=False, extra=['--csv-only'])
    c4 = g['C4_coordinates_numeric_and_in_bounds']
    assert code == 1 and c4['status'] == 'fail'
    assert c4['detail']['non_numeric'][0]['ref'] == '1' and c4['detail']['outside_hard_bounds'][0]['ref'] == '2'


def test_known_anomalies_downgrade_bounds_and_report(tmp_path):
    rs = rows_default(); rs[1]['Y-coordinate'] = '9999999'
    known = tmp_path / 'k.json'
    known.write_text(json.dumps({'known': {'2': 'bad coordinates in source', '99': 'gone'}}))
    code, rep, g = run(tmp_path, rs, xlsx=False, extra=['--csv-only', '--known-anomalies', str(known)])
    assert code == 0 and g['C4_coordinates_numeric_and_in_bounds']['status'] == 'warn'
    assert g['C5_known_anomaly_report']['detail']['known_items_no_longer_present'] == ['99']


def test_tab_padded_coordinates_are_numeric_but_reported(tmp_path):
    rs = rows_default(); rs[0]['X-coordinate'] = '\t450010'
    code, rep, g = run(tmp_path, rs, xlsx=False, extra=['--csv-only'])
    assert code == 0
    assert any(a['anomaly'] == 'HIDDEN_CHARS' and a['ref'] == '1' for a in g['C5_known_anomaly_report']['detail']['anomalies'])


def test_csv_only_skip_and_xlsx_required(tmp_path):
    code, rep, g = run(tmp_path, rows_default(), xlsx=False, extra=['--csv-only'])
    assert code == 0 and g['S3_csv_xlsx_ref_sets_equal']['status'] == 'skip'
    c = write_csv(tmp_path / 'x.csv', rows_default())
    b = write_baseline(tmp_path / 'bb.json')
    assert V.main(['check', '--csv', c, '--baseline', b, '--quiet']) == 2


def test_unusable_input_exit_2(tmp_path):
    b = write_baseline(tmp_path / 'b.json')
    assert V.main(['check', '--csv', str(tmp_path / 'missing.csv'), '--csv-only', '--baseline', b, '--quiet']) == 2
    (tmp_path / 'bad.json').write_text('{"schema": "x"}')
    c = write_csv(tmp_path / 'r.csv', rows_default())
    assert V.main(['check', '--csv', c, '--csv-only', '--baseline', str(tmp_path / 'bad.json'), '--quiet']) == 2


def test_make_baseline_from_csv_and_identity(tmp_path):
    c = write_csv(tmp_path / 'p.csv', rows_default(7))
    out = tmp_path / 'b.json'
    assert V.main(['make-baseline', '--from-csv', c, '--release-id', 'p', '--out', str(out)]) == 0
    b = json.loads(out.read_text())
    assert b['rows'] == 7 and b['refs'] == [str(i) for i in range(1, 8)]
    assert b['vocab']['Technology Type'] == {'Solar Photovoltaics': 7}
    ident = tmp_path / 'id.json'
    ident.write_text(json.dumps({'raw_record_count': 2, 'records': [
        {'repd_ref': '1', 'status': 'Operational', 'technology': 'Battery'},
        {'repd_ref': '5', 'status': 'Revised', 'technology': 'Battery'}]}))
    assert V.main(['make-baseline', '--from-identity-v6', str(ident), '--release-id', 'q', '--out', str(out)]) == 0
    b = json.loads(out.read_text())
    assert b['rows'] == 2 and b['vocab']['Development Status (short)'] == {'Operational': 1, 'Revised': 1}


def test_reconciliation_v6_accepted_as_count_baseline(tmp_path):
    r = tmp_path / 'rec.json'
    r.write_text(json.dumps({'schema': 'globalgrid2050.repd-source-reconciliation.v6',
                             'metrics': {'csv_rows': 11, 'csv_unique_refs': 11}}))
    c = write_csv(tmp_path / 'r.csv', rows_default(12))
    out = tmp_path / 'o.json'
    assert V.main(['check', '--csv', c, '--csv-only', '--baseline', str(r), '--json', str(out), '--quiet']) == 0
    g = {x['id']: x for x in json.loads(out.read_text())['gates']}
    assert g['S4_row_floor_vs_previous_release']['status'] == 'pass'
    assert g['C3_vocabularies_vs_previous']['status'] == 'warn'

Renewable Energy Planning Database (REPD) Validate

A Python command-line tool in the automation folder of GlobalGrid2050 that reads the REPD register, transformers and wind, using EPSG:27700 and EPSG:4326.

geodesyglobalgrid2050 / automation/repd/validate.py · lines 1–450 of 711 · Entry point · pattern parse_coord (shared by 2 files)

What it does
It loads the REPD register, transformers and wind. Defines 26 functions or classes, including cell_flags, parse_coord, inbox, sha256_file, _refkey. Uses libraries argparse, collections, datetime, 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, transformers, wind.
Inputs & outputs
In: command-line arguments. Out: JSON file. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid), WGS84 / EPSG:4326.
Downstream impact
Used directly by 1 file: Test Validate (globalgrid2050). Reached from 2 other entry points, including GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050); Test Hardening Nl013 (globalgrid2050).
What it achieves
It parses coord (`parse_coord`), loads baseline (`load_baseline`) and loads known coordinates (`load_known_coordinates`). Release gates for a REPD quarterly extract (raw official files or a cleaned candidate). It accepts `--csv`, `--xlsx` and `--sheet`.
Why it matters
Checked by Test Validate.
Application
globalgrid2050 · automation/repd · Python CLI
Uses
Renewable Energy Planning Database (REPD) Verify Release (relative import), argparse, collections, datetime, hashlib, json, math, os, re
Used by
imported by Test Validate (sys.path import)
Produces
cell_flags, parse_coord, inbox, sha256_file, baseline_from_rows, baseline_from_identity_v6, baseline_from_csv, load_baseline, Gates, source_gates, date_gates, vocab_gates
Defines here
cell_flags, parse_coord, inbox, sha256_file, _refkey, baseline_from_rows, baseline_from_identity_v6, baseline_from_csv, load_baseline, Gates, __init__, add, failed, source_gates, _xlsx_date_index, _csv_text_is_date, date_gates, vocab_gates, coordinate_gates, add
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/validate.py:1-450 · blob 58d2b3f71b117ab7226bac4dc357d54e3bc6724a · 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
"""validate.py - release gates for a REPD quarterly extract (raw official files or a cleaned candidate).

Reuses (does not rewrite):
  automation/repd/verify_release.py  - verbatim copy of the private prototype tools/verify_release.py
                                       (CSV/XLSX parsing, 53-column header check, ref/duplicate analysis,
                                       last-record completeness, CSV-vs-XLSX comparison, expectations)
  work7/coord_audit.py               - coordinate parsing, hidden-character flags, BNG envelope, country/region
                                       boxes and the same-region neighbour test (constants copied below)
  scripts/repd_q3_staging_verify.py  - its "rows == unique refs after dedupe", "last Ref ID present" and
                                       dd/mm/yyyy date assertions are expressed here as named gates

Usage
  python3 -I validate.py check --csv REPD.csv [--xlsx REPD.xlsx | --csv-only] --baseline PREV.json
          [--known-anomalies KNOWN.json] [--asof YYYY-MM-DD] [--json report.json] [--verify-json full.json]
          [--expect-rows N] [--expect-unique-refs N] [--expect-csv-sha256 H] [--expect-xlsx-sha256 H]
          [--strict-vocab]
  python3 -I validate.py make-baseline (--from-csv PREV.csv | --from-identity-v6 project_identity_v6.json)
          --release-id 2026q2 --out PREV.json

Gate status: pass | warn | fail | skip.  Warnings never fail the run; skips are only allowed when asked for
(--csv-only skips the CSV-vs-XLSX gates explicitly and says so).
Exit status: 0 = every gate pass/warn/skip-as-requested; 1 = at least one gate failed;
             2 = could not run (missing/unreadable input, bad baseline, usage error).
"""
import argparse
import collections
import datetime
import hashlib
import json
import math
import os
import re
import sys

_HERE = os.path.dirname(os.path.abspath(__file__))
try:  # package import (automation.repd.validate)
    from . import verify_release as vr  # type: ignore
except ImportError:  # run as a script or imported from its own directory
    if _HERE not in sys.path:
        sys.path.insert(0, _HERE)
    import verify_release as vr  # type: ignore

SCHEMA = 'globalgrid2050.repd-validate.v1'
BASELINE_SCHEMA = 'globalgrid2050.repd-validate-baseline.v1'
REF = vr.REF
UPDATED = vr.UPDATED
DATE_COLUMNS = vr.DATE_COLUMNS
FUTURE_ALLOWED = vr.FUTURE_ALLOWED
VOCAB_COLUMNS = ('Development Status (short)', 'Technology Type')
NA_MARKERS = {'NA', 'N/A', '#N/A', 'N.A.'}

# ---- coordinate constants, copied from work7/coord_audit.py ----
OFFSHORE_TECH = {'Wind Offshore', 'Tidal Stream', 'Tidal Lagoon', 'Tidal Barrage and Tidal Stream',
                 'Shoreline Wave', 'Wave'}
COUNTRY_BOX = {
    'England': (49.80, 55.85, -6.50, 1.90),
    'Scotland': (54.60, 60.95, -8.70, -0.70),
    'Wales': (51.30, 53.50, -5.40, -2.60),
    'Northern Ireland': (54.00, 55.40, -8.20, -5.40),
}
REGION_BOX = {
    'North East': (54.40, 55.85, -2.70, -0.75),
    'North West': (52.90, 55.20, -3.70, -1.90),
    'Yorkshire and Humber': (53.25, 54.60, -2.60, 0.20),
    'East Midlands': (51.95, 53.65, -2.05, 0.40),
    'West Midlands': (51.80, 53.25, -3.25, -1.15),
    'Eastern': (51.40, 53.00, -0.80, 1.80),
    'London': (51.25, 51.72, -0.55, 0.35),
    'South East': (50.50, 52.25, -1.98, 1.50),
    'South West': (49.80, 52.15, -6.50, -1.45),
    'Wales': COUNTRY_BOX['Wales'],
    'Scotland': COUNTRY_BOX['Scotland'],
    'Northern Ireland': COUNTRY_BOX['Northern Ireland'],
}
REGION_COUNTRY = {r: 'England' for r in REGION_BOX}
REGION_COUNTRY.update({'Wales': 'Wales', 'Scotland': 'Scotland', 'Northern Ireland': 'Northern Ireland'})
PAD_ON, PAD_OFF = 0.10, 2.00
# soft envelope (coord_audit): outside it is an anomaly (warn); offshore arrays legitimately exceed E 700000
BNG_E, BNG_N = (-50000, 700000), (0, 1250000)
# hard bounds (gate): outside these the value cannot be a UK/offshore British National Grid coordinate
HARD_E, HARD_N = (-250000, 900000), (-50000, 1350000)
ISO_KM = 25.0
_NUM = re.compile(r'^-?\d+(\.\d+)?$')


def cell_flags(s):
    f = []
    if s != s.strip(' '):
        f.append('SPACE_PAD')
    if '\t' in s:
        f.append('TAB')
    if '\r' in s or '\n' in s:
        f.append('CR_LF')
    if '\xa0' in s:
        f.append('NBSP')
    if any(ord(c) < 32 and c not in '\t\r\n' for c in s) or '' in s:
        f.append('OTHER_CONTROL')
    return f


def parse_coord(s):
    c = (s or '').replace('\xa0', ' ').replace('', '').strip().replace(',', '')
    if c == '':
        return None, 'BLANK'
    if not _NUM.match(c):
        return None, 'NON_NUMERIC'
    return float(c), 'OK'


def inbox(lat, lon, box, pad):
    return box[0] - pad <= lat <= box[1] + pad and box[2] - pad <= lon <= box[3] + pad


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


def _refkey(r):
    return (not r.isdigit(), int(r) if r.isdigit() else 0, r)


# =================================================================== baseline
def baseline_from_rows(dicts, release_id, source):
    refs = [vr.clean_ref(d.get(REF, '')) for d in dicts]
    vocab = {}
    for col in VOCAB_COLUMNS:
        vocab[col] = dict(sorted(collections.Counter((d.get(col) or '').strip() for d in dicts).items()))
    return {'schema': BASELINE_SCHEMA, 'release_id': release_id, 'source': source,
            'rows': len(dicts), 'unique_refs': len(set(refs)),
            'refs': sorted(set(r for r in refs if r), key=_refkey), 'vocab': vocab}


def baseline_from_identity_v6(path, release_id):
    d = json.load(open(path, encoding='utf-8'))
    recs = d['records']
    repd = [r for r in recs if r.get('repd_ref')]
    dicts = [{REF: str(r['repd_ref']), 'Development Status (short)': r.get('status') or '',
              'Technology Type': r.get('technology') or ''} for r in repd]
    b = baseline_from_rows(dicts, release_id, {'kind': 'project_identity_v6', 'path': path,
                                                'sha256': sha256_file(path),
                                                'declared_source_hashes': d.get('source_hashes'),
                                                'source_dataset_title': d.get('source_dataset_title')})
    declared = d.get('raw_record_count')
    if declared is not None and declared != b['rows']:
        raise ValueError(f'identity file declares raw_record_count={declared} but holds {b["rows"]} REPD records')
    b['rows'] = declared if declared is not None else b['rows']
    return b


def baseline_from_csv(path, release_id):
    rep = vr.Report(5)
    c = vr.check_csv(path, datetime.date.today(), rep)
    if c is None or rep.structural:
        raise ValueError(f'baseline CSV {path} has structural errors: {rep.structural}')
    return baseline_from_rows(c['dicts'], release_id, {'kind': 'csv', 'path': path, 'sha256': sha256_file(path)})


def load_baseline(path):
    b = json.load(open(path, encoding='utf-8'))
    if b.get('schema') == BASELINE_SCHEMA:
        for k in ('rows', 'vocab', 'release_id'):
            if k not in b:
                raise ValueError(f'baseline {path} lacks {k!r}')
        return b
    # accept the July repd_source_reconciliation_v6.json (counts only, no vocabularies)
    if b.get('schema') == 'globalgrid2050.repd-source-reconciliation.v6':
        m = b['metrics']
        return {'schema': BASELINE_SCHEMA, 'release_id': 'reconciliation_v6', 'rows': m['csv_rows'],
                'unique_refs': m['csv_unique_refs'], 'refs': None, 'vocab': {},
                'source': {'kind': 'repd_source_reconciliation_v6', 'path': path}}
    raise ValueError(f'{path}: not a validate baseline (schema {b.get("schema")!r})')


# =================================================================== gates
class Gates:
    def __init__(self):
        self.items = []

    def add(self, gid, group, status, summary, **detail):
        assert status in ('pass', 'warn', 'fail', 'skip')
        self.items.append({'id': gid, 'group': group, 'status': status, 'summary': summary, 'detail': detail})
        return status

    def failed(self):
        return [g for g in self.items if g['status'] == 'fail']


def source_gates(G, rep, c, x, base, csv_only):
    d = rep.data
    # S1 columns
    hdr_ok = d.get('csv.header_match_after_whitespace_normalisation') is True and d.get('csv.columns') == 53
    det = {'csv_columns': d.get('csv.columns'), 'csv_exact_verbatim': d.get('csv.header_exact_match_53_in_order'),
           'csv_whitespace_differences': d.get('csv.header_whitespace_or_text_differences', [])}
    if x is not None:
        xok = d.get('xlsx.header_match_after_whitespace_normalisation') is True and d.get('xlsx.columns') == 53
        hdr_ok = hdr_ok and xok
        det.update(xlsx_columns=d.get('xlsx.columns'), xlsx_exact_verbatim=d.get('xlsx.header_exact_match_53_in_order'))
    if not hdr_ok:
        det.update(missing=d.get('csv.header_missing'), unexpected=d.get('csv.header_unexpected'))
    G.add('S1_columns_53_in_order', 'source', 'pass' if hdr_ok else 'fail',
          '53 official columns in order (whitespace-normalised)' if hdr_ok else 'header is not the 53 official columns in order', **det)

    # S2 ids unique after identical-duplicate handling
    dup = d.get('csv.duplicate_refs') or {}
    blank = d.get('csv.blank_refs', 0)
    conflicting = [x_ for x_ in dup.get('detail', []) if x_['kind'] != 'identical']
    identical = [x_['ref'] for x_ in dup.get('detail', []) if x_['kind'] == 'identical']
    status = 'fail' if (conflicting or blank) else ('warn' if identical else 'pass')
    xdet = {}
    if x is not None:
        xdup = d.get('xlsx.duplicate_refs') or {}
        xconf = [x_ for x_ in xdup.get('detail', []) if x_['kind'] != 'identical']
        xdet = {'xlsx_identical_duplicates': [x_['ref'] for x_ in xdup.get('detail', []) if x_['kind'] == 'identical'],
                'xlsx_conflicting_duplicates': xconf, 'xlsx_blank_refs': d.get('xlsx.blank_refs', 0)}
        if xconf or d.get('xlsx.blank_refs', 0):
            status = 'fail'
    G.add('S2_ref_ids_unique_after_identical_dedupe', 'source', status,
          f'{d.get("csv.unique_refs")} unique refs in {d.get("csv.rows")} rows; identical duplicates {identical}; '
          f'conflicting {len(conflicting)}; blank {blank}',
          rows=d.get('csv.rows'), unique_refs=d.get('csv.unique_refs'), identical_duplicates=identical,
          conflicting_duplicates=conflicting, blank_refs=blank,
          non_numeric_refs=d.get('csv.non_numeric_refs'), **xdet)

    # S3 CSV and XLSX ref sets equal
    if x is None:
        G.add('S3_csv_xlsx_ref_sets_equal', 'source', 'skip' if csv_only else 'fail',
              'skipped by --csv-only (cleaned candidate)' if csv_only else 'no XLSX given (use --csv-only to skip explicitly)')
    else:
        eq = d.get('compare.ref_sets_equal') is True
        occ = d.get('compare.refs_with_different_occurrence_counts') or []
        rc = d.get('compare.row_counts')
        ok = eq and not occ and rc['csv'] == rc['xlsx']
        G.add('S3_csv_xlsx_ref_sets_equal', 'source', 'pass' if ok else 'fail',
              f'ref sets equal={eq}; rows csv={rc["csv"]} xlsx={rc["xlsx"]}',
              refs_only_in_csv=d.get('compare.refs_only_in_csv'), refs_only_in_xlsx=d.get('compare.refs_only_in_xlsx'),
              refs_with_different_occurrence_counts=occ, row_counts=rc)

    # S4 row floor vs previous release (actual count from baseline file)
    uniq = d.get('csv.unique_refs') or 0
    floor = base['rows']
    det = {'baseline_release': base.get('release_id'), 'baseline_rows': floor, 'unique_refs': uniq,
           'rows': d.get('csv.rows'), 'baseline_source': base.get('source')}
    if base.get('refs'):
        cur = {vr.clean_ref(r.get(REF, '')) for r in c['dicts']}
        prev = set(base['refs'])
        dropped = sorted(prev - cur, key=_refkey)
        det.update(refs_dropped_since_baseline={'count': len(dropped), 'refs': dropped[:200]},
                   refs_new_since_baseline=len(cur - prev))
    G.add('S4_row_floor_vs_previous_release', 'source', 'pass' if uniq >= floor else 'fail',
          f'{uniq} unique refs vs previous release {floor} ({base.get("release_id")})', **det)
    if det.get('refs_dropped_since_baseline', {}).get('count'):
        G.add('S4b_refs_dropped_since_previous_release', 'source', 'warn',
              f'{det["refs_dropped_since_baseline"]["count"]} refs of the previous release are absent',
              refs=det['refs_dropped_since_baseline']['refs'])

    # S5 last record complete (and the whole file parsed with a constant field count)
    last = d.get('csv.last_record') or {}
    ragged = any('do not have' in s for s in rep.structural)
    ok = last.get('verdict') == 'complete' and not d.get('csv.parse_error') and not ragged
    det = {'csv_last_record': last, 'parse_error': d.get('csv.parse_error'), 'ragged_rows': ragged,
           'field_count_histogram': d.get('csv.field_count_histogram')}
    if x is not None and x['dicts']:
        xlast = vr.clean_ref(x['dicts'][-1][REF][0]) if REF in x['dicts'][-1] else None
        det['xlsx_last_ref'] = xlast
        if last.get('ref') is not None and xlast != vr.clean_ref(last.get('ref')):
            det['last_ref_differs'] = True
    G.add('S5_last_record_complete', 'source', 'pass' if ok else 'fail',
          f'last record ref {last.get("ref")}: {last.get("verdict")}', **det)

    # S6 expectations (descriptor-provided counts/hashes), only when given
    if d.get('expectations') is not None:
        res = d['expectations']
        bad = [r for r in res if not r['pass']]
        G.add('S6_descriptor_expectations', 'source', 'fail' if bad else 'pass',
              f'{len(res) - len(bad)}/{len(res)} expectations met', results=res)

    # S7 other structural findings of verify_release not already covered above
    other = [s for s in rep.structural if 'header' not in s and 'Ref ID sets' not in s and 'last CSV record' not in s
             and 'do not have' not in s]
    if other:
        G.add('S7_other_structural', 'source', 'fail', '; '.join(other), findings=other)


def _xlsx_date_index(x):
    """ref -> {col: (kind, date)} for the first occurrence of each ref in the XLSX"""
    out = {}
    if x is None:
        return out
    for dct in x['dicts']:
        ref = vr.clean_ref(dct[REF][0]) if REF in dct else ''
        if ref in out:
            continue
        out[ref] = {col: vr.classify_xlsx_date(dct[col])[:2] for col in DATE_COLUMNS if col in dct}
    return out


_MDY_ANY = re.compile(r'^(\d{1,2})/(\d{1,2})/(\d{4})$')


def _csv_text_is_date(raw, dt, xd):
    """True when CSV text ``raw`` (parsed day-first as ``dt``, or None) denotes the typed XLSX date ``xd``
    as written day-first, ISO, or month-first."""
    if dt is not None and (dt == xd or vr.swap_dm(dt) == xd):
        return True
    m = _MDY_ANY.match(raw.strip())
    if m:
        try:
            return datetime.date(int(m.group(3)), int(m.group(1)), int(m.group(2))) == xd
        except ValueError:
            return False
    return False


def date_gates(G, c, x, asof):
    xi = _xlsx_date_index(x)
    invalid, resolved, na_cells, future, future_allowed = [], [], [], [], collections.Counter()
    forms = collections.defaultdict(collections.Counter)
    for dct, rn in zip(c['dicts'], c['rownum']):
        ref = vr.clean_ref(dct.get(REF, ''))
        for col in DATE_COLUMNS:
            if col not in dct:
                continue
            raw = (dct.get(col) or '').strip()
            if not raw:
                continue
            if raw.upper() in NA_MARKERS:
                na_cells.append({'ref': ref, 'field': col, 'value': raw})
                continue
            dt, form = vr.parse_text_date(raw)
            forms[col][form] += 1
            xk, xd = xi.get(ref, {}).get(col, (None, None))
            if dt is not None and form == 'dd/mm/yyyy' and xk == 'true date' and xd is not None and xd != dt:
                # valid dd/mm/yyyy text that disagrees with the typed Excel cell. Resolvable only when the
                # CSV is the same date written month-first (e.g. 09/11/2026 for 11 Sep); any other
                # disagreement is two different dates in the two official files and fails.
                item = {'ref': ref, 'record_no': rn, 'field': col, 'csv_value': raw,
                        'csv_form': 'disagrees with typed XLSX date' + (' (day/month swap)' if vr.swap_dm(dt) == xd else ''),
                        'xlsx_kind': xk, 'xlsx_date': str(xd)}
                if vr.swap_dm(dt) == xd:
                    resolved.append(item)
                    dt = xd
                else:
                    item['csv_form'] = 'different date from typed XLSX date (not a day/month swap)'
                    invalid.append(item)
                    continue
            elif dt is None or form != 'dd/mm/yyyy':
                item = {'ref': ref, 'record_no': rn, 'field': col, 'csv_value': raw, 'csv_form': form,
                        'xlsx_kind': xk, 'xlsx_date': str(xd) if xd else None}
                if xk == 'true date' and xd is not None:
                    # typed Excel date wins (general date rule) only where the CSV text is that same date in
                    # some reading (non-padded, ISO, month-first); unparseable text or another date fails
                    if _csv_text_is_date(raw, dt, xd):
                        resolved.append(item)
                        dt = xd
                    else:
                        item['csv_form'] = f'{form}; not the typed XLSX date in any reading'
                        invalid.append(item)
                        continue
                elif dt is not None and form in ('d/m/yyyy (not zero-padded)', 'iso'):
                    resolved.append(item)          # unambiguous, just not in canonical layout
                else:
                    invalid.append(item)
                if dt is None:
                    continue
            if dt > asof:
                if col in FUTURE_ALLOWED:
                    future_allowed[col] += 1
                else:
                    future.append({'ref': ref, 'field': col, 'value': raw, 'record_last_updated': dct.get(UPDATED, '')})
    G.add('C1_dates_valid', 'content', 'fail' if invalid else ('warn' if resolved else 'pass'),
          f'{len(invalid)} date cells invalid with no typed-Excel fallback; {len(resolved)} non-canonical cells resolvable '
          f'(typed XLSX date or unambiguous form)',
          invalid=invalid, resolvable_non_canonical=resolved, forms={k: dict(v) for k, v in forms.items()})
    G.add('C1b_date_na_markers', 'content', 'warn' if na_cells else 'pass',
          f'{len(na_cells)} date cells hold a text missing-value marker (treated as blank/unknown)',
          cells=na_cells, by_field=dict(collections.Counter(n['field'] for n in na_cells)))
    G.add('C2_future_dates', 'content', 'warn' if future else 'pass',
          f'{len(future)} event dates after as-of {asof} (expiry dates excluded: {dict(future_allowed)})',
          asof=str(asof), future=sorted(future, key=lambda f: _refkey(f['ref'])), expiry_dates_in_future=dict(future_allowed))


def vocab_gates(G, c, base, strict):
    bv = base.get('vocab') or {}
    if not bv:
        G.add('C3_vocabularies_vs_previous', 'content', 'fail' if strict else 'warn',
              'baseline has no vocabularies; status/technology not compared')
        return
    det, new_any = {}, False
    for col in VOCAB_COLUMNS:
        cur = collections.Counter((dct.get(col) or '').strip() for dct in c['dicts'])
        prev = bv.get(col)
        if prev is None:
            det[col] = {'error': 'column missing from baseline'}
            new_any = True
            continue
        new = {k: v for k, v in cur.items() if k not in prev}
        new_refs = {k: sorted({vr.clean_ref(dct.get(REF, '')) for dct in c['dicts'] if (dct.get(col) or '').strip() == k},
                              key=_refkey)[:50] for k in new}
        gone = sorted(k for k in prev if k not in cur)
        det[col] = {'new_values': new, 'new_value_refs': new_refs, 'values_no_longer_present': gone,
                    'counts': dict(sorted(cur.items())), 'previous_counts': prev}
        new_any = new_any or bool(new)
    summ = '; '.join(f'{col}: new {list(det[col].get("new_values", {}))} gone {det[col].get("values_no_longer_present")}'
                     for col in VOCAB_COLUMNS if isinstance(det.get(col), dict))
    G.add('C3_vocabularies_vs_previous', 'content', ('fail' if strict else 'warn') if new_any else 'pass',
          summ, baseline_release=base.get('release_id'), **det)


def coordinate_gates(G, c, known_refs, known_scope='all known refs (legacy file without known_coordinates)'):
    try:
        from pyproj import Transformer
        t_bng = Transformer.from_crs('EPSG:27700', 'EPSG:4326', always_xy=True)
        t_ig = Transformer.from_crs('EPSG:29903', 'EPSG:4326', always_xy=True)
    except Exception:  # pyproj optional: box tests are then skipped, numeric/bounds tests still run
        t_bng = t_ig = None
    anomalies, nonnum, hard_out, blank_both, blank_one = [], [], [], [], []
    xy = {}
    rows = {}

    def add(dct, code, detail):
        ref = vr.clean_ref(dct.get(REF, ''))
        anomalies.append({'anomaly': code, 'ref': ref, 'site_name': dct.get('Site Name', ''),
                          'technology': dct.get('Technology Type', ''), 'country': dct.get('Country', ''),
                          'region': dct.get('Region', ''), 'x_raw': dct.get('X-coordinate', ''),
                          'y_raw': dct.get('Y-coordinate', ''), 'detail': detail, 'known': ref in known_refs})

    for dct in c['dicts']:
        ref = vr.clean_ref(dct.get(REF, ''))
        if ref in rows:
            continue  # identical duplicates are checked once
        rows[ref] = dct
        xr, yr = dct.get('X-coordinate', '') or '', dct.get('Y-coordinate', '') or ''
        fl = sorted(set(cell_flags(xr) + cell_flags(yr)))
        if fl:
            add(dct, 'HIDDEN_CHARS', '+'.join(fl))
        country, region, tech = (dct.get('Country') or '').strip(), (dct.get('Region') or '').strip(), (dct.get('Technology Type') or '').strip()
        if not country or not region:
            add(dct, 'COUNTRY_OR_REGION_BLANK', f'country={country!r} region={region!r}')
        elif region != 'Offshore' and REGION_COUNTRY.get(region) != country:
            add(dct, 'COUNTRY_REGION_LABEL_MISMATCH', f'country={country} region={region}')
        x, sx = parse_coord(xr)
        y, sy = parse_coord(yr)
        if sx == 'BLANK' and sy == 'BLANK':
            blank_both.append(ref)
            continue