GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Grid network and substations / code-generator / apps/substation-finder/Dt

Calibrate Design Freeze and 2 more files

A Python command-line tool in the substation finder folder of Code Generator that reads calibration, using SHA-256. It writes text (`write_text`), writes JSON (`write_json`) and parses date (`parse_date`).

602 lines of Python from code-generator, in 3 files. Topic: Grid network and substations. Section 264 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. Build N1 Deep Link Candidates storage · code-generator / apps/substation-finder/Dt/202608310050-build-n1-deep-link-candidates.py lines 1–174
  2. Build Renewable Energy Planning Database (REPD) Ref Index energy-data · code-generator / apps/substation-finder/Dt/202608310050-build-repd-ref-index.py lines 1–201
  3. Calibrate Design Freeze storage · code-generator / apps/substation-finder/Dt/202608310050-calibrate-design-freeze.py lines 1–227

Build N1 Deep Link Candidates

A Python command-line tool in the substation finder folder of Code Generator that reads atlas link contract and atlas current, using SHA-256 from the GridAtlas repository.

storagecode-generator / apps/substation-finder/Dt/202608310050-build-n1-deep-link-candidates.py · lines 1–174 of 174 · version 2026-08-31 00:50 · Entry point · pattern write_text (shared by 13 files)

What it does
It loads atlas link contract and atlas current. Defines sha256, write_text, write_json, replace_strings, main. Uses libraries __future__, argparse, datetime, difflib, hashlib. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'substation'): 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: data source: gridatlas data; JSON file live-set.json; JSON file atlas-v9-link-contract.json; JSON file atlas-v9-current.json; JSON file n1-manifest.json; command-line arguments.
Downstream impact
Used directly by 1 file: Code Generator — Substation Finder Page (code-generator, https://ventusltd.github.io/code-generator/apps/substation-finder/).
What it achieves
It writes text (`write_text`), writes JSON (`write_json`) and replaces strings (`replace_strings`). Build isolated N1 candidate files. Never writes into producer repositories. It writes `atlas-v9-current.json`. It accepts `--output`, `--generation` and `--pipelinenews`.
Why it matters
Loaded by the Substation Finder page at https://ventusltd.github.io/code-generator/apps/substation-finder/.
Application
code-generator · apps/substation-finder/Dt · Python CLI
Uses
GridAtlas — Atlas Page (estate URL), GridAtlas — Index Page (estate URL), __future__, argparse, datetime, difflib, hashlib, json, pathlib, typing
Used by
linked from Code Generator — Substation Finder Page (link)
Produces
sha256, write_text, write_json, replace_strings, main
Defines here
sha256, write_text, write_json, replace_strings, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
code-generator@3897d83efcd0259d21dce87704b0c33118fe2c2e apps/substation-finder/Dt/202608310050-build-n1-deep-link-candidates.py:1-174 · blob 64ca55f8ac7c422bbd9b7f9edfa73a60c4c27882 · 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: supporting_data
#!/usr/bin/env python3
"""Build isolated N1 candidate files. Never writes into producer repositories."""
from __future__ import annotations

import argparse
import datetime as dt
import difflib
import hashlib
import json
from pathlib import Path
from typing import Any

OLD_BASE = "https://ventusltd.github.io/gridatlas/202608300453-atlas-v9/"
STABLE_BASE = "https://ventusltd.github.io/gridatlas/atlas/"
STATE_URL = "https://ventusltd.github.io/gridatlas/state/live-set.json"


def sha256(path: Path) -> str:
    return hashlib.sha256(path.read_bytes()).hexdigest()


def write_text(path: Path, text: str) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(text.rstrip() + "\n", encoding="utf-8")


def write_json(path: Path, value: Any) -> None:
    write_text(path, json.dumps(value, indent=2, sort_keys=False))


def replace_strings(value: Any) -> Any:
    if isinstance(value, dict):
        return {key: replace_strings(item) for key, item in value.items()}
    if isinstance(value, list):
        return [replace_strings(item) for item in value]
    if isinstance(value, str):
        return value.replace(OLD_BASE, STABLE_BASE)
    return value


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--output", required=True, type=Path)
    parser.add_argument("--generation", required=True)
    parser.add_argument("--pipelinenews", required=True, type=Path)
    parser.add_argument("--companies", required=True, type=Path)
    parser.add_argument("--gridatlas-current", required=True, type=Path)
    args = parser.parse_args()

    output = args.output.resolve()
    pipeline_source = args.pipelinenews / "ui" / "atlas-v9-deep-links.js"
    company_source = args.companies / "state" / "atlas-v9-link-contract.json"
    if not pipeline_source.is_file():
        raise SystemExit(f"missing {pipeline_source}")
    if not company_source.is_file():
        raise SystemExit(f"missing {company_source}")

    current = json.loads(args.gridatlas_current.read_text(encoding="utf-8"))
    composition_generation = str(current.get("generation", ""))
    release_id = str(current.get("release_id", ""))
    if current.get("live_route") != "/gridatlas/atlas/":
        raise SystemExit("gridatlas stable live route is not /gridatlas/atlas/")

    original_js = pipeline_source.read_text(encoding="utf-8")
    if OLD_BASE not in original_js and STABLE_BASE not in original_js:
        raise SystemExit("pipelinenews Atlas base is neither the known stale nor stable route")
    candidate_js = original_js.replace(OLD_BASE, STABLE_BASE)
    candidate_js_path = output / "pipelinenews" / "ui" / "atlas-v9-deep-links.js"
    write_text(candidate_js_path, candidate_js)
    patch = "".join(
        difflib.unified_diff(
            original_js.splitlines(keepends=True),
            candidate_js.splitlines(keepends=True),
            fromfile="a/ui/atlas-v9-deep-links.js",
            tofile="b/ui/atlas-v9-deep-links.js",
        )
    )
    write_text(output / "pipelinenews" / "patches" / f"{args.generation}-stable-gridatlas-route.patch", patch or "# already stable; no textual patch")

    pipeline_state = args.pipelinenews / "state" / "atlas-v9-current.json"
    if pipeline_state.is_file():
        state_original = json.loads(pipeline_state.read_text(encoding="utf-8"))
        state_candidate = replace_strings(state_original)
        if isinstance(state_candidate, dict):
            state_candidate["composition_generation"] = composition_generation
            state_candidate["candidate_generation"] = args.generation
            state_candidate["candidate_classification"] = "STABLE_GRIDATLAS_ROUTE_NOT_PROMOTED"
        write_json(output / "pipelinenews" / "state" / "atlas-v9-current.json", state_candidate)

    receipt = {
        "schema": "pipelinenews.gridatlas-pointer-receipt.v2",
        "generation": args.generation,
        "classification": "CANDIDATE_VERIFIED_GRIDATLAS_LIVE_POINTER_NOT_PROMOTED",
        "repository": "Ventusltd/gridatlas",
        "pointer": {"path": "state/live-set.json", "url": STATE_URL},
        "receiver": {
            "base_url": STABLE_BASE,
            "route": "/gridatlas/atlas/",
            "release_id": release_id,
            "composition_generation": composition_generation,
            "query_parameter": "repd_ref",
            "golden_repd_refs": ["13599", "17494"],
            "required_pointer_state": {"promotion_eligible": True, "failed_gates": 0},
        },
        "immutable_route_is_uncartridged": True,
        "promotion_eligible": False,
    }
    write_json(output / "pipelinenews" / "receipts" / f"{args.generation}-gridatlas-pointer-receipt.v2.json", receipt)

    company_original = json.loads(company_source.read_text(encoding="utf-8"))
    company_candidate = replace_strings(company_original)
    company_candidate["schema"] = "companies.gridatlas-v9-link-contract.v2"
    company_candidate["classification"] = "CANDIDATE_STABLE_GRIDATLAS_LINK_TEMPLATE_NOT_PROMOTED"
    company_candidate["generated_at"] = dt.datetime.now(dt.timezone.utc).isoformat().replace("+00:00", "Z")
    company_candidate["generation"] = args.generation
    atlas = company_candidate.setdefault("atlas", {})
    atlas["base_url"] = STABLE_BASE
    atlas["route"] = "/gridatlas/atlas/"
    atlas["state_url"] = STATE_URL
    atlas["composition_generation"] = composition_generation
    atlas["release_id"] = release_id
    join = company_candidate.setdefault("join", {})
    join["golden_url"] = f"{STABLE_BASE}?repd_ref=13599"
    join["url_template"] = f"{STABLE_BASE}?repd_ref={{repd_ref}}"
    company_candidate["verification_requirements"] = {
        "pointer_promotion_eligible": True,
        "pointer_failed_gates": 0,
        "golden_repd_refs": ["13599", "17494"],
        "desktop_and_375x667_browser_proof": True,
        "route_interceptions": 0,
        "synthetic_receiver": False,
    }
    company_candidate["promotion_eligible"] = False
    write_json(output / "companies" / "state" / f"{args.generation}-atlas-v9-link-contract.json", company_candidate)

    sentinels = {
        "schema": "gridatlas.federated-deep-link-sentinels.v1",
        "generation": args.generation,
        "stable_base": STABLE_BASE,
        "tests": [
            {"id": "stable-beacon-fen", "url": f"{STABLE_BASE}?repd_ref=13599", "expected": "resolved"},
            {"id": "root-redirect-beacon-fen", "url": "https://ventusltd.github.io/gridatlas/?repd_ref=13599", "expected": "resolved"},
            {"id": "stable-east-pye", "url": f"{STABLE_BASE}?repd_ref=17494", "expected": "resolved"},
            {"id": "stale-root-release", "url": f"{OLD_BASE}?repd_ref=13599", "expected_http": 404},
        ],
    }
    write_json(output / "tests" / f"{args.generation}-federated-deep-link-sentinels.json", sentinels)

    manifest = {
        "schema": "gridatlas.n1-candidate-manifest.v1",
        "generation": args.generation,
        "classification": "CANDIDATE_ONLY_NO_PRODUCER_REPOSITORY_CHANGED",
        "inputs": {
            "pipelinenews_source": str(pipeline_source),
            "pipelinenews_source_sha256": sha256(pipeline_source),
            "companies_source": str(company_source),
            "companies_source_sha256": sha256(company_source),
            "gridatlas_composition_generation": composition_generation,
            "gridatlas_release_id": release_id,
        },
        "outputs": {
            "pipelinenews_candidate_sha256": sha256(candidate_js_path),
            "stable_base": STABLE_BASE,
            "live_pointer_changed": False,
            "producer_main_changed": False,
        },
    }
    write_json(output / "n1-manifest.json", manifest)
    print(json.dumps(manifest, indent=2))
    return 0


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

Build Renewable Energy Planning Database (REPD) Ref Index

A Python command-line tool in the substation finder folder of Code Generator that reads REPD projects, cartridge installation readiness and the REPD register, using SHA-256.

energy-datacode-generator / apps/substation-finder/Dt/202608310050-build-repd-ref-index.py · lines 1–201 of 201 · version 2026-08-31 00:50 · Entry point · pattern normal (shared by 2 files)

What it does
It loads REPD projects, cartridge installation readiness and the REPD register. Defines sha256, write_text, write_json, normal, main. Uses libraries __future__, argparse, gzip, hashlib, json. Side effects: reads or writes files; uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'repd'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: the REPD register.
Inputs & outputs
In: Parquet file repd_projects_202608290716.parquet; JSON file cartridge-installation-readiness.json; DuckDB queries; command-line arguments.
Downstream impact
Used directly by 1 file: Code Generator — Substation Finder Page (code-generator, https://ventusltd.github.io/code-generator/apps/substation-finder/).
What it achieves
It writes text (`write_text`) and writes JSON (`write_json`). Build the N2 static exact-REPD reference index as an isolated test artefact. It writes `manifest.json`. It accepts `--parquet`, `--output` and `--generation`.
Why it matters
Loaded by the Substation Finder page at https://ventusltd.github.io/code-generator/apps/substation-finder/.
Application
code-generator · apps/substation-finder/Dt · Python CLI
Uses
__future__, argparse, gzip, hashlib, json, shutil, pathlib, typing
Used by
linked from Code Generator — Substation Finder Page (link)
Produces
sha256, write_text, write_json, normal, main
Defines here
sha256, write_text, write_json, normal, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
code-generator@3897d83efcd0259d21dce87704b0c33118fe2c2e apps/substation-finder/Dt/202608310050-build-repd-ref-index.py:1-201 · blob 6dedb985c0e97462b3e8b602ae7befa0e1d9aebe · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: supporting_data
#!/usr/bin/env python3
"""Build the N2 static exact-REPD reference index as an isolated test artefact."""
from __future__ import annotations

import argparse
import gzip
import hashlib
import json
import shutil
from pathlib import Path
from typing import Any

import duckdb

EXPECTED_PARQUET_SHA256 = "174040c37f3d63742d6fdd7af722a8cfdf3fb53de3ff85ff1142d22fdac4866b"
EXPECTED_ROWS = 11069
EXPECTED_COLUMNS = ["name", "technology", "status", "capacity_mw", "longitude", "latitude"]


def sha256(path: Path) -> str:
    return hashlib.sha256(path.read_bytes()).hexdigest()


def write_text(path: Path, text: str) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(text.rstrip() + "\n", encoding="utf-8")


def write_json(path: Path, value: Any, *, compact: bool = False) -> None:
    if compact:
        write_text(path, json.dumps(value, ensure_ascii=False, separators=(",", ":"), sort_keys=False))
    else:
        write_text(path, json.dumps(value, indent=2, ensure_ascii=False, sort_keys=False))


def normal(value: Any) -> Any:
    if value is None:
        return None
    if isinstance(value, float):
        if value != value:
            return None
        return round(value, 7)
    return value


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--parquet", required=True, type=Path)
    parser.add_argument("--output", required=True, type=Path)
    parser.add_argument("--generation", required=True)
    parser.add_argument("--build-plan", type=Path, default=Path("_build-plan"))
    args = parser.parse_args()

    parquet = args.parquet.resolve()
    output = (args.output / "repd-ref-index").resolve()
    output.mkdir(parents=True, exist_ok=True)
    if not parquet.is_file():
        raise SystemExit(f"missing Parquet {parquet}")
    parquet_sha = sha256(parquet)
    if parquet_sha != EXPECTED_PARQUET_SHA256:
        raise SystemExit(f"Parquet SHA-256 mismatch: {parquet_sha}")

    connection = duckdb.connect(database=":memory:", read_only=False, config={"threads": "1"})
    try:
        rows = connection.execute(
            """
            SELECT
              CAST(repd_ref AS VARCHAR) AS repd_ref,
              CAST(name AS VARCHAR) AS name,
              CAST(technology AS VARCHAR) AS technology,
              CAST(status AS VARCHAR) AS status,
              CAST(capacity_mw AS DOUBLE) AS capacity_mw,
              CAST(longitude AS DOUBLE) AS longitude,
              CAST(latitude AS DOUBLE) AS latitude
            FROM read_parquet(?)
            ORDER BY TRY_CAST(repd_ref AS BIGINT) ASC NULLS LAST, repd_ref ASC
            """,
            [str(parquet)],
        ).fetchall()
    finally:
        connection.close()

    if len(rows) != EXPECTED_ROWS:
        raise SystemExit(f"row closure mismatch: {len(rows)} != {EXPECTED_ROWS}")

    records: dict[str, list[Any]] = {}
    false_origins = 0
    unmapped = 0
    for repd_ref, name, technology, status, capacity_mw, longitude, latitude in rows:
        ref = str(repd_ref).strip()
        if not ref:
            raise SystemExit("empty repd_ref")
        if ref in records:
            raise SystemExit(f"duplicate repd_ref {ref}")
        lon = normal(longitude)
        lat = normal(latitude)
        if lon is None or lat is None:
            unmapped += 1
        if lon is not None and lat is not None and abs(lat - 49.766807) < 1e-9 and abs(lon + 7.55716) < 1e-9:
            false_origins += 1
        records[ref] = [
            str(name or ""),
            str(technology or ""),
            str(status or ""),
            normal(capacity_mw),
            lon,
            lat,
        ]

    index = {
        "schema": "gridatlas.repd-ref-index.v1",
        "generation": args.generation,
        "source": {
            "path": "data/repd_projects_202608290716.parquet",
            "sha256": parquet_sha,
            "rows": EXPECTED_ROWS,
        },
        "identity": "EXACT_REPD_REF_ONLY",
        "row_format": EXPECTED_COLUMNS,
        "rows": len(records),
        "records": records,
    }
    json_path = output / f"repd_ref_index_{args.generation}.json"
    write_json(json_path, index, compact=True)

    gzip_path = output / f"repd_ref_index_{args.generation}.json.gz"
    with gzip.GzipFile(filename="", mode="wb", fileobj=gzip_path.open("wb"), compresslevel=9, mtime=0) as target:
        target.write(json_path.read_bytes())

    golden = records.get("13599")
    if not golden or "Beacon Fen" not in golden[0]:
        raise SystemExit("golden REPD 13599 missing or unexpected")

    manifest = {
        "schema": "gridatlas.repd-ref-index-manifest.v1",
        "generation": args.generation,
        "classification": "TEST_DATA_ARTEFACT_NOT_INSTALLED",
        "source_parquet": {
            "path": "data/repd_projects_202608290716.parquet",
            "bytes": parquet.stat().st_size,
            "sha256": parquet_sha,
        },
        "index": {
            "path": json_path.name,
            "bytes": json_path.stat().st_size,
            "sha256": sha256(json_path),
            "gzip_path": gzip_path.name,
            "gzip_bytes": gzip_path.stat().st_size,
            "gzip_sha256": sha256(gzip_path),
            "rows": len(records),
            "unique_repd_refs": len(records),
            "row_format": EXPECTED_COLUMNS,
            "unmapped_rows": unmapped,
            "false_origin_rows": false_origins,
        },
        "golden": {
            "repd_ref": "13599",
            "name": golden[0],
            "longitude": golden[4],
            "latitude": golden[5],
        },
        "contracts": {
            "deep_link_uses_duckdb": False,
            "free_text_search_still_uses_duckdb_lazily": True,
            "live_pointer_changed": False,
            "cartridge_installed": False,
            "full_application_copy_created": False,
        },
    }
    write_json(output / "manifest.json", manifest)

    required_drafts = [
        args.build_plan / "DRAFT-CARTRIDGES" / "exact-ref-index.spec.md",
        args.build_plan / "DRAFT-CARTRIDGES" / "exact-ref-index.js.txt",
    ]
    missing = [str(path) for path in required_drafts if not path.is_file()]
    copied: list[dict[str, Any]] = []
    if not missing:
        draft_output = output / "draft-inputs"
        draft_output.mkdir(parents=True, exist_ok=True)
        for source in required_drafts:
            target = draft_output / source.name
            shutil.copyfile(source, target)
            copied.append({"source": str(source), "target": target.name, "sha256": sha256(target)})
    write_json(
        output / "cartridge-installation-readiness.json",
        {
            "schema": "gridatlas.exact-ref-index-installation-readiness.v1",
            "generation": args.generation,
            "status": "READY_FOR_ANCHORED_CARTRIDGE_BUILD" if not missing else "BLOCKED_MISSING_DRAFT_INPUTS",
            "missing": missing,
            "copied_drafts": copied,
            "rule": "Do not infer or rewrite the anchored search-cartridge patch when the reviewed draft is absent.",
        },
    )
    print(json.dumps(manifest, indent=2))
    return 0


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

Calibrate Design Freeze

A Python command-line tool in the substation finder folder of Code Generator that reads calibration, using SHA-256. It writes text (`write_text`), writes JSON (`write_json`) and parses date (`parse_date`).

storagecode-generator / apps/substation-finder/Dt/202608310050-calibrate-design-freeze.py · lines 1–227 of 227 · version 2026-08-31 00:50 · Entry point · pattern parse_date (shared by 5 files)

What it does
It loads calibration. Defines 7 functions or classes, including write_text, write_json, parse_date, capacity_band, records_from_file. Uses libraries __future__, argparse, datetime, hashlib, json. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'design'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
Inputs & outputs
In: JSON file calibration.json; command-line arguments.
Downstream impact
Used directly by 1 file: Code Generator — Substation Finder Page (code-generator, https://ventusltd.github.io/code-generator/apps/substation-finder/).
What it achieves
N4: deterministic design-freeze calibration over the frozen PipelineNews project spine. It writes `calibration.json`. It accepts `--pipelinenews`, `--output` and `--generation`.
Why it matters
Loaded by the Substation Finder page at https://ventusltd.github.io/code-generator/apps/substation-finder/.
Application
code-generator · apps/substation-finder/Dt · Python CLI
Uses
__future__, argparse, datetime, hashlib, json, statistics, subprocess, collections
Used by
linked from Code Generator — Substation Finder Page (link)
Produces
write_text, write_json, parse_date, capacity_band, records_from_file, sha256_paths, main
Defines here
write_text, write_json, parse_date, capacity_band, records_from_file, sha256_paths, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
code-generator@3897d83efcd0259d21dce87704b0c33118fe2c2e apps/substation-finder/Dt/202608310050-calibrate-design-freeze.py:1-227 · blob 3ecb90ec835273bb67cda86d9a0a5dde8d94255a · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: supporting_data
#!/usr/bin/env python3
"""N4: deterministic design-freeze calibration over the frozen PipelineNews project spine."""
from __future__ import annotations

import argparse
import datetime as dt
import hashlib
import json
import statistics
import subprocess
from collections import defaultdict
from pathlib import Path
from typing import Any, Iterable

TECHNOLOGIES = ["solar", "bess", "wind_onshore", "wind_offshore"]
BANDS = [
    ("1-5", 1.0, 5.0),
    ("5-20", 5.0, 20.0),
    ("20-50", 20.0, 50.0),
    ("50-100", 50.0, 100.0),
    ("100-250", 100.0, 250.0),
    ("250+", 250.0, float("inf")),
]
MIN_SAMPLES = 30


def write_text(path: Path, text: str) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(text.rstrip() + "\n", encoding="utf-8")


def write_json(path: Path, value: Any) -> None:
    write_text(path, json.dumps(value, indent=2, ensure_ascii=False, sort_keys=False))


def parse_date(value: Any) -> dt.date | None:
    if value in (None, ""):
        return None
    text = str(value).strip()
    if not text:
        return None
    try:
        return dt.date.fromisoformat(text[:10])
    except ValueError:
        return None


def capacity_band(capacity: float) -> str | None:
    for label, lower, upper in BANDS:
        if lower <= capacity < upper:
            return label
    return None


def records_from_file(path: Path) -> Iterable[dict[str, Any]]:
    value = json.loads(path.read_text(encoding="utf-8"))
    if isinstance(value, list):
        yield from (item for item in value if isinstance(item, dict))
        return
    if isinstance(value, dict):
        for key in ("projects", "records", "items", "features"):
            items = value.get(key)
            if isinstance(items, list):
                yield from (item for item in items if isinstance(item, dict))
                return
    raise ValueError(f"unsupported project partition shape: {path}")


def sha256_paths(paths: list[Path]) -> str:
    digest = hashlib.sha256()
    for path in paths:
        digest.update(path.name.encode("utf-8"))
        digest.update(b"\0")
        digest.update(hashlib.sha256(path.read_bytes()).digest())
    return digest.hexdigest()


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--pipelinenews", required=True, type=Path)
    parser.add_argument("--output", required=True, type=Path)
    parser.add_argument("--generation", required=True)
    args = parser.parse_args()

    repo = args.pipelinenews.resolve()
    output = (args.output / "design-freeze").resolve()
    output.mkdir(parents=True, exist_ok=True)
    partitions = sorted((repo / "data" / "projects").glob("*-project-partition-v9-1-*.json"))
    if not partitions:
        raise SystemExit("no PipelineNews v9.1 project partitions found")

    samples: dict[tuple[str, str], list[int]] = defaultdict(list)
    total_projects = 0
    eligible = 0
    malformed_dates = 0
    negative_intervals = 0
    out_of_universe = 0
    duplicate_ids: set[str] = set()
    seen_ids: set[str] = set()
    examples: list[dict[str, Any]] = []

    for partition in partitions:
        for project in records_from_file(partition):
            total_projects += 1
            project_id = str(project.get("gg_project_id") or "").strip()
            if project_id:
                if project_id in seen_ids:
                    duplicate_ids.add(project_id)
                seen_ids.add(project_id)
            technology = str(project.get("technology") or "").strip()
            try:
                capacity = float(project.get("capacity_mw"))
            except (TypeError, ValueError):
                continue
            band = capacity_band(capacity)
            if technology not in TECHNOLOGIES or band is None:
                out_of_universe += 1
                continue
            permission = parse_date(project.get("planning_permission_granted"))
            construction = parse_date(project.get("under_construction"))
            if project.get("planning_permission_granted") not in (None, "") and permission is None:
                malformed_dates += 1
            if project.get("under_construction") not in (None, "") and construction is None:
                malformed_dates += 1
            if not permission or not construction:
                continue
            delta = (construction - permission).days
            if delta < 0:
                negative_intervals += 1
                continue
            eligible += 1
            samples[(technology, band)].append(delta)
            if len(examples) < 20:
                examples.append({
                    "gg_project_id": project_id,
                    "repd_ref": str(project.get("repd_ref") or ""),
                    "technology": technology,
                    "capacity_mw": capacity,
                    "capacity_band": band,
                    "planning_permission_granted": permission.isoformat(),
                    "under_construction": construction.isoformat(),
                    "days": delta,
                })

    cells = []
    for technology in TECHNOLOGIES:
        for label, _, _ in BANDS:
            values = sorted(samples.get((technology, label), []))
            median = statistics.median(values) if len(values) >= MIN_SAMPLES else None
            cells.append({
                "technology": technology,
                "capacity_band": label,
                "samples": len(values),
                "median_days_permission_to_construction": median,
                "status": "PUBLISHED_MEDIAN" if median is not None else "NULL_INSUFFICIENT_SAMPLE",
                "minimum_samples": MIN_SAMPLES,
                "min_days": values[0] if values else None,
                "max_days": values[-1] if values else None,
            })

    try:
        source_commit = subprocess.check_output(["git", "-C", str(repo), "rev-parse", "HEAD"], text=True).strip()
    except Exception:
        source_commit = None

    calibration = {
        "schema": "pipelinenews.design-freeze-calibration.v1",
        "generation": args.generation,
        "classification": "CANDIDATE_DERIVED_NOT_PUBLISHED",
        "method": "median(under_construction - planning_permission_granted) by technology and capacity band",
        "source": {
            "repository": "Ventusltd/pipelinenews",
            "commit": source_commit,
            "partition_pattern": "data/projects/*-project-partition-v9-1-*.json",
            "partition_count": len(partitions),
            "partition_set_sha256": sha256_paths(partitions),
            "project_rows": total_projects,
        },
        "rules": {
            "minimum_samples": MIN_SAMPLES,
            "insufficient_cell_value": None,
            "negative_interval_policy": "exclude-and-count",
            "estimate_label": "DERIVED_NOT_PUBLISHED",
            "network_requests": 0,
        },
        "closure": {
            "eligible_intervals": eligible,
            "duplicate_project_ids": sorted(duplicate_ids),
            "malformed_dates": malformed_dates,
            "negative_intervals": negative_intervals,
            "out_of_universe": out_of_universe,
            "cells": len(cells),
            "published_cells": sum(1 for cell in cells if cell["median_days_permission_to_construction"] is not None),
            "null_cells": sum(1 for cell in cells if cell["median_days_permission_to_construction"] is None),
        },
        "cells": cells,
        "examples": examples,
        "promotion_eligible": False,
    }
    write_json(output / "calibration.json", calibration)

    contract = {
        "schema": "pipelinenews.design-freeze-calibration-contract.v1",
        "generation": args.generation,
        "deployment": "not-authorised",
        "source_commit": source_commit,
        "source_partition_set_sha256": calibration["source"]["partition_set_sha256"],
        "declared_key": ["technology", "capacity_band"],
        "hard_gates": {
            "cells": 24,
            "minimum_samples_or_null": True,
            "duplicate_project_ids": 0,
            "negative_intervals_retained_as_count": True,
            "deterministic_rebuild_required": True,
            "promotion_eligible": False,
        },
        "recovery_rule": "Never overwrite this calibration; create a later Europe/London timestamped successor.",
    }
    write_json(output / f"{args.generation}-design-freeze-calibration-contract.json", contract)
    print(json.dumps(calibration["closure"], indent=2))
    if duplicate_ids:
        raise SystemExit(f"duplicate project ids found: {len(duplicate_ids)}")
    return 0


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