GLOBALGRID2050 / EXPLORE CODE

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

Renewable Energy Planning Database (REPD) Verify Release and 1 more file

A Python command-line tool in the automation folder of GlobalGrid2050 that reads the REPD register and solar, using SHA-256.

700 lines of Python from globalgrid2050, in 2 files. Topic: Electricity markets and data pipelines. Section 837 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. Renewable Energy Planning Database (REPD) Validate geodesy · globalgrid2050 / automation/repd/validate.py lines 451–711
  2. Renewable Energy Planning Database (REPD) Verify Release automation · globalgrid2050 / automation/repd/verify_release.py lines 1–439

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 451–711 of 711 (continued from section 836) · 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
anomaly_gate, load_known_coordinates, load_known, run_check, _print, 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/validate.py:451-711 · 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
        if 'BLANK' in (sx, sy) and 'NON_NUMERIC' not in (sx, sy):
            blank_one.append(ref)
            continue
        if 'NON_NUMERIC' in (sx, sy):
            nonnum.append({'ref': ref, 'x': xr, 'y': yr})
            continue
        if not (HARD_E[0] <= x <= HARD_E[1] and HARD_N[0] <= y <= HARD_N[1]) or (abs(x) < 1000 and abs(y) < 1000):
            hard_out.append({'ref': ref, 'x': x, 'y': y, 'known': ref in known_refs})
            add(dct, 'OUTSIDE_HARD_BOUNDS', f'E {x} N {y} outside E {HARD_E} N {HARD_N} (or both < 1000: degrees?)')
            continue
        xy[ref] = (x, y)
        if x == 0 or y == 0:
            add(dct, 'ZERO_VALUE', '')
        if not (BNG_E[0] <= x <= BNG_E[1] and BNG_N[0] <= y <= BNG_N[1]):
            add(dct, 'OUTSIDE_BNG_ENVELOPE', f'E range {BNG_E}, N range {BNG_N} (offshore arrays may exceed)')
        if t_bng is None:
            continue
        lon, lat = t_bng.transform(x, y)
        offshore = tech in OFFSHORE_TECH or region == 'Offshore'
        pad = PAD_OFF if offshore else PAD_ON
        if country == 'Northern Ireland':
            nb = COUNTRY_BOX['Northern Ireland']
            if not inbox(lat, lon, nb, pad):
                lon_ig, lat_ig = t_ig.transform(x, y)
                add(dct, 'NI_IRISH_GRID_NOT_BNG' if inbox(lat_ig, lon_ig, nb, pad) else 'OUTSIDE_COUNTRY_BOX',
                    f'BNG lat/lon {lat:.4f},{lon:.4f}')
            continue
        cb = COUNTRY_BOX.get(country)
        if cb is not None and not inbox(lat, lon, cb, pad):
            add(dct, 'OUTSIDE_COUNTRY_BOX', f'BNG lat/lon {lat:.4f},{lon:.4f}; offshore={offshore}')
        rb = REGION_BOX.get(region)
        if rb is not None and not inbox(lat, lon, rb, pad):
            add(dct, 'OUTSIDE_REGION_BOX', f'BNG lat/lon {lat:.4f},{lon:.4f}; offshore={offshore}')

    # neighbour test (coord_audit): onshore point whose nearest same-region record is > 25 km away and whose
    # 10 nearest records are all in other regions
    try:
        import numpy as np
        on = [k for k in xy if (rows[k].get('Region') or '').strip() in REGION_BOX
              and (rows[k].get('Technology Type') or '').strip() not in OFFSHORE_TECH]
        if len(on) > 10:
            P = np.array([xy[k] for k in on])
            reg = np.array([(rows[k].get('Region') or '').strip() for k in on])
            for i in range(0, len(on), 500):
                D = np.hypot(P[i:i + 500, None, 0] - P[None, :, 0], P[i:i + 500, None, 1] - P[None, :, 1])
                for j in range(D.shape[0]):
                    dd = D[j]
                    same = (reg == reg[i + j]) & (dd > 0)
                    dsame = dd[same].min() if same.any() else float('inf')
                    order = np.argsort(dd)
                    k10 = order[dd[order] > 0][:10]
                    if dsame > ISO_KM * 1000 and float((reg[k10] == reg[i + j]).mean()) == 0.0:
                        near = collections.Counter(reg[k10]).most_common(1)[0][0]
                        add(rows[on[i + j]], 'ISOLATED_FROM_STATED_REGION',
                            f'nearest other {reg[i + j]} record {dsame / 1000:.1f} km away; 10 nearest mostly {near}')
    except ImportError:
        pass

    unknown_hard = [h for h in hard_out if not h['known']]
    G.add('C4_coordinates_numeric_and_in_bounds', 'content',
          'fail' if (nonnum or unknown_hard) else ('warn' if hard_out else 'pass'),
          f'{len(xy)} numeric pairs in bounds; non-numeric {len(nonnum)}; outside hard bounds {len(hard_out)} '
          f'({len(unknown_hard)} not on known list); blank both {len(blank_both)}; one blank {len(blank_one)}',
          hard_bounds={'E': HARD_E, 'N': HARD_N}, non_numeric=nonnum, outside_hard_bounds=hard_out,
          blank_both=sorted(blank_both, key=_refkey), blank_one=sorted(blank_one, key=_refkey),
          pyproj_box_tests=t_bng is not None, known_scope=known_scope)
    return anomalies


def anomaly_gate(G, c, x, rep, coord_anoms, known):
    """C5: known-anomaly report. Never fails; lists what is found, which known items are still present,
    which known items are gone, and which anomalies are not on the known list."""
    d = rep.data
    found = list(coord_anoms)
    for dup_ in (d.get('csv.duplicate_refs') or {}).get('detail', []):
        found.append({'anomaly': 'DUPLICATE_REF_' + dup_['kind'].upper(), 'ref': dup_['ref'],
                      'detail': f'{dup_["occurrences"]} occurrences', 'known': dup_['ref'] in known})
    for g in G.items:
        if g['id'] == 'C1_dates_valid':
            for it in g['detail']['resolvable_non_canonical']:
                found.append({'anomaly': 'CSV_DATE_NON_CANONICAL', 'ref': it['ref'],
                              'detail': f'{it["field"]}: CSV {it["csv_value"]!r} ({it["csv_form"]}) XLSX {it["xlsx_date"]}',
                              'known': it['ref'] in known})
        if g['id'] == 'C1b_date_na_markers':
            for it in g['detail']['cells']:
                found.append({'anomaly': 'DATE_TEXT_NA', 'ref': it['ref'], 'detail': it['field'], 'known': it['ref'] in known})
    if x is not None:
        for dd in d.get('compare.date_disagreements.detail', []):
            if (dd['csv_raw'] or '').strip().upper() in NA_MARKERS:
                continue  # reported as DATE_TEXT_NA
            found.append({'anomaly': 'CSV_XLSX_DATE_DISAGREEMENT', 'ref': dd['ref'],
                          'detail': f'{dd["field"]}: CSV {dd["csv_raw"]!r} vs XLSX {dd["xlsx_raw"]!r} ({dd["kind"]})',
                          'known': dd['ref'] in known})
        # XLSX numbers stored with a date format in a non-date column (e.g. "Offshore Wind Round")
        date_fmt_cols = collections.Counter()
        for dct in x['dicts']:
            for col, cell in dct.items():
                if col in DATE_COLUMNS or cell is None:
                    continue
                if isinstance(cell[0], (datetime.datetime, datetime.date)):
                    date_fmt_cols[col] += 1
        for col, n in date_fmt_cols.items():
            found.append({'anomaly': 'XLSX_DATE_TYPED_CELLS_IN_NON_DATE_COLUMN', 'ref': '', 'detail': f'{col}: {n} cells',
                          'known': ('column:' + col) in known})
    kinds = {k.split(':', 1)[1] for k in known if k.startswith('kind:')}
    for a in found:
        if a['anomaly'] in kinds:
            a['known'] = True
    present = {a['ref'] for a in found if a['ref']}
    present_cols = {'column:' + a['detail'].split(':')[0] for a in found if a['anomaly'] == 'XLSX_DATE_TYPED_CELLS_IN_NON_DATE_COLUMN'}
    present_kinds = {'kind:' + a['anomaly'] for a in found}
    known_missing = sorted([k for k in known if k not in present and k not in present_cols and k not in present_kinds
                            and not (k.startswith('column:') and x is None)], key=_refkey)
    unknown = [a for a in found if not a['known']]
    G.add('C5_known_anomaly_report', 'content', 'warn' if (unknown or known_missing) else 'pass',
          f'{len(found)} anomalies ({len(found) - len(unknown)} on known list, {len(unknown)} not); '
          f'{len(known_missing)} known items no longer present',
          counts=dict(collections.Counter(a['anomaly'] for a in found)), known_items_no_longer_present=known_missing,
          known_list=known, anomalies=found)


def load_known_coordinates(path):
    """Refs whose coordinates are known to be wrong or legitimately outside the boxes ("known_coordinates"
    in the known-anomalies file). None when the file has no such key: C4 then falls back to the whole
    known list (legacy behaviour, reported as such in the gate detail)."""
    if not path:
        return None
    k = json.load(open(path, encoding='utf-8'))
    if not isinstance(k, dict) or 'known_coordinates' not in k:
        return None
    items = k['known_coordinates']
    return {str(a): b for a, b in items.items()} if isinstance(items, dict) else {str(i): '' for i in items}


def load_known(path):
    if not path:
        return {}
    k = json.load(open(path, encoding='utf-8'))
    items = k.get('known', k) if isinstance(k, dict) else k
    if isinstance(items, dict):
        return {str(a): b for a, b in items.items()}
    return {str(i['ref']): i.get('note', '') for i in items}


# =================================================================== driver
def run_check(csv_path, xlsx_path=None, baseline=None, known=None, asof=None, csv_only=False, strict_vocab=False,
              expectations=None, sheet=None, max_examples=10, known_coordinates=None):
    """Run every gate; returns (report_dict, verify_release_data). Raises OSError/ValueError on unusable input."""
    asof = asof or datetime.date.today()
    known = known or {}
    rep = vr.Report(max_examples)
    c = vr.check_csv(csv_path, asof, rep)
    if c is None:
        raise ValueError(f'{csv_path}: no CSV records ({rep.structural})')
    x = vr.check_xlsx(xlsx_path, sheet, rep) if xlsx_path else None
    if xlsx_path and x is None:
        raise ValueError(f'{xlsx_path}: XLSX could not be read ({rep.structural})')
    if x is not None:
        vr.compare(c, x, asof, rep)
    if expectations:
        vr.check_expectations(expectations, rep)
    G = Gates()
    source_gates(G, rep, c, x, baseline, csv_only)
    date_gates(G, c, x, asof)
    vocab_gates(G, c, baseline, strict_vocab)
    if known_coordinates is None:
        coord_anoms = coordinate_gates(G, c, known)
    else:
        # a ref on the known list for another reason (a date, a duplicate) must not waive a coordinate failure
        coord_anoms = coordinate_gates(G, c, known_coordinates, 'known_coordinates only')
        for a in coord_anoms:
            a['known'] = a['known'] or (a['anomaly'] not in ('OUTSIDE_HARD_BOUNDS',) and a['ref'] in known)
    anomaly_gate(G, c, x, rep, coord_anoms, known)
    failed = G.failed()
    report = {
        'schema': SCHEMA, 'tool': 'automation/repd/validate.py', 'asof': str(asof),
        'generated_at': datetime.datetime.now(datetime.timezone.utc).isoformat(timespec='seconds'),
        'inputs': {'csv': {'path': csv_path, 'bytes': rep.data.get('csv.bytes'), 'sha256': rep.data.get('csv.sha256'),
                           'encoding': rep.data.get('csv.encoding')},
                   'xlsx': None if x is None else {'path': xlsx_path, 'bytes': rep.data.get('xlsx.bytes'),
                                                   'sha256': rep.data.get('xlsx.sha256'), 'sheet': rep.data.get('xlsx.sheet_used')},
                   'csv_only': csv_only, 'baseline_release': baseline.get('release_id'),
                   'baseline_source': baseline.get('source')},
        'summary': {s: sum(1 for g in G.items if g['status'] == s) for s in ('pass', 'warn', 'fail', 'skip')},
        'result': 'FAIL' if failed else 'PASS', 'exit_code': 1 if failed else 0,
        'failed_gates': [g['id'] for g in failed], 'gates': G.items,
    }
    return report, rep.data


def _print(report):
    for g in report['gates']:
        print(f'{g["status"].upper():5} {g["id"]}: {g["summary"]}')
    print(f'RESULT {report["result"]} (exit {report["exit_code"]}) {report["summary"]}')


def main(argv=None):
    ap = argparse.ArgumentParser(description=__doc__.split('\n')[0])
    sub = ap.add_subparsers(dest='cmd', required=True)
    ck = sub.add_parser('check')
    ck.add_argument('--csv', required=True)
    ck.add_argument('--xlsx')
    ck.add_argument('--sheet')
    ck.add_argument('--csv-only', action='store_true', help='cleaned candidate: skip CSV-vs-XLSX gates explicitly')
    ck.add_argument('--baseline', required=True, help='previous-release baseline JSON (make-baseline output, or repd_source_reconciliation_v6.json)')
    ck.add_argument('--known-anomalies')
    ck.add_argument('--asof', help='YYYY-MM-DD (default today, UTC)')
    ck.add_argument('--json')
    ck.add_argument('--verify-json', help='also write the full verify_release data (large)')
    ck.add_argument('--strict-vocab', action='store_true', help='new status/technology values fail instead of warn')
    ck.add_argument('--expect-rows', type=int)
    ck.add_argument('--expect-unique-refs', type=int)
    ck.add_argument('--expect-csv-sha256')
    ck.add_argument('--expect-xlsx-sha256')
    ck.add_argument('--quiet', action='store_true')
    mb = sub.add_parser('make-baseline')
    g = mb.add_mutually_exclusive_group(required=True)
    g.add_argument('--from-csv')
    g.add_argument('--from-identity-v6')
    mb.add_argument('--release-id', required=True)
    mb.add_argument('--out', required=True)
    try:
        a = ap.parse_args(argv)
    except SystemExit as e:
        return 2 if e.code else 0
    try:
        if a.cmd == 'make-baseline':
            b = baseline_from_csv(a.from_csv, a.release_id) if a.from_csv else baseline_from_identity_v6(a.from_identity_v6, a.release_id)
            with open(a.out, 'w', encoding='utf-8') as f:
                json.dump(b, f, indent=1, ensure_ascii=False)
                f.write('\n')
            print(f'baseline {a.release_id}: rows={b["rows"]} unique_refs={b["unique_refs"]} -> {a.out}')
            return 0
        if not a.xlsx and not a.csv_only:
            print('ERROR: give --xlsx, or --csv-only to skip the CSV-vs-XLSX gates explicitly', file=sys.stderr)
            return 2
        baseline = load_baseline(a.baseline)
        known = load_known(a.known_anomalies)
        known_coordinates = load_known_coordinates(a.known_anomalies)
        asof = datetime.date.fromisoformat(a.asof) if a.asof else datetime.datetime.now(datetime.timezone.utc).date()
        exp = {k: v for k, v in (('rows', a.expect_rows), ('unique_refs', a.expect_unique_refs),
                                 ('csv_sha256', a.expect_csv_sha256), ('xlsx_sha256', a.expect_xlsx_sha256)) if v is not None}
        report, vdata = run_check(a.csv, a.xlsx, baseline, known, asof, a.csv_only, a.strict_vocab, exp or None, a.sheet,
                                  known_coordinates=known_coordinates)
    except (OSError, ValueError, KeyError, json.JSONDecodeError) as e:
        print(f'ERROR: cannot run validation: {e}', file=sys.stderr)
        return 2
    if not a.quiet:
        _print(report)
    if a.json:
        with open(a.json, 'w', encoding='utf-8') as f:
            json.dump(report, f, indent=1, default=str, ensure_ascii=False)
            f.write('\n')
    if a.verify_json:
        with open(a.verify_json, 'w', encoding='utf-8') as f:
            json.dump(vdata, f, indent=1, default=str, ensure_ascii=False)
    return report['exit_code']


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

Renewable Energy Planning Database (REPD) Verify Release

A Python command-line tool in the automation folder of GlobalGrid2050 that reads the REPD register and solar, using SHA-256.

automationglobalgrid2050 / automation/repd/verify_release.py · lines 1–439 of 541 · Entry point · pattern norm_text (shared by 3 files)

What it does
It loads the REPD register and solar. Defines 27 functions or classes, including nh, parse_text_date, swap_dm, excel_serial_to_date, sha256. Uses libraries argparse, collections, csv, datetime, hashlib. 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, solar.
Inputs & outputs
In: command-line arguments. Out: JSON file.
Downstream impact
Used directly by 2 files: Test Validate (globalgrid2050); Renewable Energy Planning Database (REPD) Validate (globalgrid2050). Reached from 2 other entry points, including GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050); Test Hardening Nl013 (globalgrid2050).
What it achieves
It parses text date (`parse_text_date`), cleans ref (`clean_ref`) and checks CSV (`check_csv`). Independent integrity check of a raw official REPD release. It accepts `--xlsx`, `--sheet` and `--asof`.
Why it matters
Imported by Renewable Energy Planning Database (REPD) Validate. Checked by Test Validate.
Application
globalgrid2050 · automation/repd · Python CLI
Uses
argparse, collections, csv, datetime, hashlib, io, json, re
Used by
imported by Test Validate (sys.path import), imported by Renewable Energy Planning Database (REPD) Validate (relative import)
Produces
nh, parse_text_date, swap_dm, excel_serial_to_date, sha256, norm_text, as_number, clean_ref, Report, check_csv, idx, header_report
Defines here
nh, parse_text_date, swap_dm, excel_serial_to_date, sha256, norm_text, as_number, clean_ref, Report, __init__, section, put, note, error, check_csv, idx, header_report, refs_report, check_xlsx, render, classify_xlsx_date, plausible, compare, occ
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/verify_release.py:1-439 · blob 6db4c3f0787336562b723b1b959fd2b2092f9269 · 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
"""verify_release.py - independent integrity check of a raw official REPD release.

Usage
  python3 -I verify_release.py REPD.csv [--xlsx REPD.xlsx] [--asof YYYY-MM-DD]
                               [--expect-october-2026] [--json report.json] [--max-examples N]
  (individual expectations: --expect-csv-bytes, --expect-csv-sha256, --expect-xlsx-bytes,
   --expect-xlsx-sha256, --expect-rows, --expect-unique-refs, --expect-duplicate-refs 7679,
   --expect-date-conflicts "Planning Application Submitted=21424,21438")

What it reports
  CSV : bytes, sha256, encoding, line endings, physical lines vs records, field-count histogram,
        header vs the 53 official columns in order, unique / duplicate refs (identical or conflicting),
        last-record completeness + trailing newline, unparseable and future dates per date column.
  XLSX: bytes, sha256, sheet, header, rows, refs, duplicates, cell typing of every date column.
  Both: ref-set equality and every field-level disagreement on the date columns, with both raw values,
        whether the Excel cell is a true date or a string, whether a day/month swap of one equals the
        other, and which value is plausible given "Record Last Updated" and --asof.
        Non-date columns get a per-column disagreement count with a coarse classification.

Nothing is assumed: expectations are only compared, never used to steer parsing. The script reads
its inputs and writes nothing except the optional --json file. Exit status: 0 = no expectation failed
and no structural error; 1 = an expectation failed; 2 = structural error (truncation, ragged rows,
header mismatch, ref sets differ).
"""
import argparse, collections, csv, datetime, hashlib, io, json, re, sys

EXPECTED_COLUMNS = [
    '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)',
]  # verbatim (including the trailing space and the double space) from the January 2026 raw CSV header
assert len(EXPECTED_COLUMNS) == 53

def nh(s):
    """normalised header: trim + collapse internal whitespace"""
    return ' '.join(str(s if s is not None else '').replace('', '').split())

NORM_EXPECTED = [nh(c) for c in EXPECTED_COLUMNS]
REF, UPDATED = 'Ref ID', 'Record Last Updated (dd/mm/yyyy)'
DATE_COLUMNS = [UPDATED] + NORM_EXPECTED[37:51]
FUTURE_ALLOWED = {'Planning Permission Expired'}  # an expiry date is legitimately in the future
NUMERIC_COLUMNS = {'Installed Capacity (MWelec)', 'CfD Capacity (MW)', 'Turbine Capacity (MW)', 'No. of Turbines',
                   'Height of Turbines (m)', 'X-coordinate', 'Y-coordinate', 'Solar Site Area (sqm)',
                   'RO Banding (ROC/MWh)', 'FiT Tariff (p/kWh)'}

OCTOBER_2026 = dict(csv_bytes=5219160, csv_sha256='48e76c49f33a1090e78108d1ea9bfe689b35963ea3be1bb4f6516d038a5ff862',
                    xlsx_bytes=5378656, xlsx_sha256='87811e249395a05b223db6855952334f425e66cc9a2106caea0e38fd9e5037ea',
                    rows=14968, unique_refs=14967, duplicate_refs=['7679'],
                    date_conflicts={'Planning Application Submitted': ['21424', '21438', '21456', '21463', '21464']})

# ------------------------------------------------------------------ dates
DMY = re.compile(r'^(\d{1,2})/(\d{1,2})/(\d{4})$')
DMY2 = re.compile(r'^(\d{1,2})/(\d{1,2})/(\d{2})$')
ISO = re.compile(r'^(\d{4})-(\d{2})-(\d{2})(?:[T ]00:00(?::00(?:\.0+)?)?)?$')
DMY_DASH = re.compile(r'^(\d{1,2})[-.](\d{1,2})[-.](\d{4})$')

def parse_text_date(s):
    """-> (date|None, form). The official layout is dd/mm/yyyy; anything else is reported by form."""
    s = (s or '').strip()
    if not s:
        return None, 'blank'
    for rx, form in ((DMY, 'dd/mm/yyyy'), (ISO, 'iso'), (DMY_DASH, 'dd-mm-yyyy'), (DMY2, 'dd/mm/yy')):
        m = rx.match(s)
        if not m:
            continue
        a, b, c = (int(x) for x in m.groups()[:3])
        try:
            if form == 'iso':
                return datetime.date(a, b, c), form
            if form == 'dd/mm/yy':
                return datetime.date(2000 + c if c < 70 else 1900 + c, b, a), form
            if form == 'dd/mm/yyyy' and (len(m.group(1)) != 2 or len(m.group(2)) != 2):
                form = 'd/m/yyyy (not zero-padded)'
            return datetime.date(c, b, a), form
        except ValueError:
            return None, 'impossible ' + form
    return None, 'unparseable'

def swap_dm(d):
    """date with day and month exchanged, or None when that is not a valid date"""
    if d is None:
        return None
    try:
        return datetime.date(d.year, d.day, d.month)
    except ValueError:
        return None

def excel_serial_to_date(v):
    try:
        return (datetime.datetime(1899, 12, 30) + datetime.timedelta(days=float(v))).date()
    except (OverflowError, ValueError, TypeError):
        return None

# ------------------------------------------------------------------ helpers
def sha256(b):
    return hashlib.sha256(b).hexdigest()

def norm_text(v):
    return ' '.join(str(v if v is not None else '').replace('_x000D_', ' ').replace('\xa0', ' ').split())

def as_number(v):
    s = norm_text(v).replace(',', '')
    if re.fullmatch(r'-?\d+(\.\d+)?([eE]-?\d+)?', s):
        try:
            return float(s)
        except ValueError:
            return None
    return None

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

class Report:
    def __init__(self, max_examples):
        self.data = collections.OrderedDict(); self.lines = []; self.structural = []; self.n = max_examples
    def section(self, title):
        self.lines.append(''); self.lines.append('=' * 6 + ' ' + title + ' ' + '=' * 6)
    def put(self, key, value, show=True):
        self.data[key] = value
        if show:
            v = value if isinstance(value, str) else json.dumps(value, default=str, ensure_ascii=False)
            self.lines.append(f'{key}: {v}')
    def note(self, text):
        self.lines.append(text)
    def error(self, text):
        self.structural.append(text); self.lines.append('STRUCTURAL: ' + text)

# ------------------------------------------------------------------ CSV
def check_csv(path, asof, rep):
    raw = open(path, 'rb').read()
    rep.section('CSV file')
    rep.put('csv.path', path); rep.put('csv.bytes', len(raw)); rep.put('csv.sha256', sha256(raw))
    bom = raw.startswith(b'\xef\xbb\xbf')
    non_ascii = sum(1 for b in raw if b > 127)
    try:
        text = raw.decode('utf-8-sig'); enc = 'utf-8-sig (BOM present)' if bom else ('ascii' if non_ascii == 0 else 'utf-8')
    except UnicodeDecodeError as e:
        undefined = {hex(x): raw.count(bytes([x])) for x in (0x81, 0x8d, 0x8f, 0x90, 0x9d) if raw.count(bytes([x]))}
        if undefined:
            text = raw.decode('latin-1'); enc = 'latin-1 (not UTF-8; contains bytes undefined in cp1252: %s)' % undefined
        else:
            text = raw.decode('cp1252'); enc = 'cp1252 (not valid UTF-8: first bad byte 0x%02x at offset %d)' % (raw[e.start], e.start)
    rep.put('csv.encoding', enc); rep.put('csv.non_ascii_bytes', non_ascii)
    rep.put('csv.nbsp_chars', text.count('\xa0')); rep.put('csv.c1_control_chars', sum(1 for ch in text if 0x80 <= ord(ch) <= 0x9f))
    rep.put('csv.mojibake_markers', {m: text.count(m) for m in ('Ã', 'Â\xa0', 'â€', '�', '_x000D_') if text.count(m)})
    crlf = raw.count(b'\r\n'); lf = raw.count(b'\n') - crlf; cr = raw.count(b'\r') - crlf
    rep.put('csv.line_endings', {'CRLF': crlf, 'bare_LF': lf, 'bare_CR': cr})
    rep.put('csv.ends_with_newline', raw.endswith(b'\n')); rep.put('csv.last_bytes', repr(raw[-40:]))
    rep.put('csv.nul_bytes', raw.count(b'\x00'))
    # parse (strict: an unterminated quoted field at end of file raises instead of being swallowed)
    records, linenos, parse_error = [], [], None
    reader = csv.reader(io.StringIO(text, newline=''), strict=True)
    try:
        for row in reader:
            records.append(row); linenos.append(reader.line_num)
    except csv.Error as e:
        parse_error = f'{e} near physical line {reader.line_num}'
        rep.error('CSV parse error (possible truncation inside a quoted field): ' + parse_error)
    rep.put('csv.parse_error', parse_error)
    if not records:
        rep.error('CSV has no records'); return None
    header = records[0]; body = records[1:]; body_lines = linenos[1:]
    rep.put('csv.physical_lines', raw.count(b'\n') + (0 if raw.endswith(b'\n') or not raw else 1))
    rep.put('csv.records_including_blank', len(body))
    blank = [i for i, r in enumerate(body) if not any(c.strip() for c in r)]
    rep.put('csv.blank_records', len(blank))
    keep = [i for i in range(len(body)) if i not in set(blank)]
    rows = [body[i] for i in keep]; rownum = [i + 2 for i in keep]; rowline = [body_lines[i] for i in keep]
    rep.put('csv.rows', len(rows))
    rep.note('  (a "row" is a parsed CSV record; quoted fields may span several physical lines, so line counts are not row counts)')
    rep.put('csv.records_with_embedded_newlines', sum(1 for r in rows if any('\n' in c or '\r' in c for c in r)))
    hist = collections.Counter(len(r) for r in rows)
    rep.put('csv.field_count_histogram', dict(sorted(hist.items())))
    ragged = [(rownum[i], rowline[i], len(r)) for i, r in enumerate(rows) if len(r) != len(header)]
    if ragged:
        rep.error(f'{len(ragged)} CSV records do not have {len(header)} fields; first (record_no, line, fields): {ragged[:rep.n]}')
    header_report(header, 'csv', rep)
    last = rows[-1] if rows else []
    complete = bool(rows) and len(last) == len(header) and raw.endswith(b'\n') and parse_error is None
    rep.put('csv.last_record', {'record_no': rownum[-1] if rows else None, 'fields': len(last), 'ref': last[idx(header, REF)] if rows and idx(header, REF) is not None and len(last) > idx(header, REF) else None,
                                'complete_field_count': len(last) == len(header), 'file_ends_with_newline': raw.endswith(b'\n'), 'verdict': 'complete' if complete else 'SUSPECT'})
    if not complete:
        rep.error('last CSV record is incomplete or the file does not end with a newline')
    hn = [nh(h) for h in header]
    dicts = [dict(zip(hn, r)) for r in rows]
    refs_report([d.get(REF, '') for d in dicts], dicts, rownum, 'csv', rep, hn, lambda v: v)
    formula = sum(1 for r in rows for c in r if c[:1] in ('=', '@') or (c[:1] in ('+', '-') and as_number(c) is None and len(c) > 1 and not c[1:2].isdigit()))
    rep.put('csv.formula_leading_cells', formula)
    # dates
    rep.section('CSV date columns (official layout dd/mm/yyyy; as-of %s)' % asof)
    out = collections.OrderedDict()
    for col in DATE_COLUMNS:
        if col not in hn:
            out[col] = 'COLUMN MISSING'; continue
        forms = collections.Counter(); bad = []; fut = []; pre = 0; after_upd = 0; nonblank = 0; mn = mx = None
        for d, rn in zip(dicts, rownum):
            v = d.get(col, '') or ''
            dt, form = parse_text_date(v)
            if form == 'blank':
                continue
            nonblank += 1; forms[form] += 1
            if dt is None:
                if len(bad) < rep.n: bad.append({'ref': d.get(REF), 'record_no': rn, 'value': v})
                continue
            mn = dt if mn is None or dt < mn else mn; mx = dt if mx is None or dt > mx else mx
            if dt > asof:
                fut.append({'ref': d.get(REF), 'record_no': rn, 'value': v})
            if dt.year < 1990: pre += 1
            if col != UPDATED:
                u, _ = parse_text_date(d.get(UPDATED, ''))
                if u and dt > u: after_upd += 1
        out[col] = {'nonblank': nonblank, 'forms': dict(forms), 'unparseable': sum(v for k, v in forms.items() if k in ('unparseable',) or k.startswith('impossible')),
                    'unparseable_examples': bad, 'min': str(mn), 'max': str(mx), 'future_after_asof': len(fut), 'future_examples': fut[:rep.n],
                    'future_is_expected_for_this_column': col in FUTURE_ALLOWED, 'before_1990': pre,
                    'later_than_record_last_updated': after_upd if col != UPDATED else None}
        rep.put('csv.dates.' + col, out[col])
    ups = [parse_text_date(d.get(UPDATED, ''))[0] for d in dicts]
    ups = [u for u in ups if u is not None and u <= asof]
    file_max_updated = max(ups) if ups else None
    rep.put('csv.max_record_last_updated_not_after_asof', str(file_max_updated))
    base = {col: {'nonblank': out[col]['nonblank'], 'later_than_record_last_updated': out[col]['later_than_record_last_updated']}
            for col in DATE_COLUMNS if isinstance(out.get(col), dict) and col != UPDATED}
    return {'raw': raw, 'header': header, 'hn': hn, 'dicts': dicts, 'rownum': rownum, 'file_max_updated': file_max_updated, 'base': base}

def idx(header, name):
    hn = [nh(h) for h in header]
    return hn.index(name) if name in hn else None

def header_report(header, tag, rep):
    hs = ['' if h is None else str(h) for h in header]
    exact = hs == EXPECTED_COLUMNS
    hn = [nh(h) for h in hs]
    normeq = hn == NORM_EXPECTED
    rep.put(f'{tag}.columns', len(hs))
    rep.put(f'{tag}.header_exact_match_53_in_order', exact)
    rep.put(f'{tag}.header_match_after_whitespace_normalisation', normeq)
    if not exact:
        rep.put(f'{tag}.header_whitespace_or_text_differences', [{'position': i + 1, 'found': a, 'expected': b} for i, (a, b) in enumerate(zip(hs, EXPECTED_COLUMNS)) if a != b][:60])
    if not normeq:
        rep.put(f'{tag}.header_missing', [c for c in NORM_EXPECTED if c not in hn])
        rep.put(f'{tag}.header_unexpected', [c for c in hn if c not in NORM_EXPECTED])
        common = [c for c in hn if c in NORM_EXPECTED]
        rep.put(f'{tag}.header_common_columns_in_expected_order', common == [c for c in NORM_EXPECTED if c in hn])
        rep.error(f'{tag} header does not match the 53 official columns in order (after whitespace normalisation)')
    dup = [c for c, n in collections.Counter(hn).items() if n > 1]
    if dup:
        rep.error(f'{tag} header has duplicated column names: {dup}')

def refs_report(refs, dicts, rownum, tag, rep, hn, render):
    refs = [clean_ref(r) for r in refs]
    rep.put(f'{tag}.unique_refs', len(set(refs)))
    rep.put(f'{tag}.blank_refs', sum(1 for r in refs if not r))
    nonnum = [r for r in refs if r and not r.isdigit()]
    rep.put(f'{tag}.non_numeric_refs', {'count': len(nonnum), 'examples': nonnum[:rep.n]})
    nums = [int(r) for r in refs if r.isdigit()]
    rep.put(f'{tag}.ref_min_max', [min(nums), max(nums)] if nums else None)
    pos = collections.defaultdict(list)
    for i, r in enumerate(refs): pos[r].append(i)
    dups = []
    for r, ii in pos.items():
        if len(ii) < 2 or not r: continue
        diff = sorted({c for i in ii[1:] for c in hn if render(dicts[i].get(c)) != render(dicts[ii[0]].get(c))}, key=hn.index)
        dups.append({'ref': r, 'occurrences': len(ii), 'record_nos': [rownum[i] for i in ii], 'kind': 'identical' if not diff else 'CONFLICTING',
                     'differing_fields': {c: [str(render(dicts[i].get(c))) for i in ii] for c in diff[:12]}})
    dups.sort(key=lambda d: (not d['ref'].isdigit(), int(d['ref']) if d['ref'].isdigit() else 0))
    rep.put(f'{tag}.duplicate_refs', {'refs': len(dups), 'surplus_rows': sum(d['occurrences'] - 1 for d in dups),
                                      'identical': sum(1 for d in dups if d['kind'] == 'identical'), 'conflicting': sum(1 for d in dups if d['kind'] != 'identical'),
                                      'detail': dups[:max(rep.n, 20)]})
    return refs

# ------------------------------------------------------------------ XLSX
def check_xlsx(path, sheet, rep):
    try:
        import openpyxl
    except ImportError:
        rep.error('openpyxl is not installed; the XLSX cannot be checked (pip install "openpyxl>=3.1,<4")'); return None
    raw = open(path, 'rb').read()
    rep.section('XLSX file')
    rep.put('xlsx.path', path); rep.put('xlsx.bytes', len(raw)); rep.put('xlsx.sha256', sha256(raw))
    rep.put('xlsx.is_zip_container', raw[:2] == b'PK')
    wb = openpyxl.load_workbook(io.BytesIO(raw), read_only=True, data_only=True)
    rep.put('xlsx.sheets', wb.sheetnames); rep.put('xlsx.date_system_1904', bool(wb.epoch == openpyxl.utils.datetime.CALENDAR_MAC_1904))
    found = None
    for name in ([sheet] if sheet else wb.sheetnames):
        if name not in wb.sheetnames:
            rep.error(f'sheet {name!r} not found'); return None
        ws = wb[name]
        for r_i, row in enumerate(ws.iter_rows(min_row=1, max_row=25), 1):
            if REF in [nh(c.value) for c in row]:
                found = (name, r_i); break
        if found: break
    if not found:
        rep.error('no sheet with a header row containing "Ref ID" in its first 25 rows'); return None
    name, hrow = found; ws = wb[name]
    rep.put('xlsx.sheet_used', name); rep.put('xlsx.header_row', hrow)
    header = None; rows = []; rownum = []
    for r_i, row in enumerate(ws.iter_rows(min_row=hrow), hrow):
        if header is None:
            header = [c.value for c in row]
            while header and header[-1] is None: header.pop()
            continue
        cells = list(row[:len(header)])
        if not any(c.value is not None and str(c.value).strip() != '' for c in cells):
            continue
        rows.append([(c.value, getattr(c, 'is_date', False), getattr(c, 'number_format', None), getattr(c, 'data_type', None)) for c in cells] + [(None, False, None, None)] * (len(header) - len(cells)))
        rownum.append(r_i)
    header_report(header, 'xlsx', rep)
    hn = [nh(h) for h in header]
    rep.put('xlsx.rows', len(rows))
    dicts = [dict(zip(hn, r)) for r in rows]
    def render(c):
        if c is None: return ''
        v = c[0]
        if isinstance(v, (datetime.datetime, datetime.date)): return v.isoformat()
        return '' if v is None else str(v)
    refs_report([d[REF][0] if REF in d else '' for d in dicts], dicts, rownum, 'xlsx', rep, hn, render)
    rep.section('XLSX date-column cell typing')
    for col in DATE_COLUMNS:
        if col not in hn:
            rep.put('xlsx.dates.' + col, 'COLUMN MISSING'); continue
        kinds = collections.Counter(); fmts = collections.Counter(); timed = 0
        for d in dicts:
            k, dt, _ = classify_xlsx_date(d[col])
            kinds[k] += 1
            if k == 'true date':
                fmts[d[col][2]] += 1
                v = d[col][0]
                if isinstance(v, datetime.datetime) and (v.hour or v.minute or v.second): timed += 1
        rep.put('xlsx.dates.' + col, {'cell_kinds': dict(kinds), 'number_formats_of_true_dates': dict(fmts), 'true_dates_with_time_of_day': timed})
    return {'raw': raw, 'header': header, 'hn': hn, 'dicts': dicts, 'rownum': rownum, 'render': render}

def classify_xlsx_date(cell):
    """-> (kind, date|None, raw display).  kind: blank | true date | string | number (not date-formatted) | other"""
    v, is_date, fmt, _ = cell
    if v is None or (isinstance(v, str) and not v.strip()):
        return 'blank', None, ''
    if isinstance(v, datetime.datetime):
        return 'true date', v.date(), v.isoformat(sep=' ')
    if isinstance(v, datetime.date):
        return 'true date', v, v.isoformat()
    if isinstance(v, str):
        d, form = parse_text_date(v)
        return 'string', d, v
    if isinstance(v, (int, float)) and not isinstance(v, bool):
        return 'number (not date-formatted)', excel_serial_to_date(v) if 1 < v < 110000 else None, repr(v)
    return 'other', None, repr(v)

# ------------------------------------------------------------------ CSV vs XLSX
def plausible(d, updated, asof, col):
    """An event date is plausible when it is not after the record's own last update and not after the as-of date.
    Expiry dates are exempt (legitimately in the future)."""
    if d is None: return None
    if col in FUTURE_ALLOWED: return 'n/a (future allowed)'
    if d > asof: return False
    if updated is not None and d > updated: return False
    return True

def compare(c, x, asof, rep):
    rep.section('CSV versus XLSX')
    def occ(dicts, getref):
        m = collections.defaultdict(list)
        for i, d in enumerate(dicts): m[clean_ref(getref(d))].append(i)
        return m
    co = occ(c['dicts'], lambda d: d.get(REF, '')); xo = occ(x['dicts'], lambda d: d[REF][0] if REF in d else '')
    only_c = sorted(set(co) - set(xo), key=lambda r: (not r.isdigit(), int(r) if r.isdigit() else 0))
    only_x = sorted(set(xo) - set(co), key=lambda r: (not r.isdigit(), int(r) if r.isdigit() else 0))
    rep.put('compare.row_counts', {'csv': len(c['dicts']), 'xlsx': len(x['dicts'])})
    rep.put('compare.ref_sets_equal', not only_c and not only_x)
    rep.put('compare.refs_only_in_csv', {'count': len(only_c), 'examples': only_c[:rep.n]})
    rep.put('compare.refs_only_in_xlsx', {'count': len(only_x), 'examples': only_x[:rep.n]})
    if only_c or only_x: rep.error('CSV and XLSX Ref ID sets differ')
    occ_mismatch = sorted(r for r in set(co) & set(xo) if len(co[r]) != len(xo[r]))
    rep.put('compare.refs_with_different_occurrence_counts', occ_mismatch[:rep.n])
    rep.put('compare.same_row_order', [clean_ref(d.get(REF, '')) for d in c['dicts']] == [clean_ref(d[REF][0]) for d in x['dicts']] if REF in x['hn'] else None)
    pairs = [(ci, xi, r) for r in co if r in xo for ci, xi in zip(co[r], xo[r])]
    rep.put('compare.row_pairs_compared', len(pairs))
    # ---- dates
    conflicts = []; per_col = collections.Counter(); kinds = collections.Counter()
    for ci, xi, ref in pairs:
        cd, xd = c['dicts'][ci], x['dicts'][xi]
        cu, _ = parse_text_date(cd.get(UPDATED, ''))
        _, xu, _ = classify_xlsx_date(xd[UPDATED]) if UPDATED in xd else ('blank', None, '')
        for col in DATE_COLUMNS:
            if col not in cd or col not in xd: continue
            craw = cd[col] or ''
            cdt, cform = parse_text_date(craw)
            xkind, xdt, xraw = classify_xlsx_date(xd[col])
            if cform == 'blank' and xkind == 'blank': continue
            if cdt is not None and cdt == xdt: continue
            swap = None
            if cdt is not None and xdt is not None:
                swap = (swap_dm(cdt) == xdt) or (swap_dm(xdt) == cdt)
            upd = cu or xu
            pc, px = plausible(cdt, upd, asof, col), plausible(xdt, upd, asof, col)
            fm = c.get('file_max_updated')
            late_c = None if cdt is None or fm is None or col in FUTURE_ALLOWED else cdt > fm
            late_x = None if xdt is None or fm is None or col in FUTURE_ALLOWED else xdt > fm
            if col == UPDATED:
                pc = None if cdt is None else cdt <= asof; px = None if xdt is None else xdt <= asof
            if pc is True and px is True: verdict = 'both plausible'
            elif pc is True and px is not True: verdict = 'only CSV value plausible'
            elif px is True and pc is not True: verdict = 'only XLSX value plausible'
            elif isinstance(pc, str) or isinstance(px, str): verdict = 'not assessed (future dates allowed in this column)'
            else: verdict = 'neither plausible'
            kind = ('day/month swap' if swap else 'one side blank' if (cform == 'blank' or xkind == 'blank') else
                    'unparseable value' if (cdt is None or xdt is None) else 'different dates')
            per_col[col] += 1; kinds[kind] += 1
            conflicts.append({'ref': ref, 'field': col, 'csv_record_no': c['rownum'][ci], 'xlsx_row': x['rownum'][xi],
                              'csv_raw': craw, 'csv_parsed': str(cdt) if cdt else None, 'csv_form': cform,
                              'xlsx_raw': xraw, 'xlsx_parsed': str(xdt) if xdt else None, 'xlsx_cell_kind': xkind,
                              'xlsx_number_format': xd[col][2], 'day_month_swap_explains': swap, 'kind': kind,
                              'record_last_updated_csv': cd.get(UPDATED, ''), 'record_last_updated_xlsx': str(xu) if xu else None,
                              'asof': str(asof), 'file_max_record_last_updated': str(c.get('file_max_updated')), 'csv_value_after_file_max_record_updated': late_c, 'xlsx_value_after_file_max_record_updated': late_x, 'csv_value_plausible': pc, 'xlsx_value_plausible': px, 'verdict': verdict})
    conflicts.sort(key=lambda d: (DATE_COLUMNS.index(d['field']), not d['ref'].isdigit(), int(d['ref']) if d['ref'].isdigit() else 0))
    rep.put('compare.date_disagreements.total', len(conflicts))
    rep.put('compare.date_disagreements.by_field', dict(per_col)); rep.put('compare.date_disagreements.by_kind', dict(kinds))
    rep.data['compare.date_disagreements.detail'] = conflicts
    for d in conflicts[:max(rep.n * 5, 50)]:
        rep.note(f"  ref {d['ref']} | {d['field']} | CSV {d['csv_raw']!r} ({d['csv_parsed']}) vs XLSX {d['xlsx_raw']!r} ({d['xlsx_parsed']}; {d['xlsx_cell_kind']}"
                 f"{', format ' + str(d['xlsx_number_format']) if d['xlsx_cell_kind'] == 'true date' else ''}) | swap explains: {d['day_month_swap_explains']} | "
                 f"record last updated {d['record_last_updated_csv']!r} | {d['verdict']} | later than newest record update in file ({d['file_max_record_last_updated']}): CSV {d['csv_value_after_file_max_record_updated']}, XLSX {d['xlsx_value_after_file_max_record_updated']}")
    if len(conflicts) > max(rep.n * 5, 50):
        rep.note(f'  ... {len(conflicts) - max(rep.n * 5, 50)} more (all are in the --json output)')