GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Websites and apps / lightning / /

Collect and 1 more file

A Python command-line tool in Lightning that fetches UK lightning. It downloads outage (`DownloadOutage`), classifies download error (`classify_download_error`) and refreshes access token (`refresh_access_token`).

645 lines of Python from lightning, in 2 files. Topic: Websites and apps. Section 2002 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. Collect render · lightning / collect.py lines 701–1079
  2. Grid ingest · lightning / grid.py lines 1–266

Collect

A Python command-line tool in Lightning that fetches UK lightning. It downloads outage (`DownloadOutage`), classifies download error (`classify_download_error`) and refreshes access token (`refresh_access_token`).

renderlightning / collect.py · lines 701–1079 of 1079 (continued from section 2001) · Entry point · pattern run_search (shared by 2 files)

What it does
It fetches UK lightning. Defines 47 functions or classes, including TooManyUnparsed, __init__, DownloadOutage, __init__, _sleep. Uses libraries __future__, argparse, io, json, math. Side effects: changes the web page (DOM); reads or writes files; makes network requests.
Why it exists in the grid workflow
README: "`collect.py`: downloads genuine LFL products with `eumdac`, reads NetCDF BODY data, filters UK coordinates and exports GeoJSON."
Inputs & outputs
In: JSON file index.json; GeoJSON file uk_lightning.geojson; JSON file status.json; command-line arguments.
Downstream impact
Used directly by 25 files: Backfill Lightning Workflow (lightning); Update Lightning Workflow (lightning); Test Backfill (lightning); Test Backfill Parallel (lightning); and 21 more. Reached from 9 other entry points, including Backfill Parallel Lightning Workflow (lightning); Test Lightning Workflow (lightning); Verify Lightning Data Workflow (lightning).
What it achieves
UK lightning flash GeoJSON from EUMETSAT Meteosat LI L2-LFL. It accepts `--hours`, `--auto-window` and `--rebuild-day`.
Why it matters
Imported by Grid, History and Status. Run by 4 workflows and scripts, including Backfill Lightning Workflow, Update Lightning Workflow and Backfill Parallel. Checked by 18 tests, including Test Backfill.
Application
lightning · / · Python CLI
Uses
__future__, argparse, io, json, math, os, random, re
Used by
run by Backfill Lightning Workflow (workflow run), run by Update Lightning Workflow (workflow run), imported by Test Backfill (import), imported by Test Backfill Parallel (import), imported by Test Backfill Workflow (import), imported by Test CI Verify (import), imported by Test Collect (import), imported by Test Concurrent Writers (import), and 17 more
Produces
TooManyUnparsed, DownloadOutage, http_status, retry_after_seconds, classify_download_error, backoff_seconds, refresh_access_token, new_retry_stats, fetch_product, parse_utc, iso_utc, inside_uk_view
Defines here
read_last_success, product_slot, flash_slot, classify_flash, flash_in_examined_slot, split_by_window, merge_ranges, scanned_ranges, unscanned_ranges, _iso_pairs, build_run_record, write_json, rebuild_day_record, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
lightning@2882145e28a0412de3a5bcfa40a12d7cd894ba90 collect.py:701-1079 · blob f97c7322fa6fb321a18a55c3d9e5c184bfcb35ae · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network · domain stage: unknown · users: none · canonical: unknown
    successful scan exceeds the maximum: the part of the gap older than
    ``maximum`` can never be searched by the scheduled job and stays UNKNOWN.
    """
    minimum = timedelta(hours=minimum_hours)
    maximum = timedelta(hours=maximum_hours)
    wanted = minimum
    if last_success_end is not None:
        wanted = max(minimum, now - last_success_end + timedelta(minutes=margin_minutes))
    return min(wanted, maximum), wanted > maximum


def read_last_success(status_path: Path | None, history_dir: Path | None) -> tuple[datetime | None, str]:
    """Last successful scan end from data/status.json, else the archive index."""
    if status_path and status_path.exists():
        try:
            status = json.loads(status_path.read_text(encoding="utf-8"))
            value = status.get("last_successful_scan_end_utc")
            if value:
                return parse_utc(value), "status"
        except (ValueError, TypeError, AttributeError):
            pass
    index_path = history_dir / "index.json" if history_dir else None
    if index_path and index_path.exists():
        try:
            index = json.loads(index_path.read_text(encoding="utf-8"))
            value = index.get("last_successful_scan_end_utc")
            if value:
                return parse_utc(value), "index"
            ends = [parse_utc(w["end_utc"]) for w in index.get("scan_windows", []) if w.get("end_utc")]
            if ends:
                return max(ends), "index"
        except (ValueError, TypeError, AttributeError, KeyError):
            pass
    return None, "default"


# --- examined 10-minute product slots --------------------------------------

def product_slot(product_name: str) -> tuple[datetime, datetime] | None:
    """Sensing slot [start, end) encoded in an LFL product name, or None."""
    match = PRODUCT_SLOT.search(product_name or "")
    if not match:
        return None
    try:
        start = datetime.strptime(match.group(1), "%Y%m%d%H%M%S").replace(tzinfo=timezone.utc)
        end = datetime.strptime(match.group(2), "%Y%m%d%H%M%S").replace(tzinfo=timezone.utc)
    except ValueError:
        return None
    if end <= start or (end - start) > timedelta(hours=1):
        return None
    return start, end


def flash_slot(feature) -> tuple[datetime, datetime] | None:
    """Nominal sensing slot of the product a flash came from (its id is
    ``<product name>:<index>``), or None when the id carries no product slot."""
    identifier = feature.get("id") if isinstance(feature, dict) else None
    if not isinstance(identifier, str):
        return None
    return product_slot(identifier.rsplit(":", 1)[0])


# classify_flash results. The first two are consistent with the examined slots;
# the third is a genuine flash in time nobody searched (kept and counted, its
# slot stays unknown); the last two are inconsistent records (refused).
FLASH_IN_PRODUCT_SPAN = "in_product_span"        # within tolerance of its product's nominal span
FLASH_IN_EXAMINED_SPAN = "in_examined_span"      # outside that, but its own time lies in an examined span
FLASH_IN_UNEXAMINED_TIME = "in_unexamined_time"  # examined product, own time in no examined span
FLASH_UNEXAMINED_PRODUCT = "unexamined_product"  # its product is not among the examined slots
FLASH_NO_SLOT_OUTSIDE = "no_slot_outside"        # legacy id without a product slot, outside every span


def classify_flash(feature, examined_starts, spans, *,
                   tolerance_seconds: float = SLOT_EDGE_TOLERANCE_SECONDS) -> str:
    """How a flash relates to what the search examined (one of the FLASH_* values).

    The product (from the id) decides only WHETHER the flash was examined: its
    nominal start must be one of ``examined_starts``. WHEN the flash happened is
    its own timestamp, checked against its product's nominal span +- tolerance
    and then against the union of examined ``spans``; a product's name span is
    not a bound on its flashes' times (see SLOT_EDGE_TOLERANCE_SECONDS).
    """
    moment = parse_utc(feature["properties"]["time_utc"])
    in_spans = any(s <= moment < e for s, e in spans)
    slot = flash_slot(feature)
    if slot is None:
        return FLASH_IN_EXAMINED_SPAN if in_spans else FLASH_NO_SLOT_OUTSIDE
    start, end = slot
    if start not in examined_starts:
        return FLASH_UNEXAMINED_PRODUCT
    tolerance = timedelta(seconds=tolerance_seconds)
    if start - tolerance <= moment < end + tolerance:
        return FLASH_IN_PRODUCT_SPAN
    return FLASH_IN_EXAMINED_SPAN if in_spans else FLASH_IN_UNEXAMINED_TIME


def flash_in_examined_slot(feature, examined_starts, spans, *,
                           tolerance_seconds: float = SLOT_EDGE_TOLERANCE_SECONDS) -> bool:
    """Does this flash's own time lie in examined time (its product's span +- tolerance,
    or any examined span), with its product examined? See classify_flash."""
    return classify_flash(feature, examined_starts, spans, tolerance_seconds=tolerance_seconds) in (
        FLASH_IN_PRODUCT_SPAN, FLASH_IN_EXAMINED_SPAN)


def split_by_window(features, start: datetime, end: datetime) -> tuple[list, int]:
    """(flashes timed inside [start, end), number of flashes outside it)."""
    inside, outside = [], 0
    for feature in features:
        if start <= parse_utc(feature["properties"]["time_utc"]) < end:
            inside.append(feature)
        else:
            outside += 1
    return inside, outside


def merge_ranges(ranges, *, tolerance_seconds: float = 1.0) -> list[tuple[datetime, datetime]]:
    """Union of half-open ranges; adjacent slots (within tolerance) join."""
    ordered = sorted((s, e) for s, e in ranges if e > s)
    merged: list[list[datetime]] = []
    for start, end in ordered:
        if merged and start <= merged[-1][1] + timedelta(seconds=tolerance_seconds):
            merged[-1][1] = max(merged[-1][1], end)
        else:
            merged.append([start, end])
    return [(s, e) for s, e in merged]


def scanned_ranges(product_names, beginning: datetime, now: datetime) -> tuple[list[tuple[datetime, datetime]], list[datetime], bool]:
    """Searched coverage of a run = union of examined slots clipped to [beginning, now).

    Returns (ranges, slot_starts, parsed). When no product name carries a
    slot, the whole query window is returned and ``parsed`` is False so the
    record can say the coverage is the requested window, not examined slots.
    """
    slots = []
    for name in product_names:
        slot = product_slot(name)
        if slot:
            slots.append(slot)
    if not slots:
        return ([(beginning, now)] if now > beginning else []), [], False
    clipped = []
    for start, end in slots:
        s, e = max(start, beginning), min(end, now)
        if e > s:
            clipped.append((s, e))
    return merge_ranges(clipped), sorted({s for s, _ in slots}), True


def unscanned_ranges(ranges, beginning: datetime, now: datetime, *, grace_seconds: int = PUBLICATION_GRACE_SECONDS):
    """Gaps inside [beginning, now) no examined slot covers.

    Returns (gaps, tail_seconds): ``tail_seconds`` is the unobserved tail
    ending at ``now`` (products not yet published); ``gaps`` are the other
    holes, i.e. genuine source gaps (EUMETSAT slots missing at search time).
    """
    gaps = []
    cursor = beginning
    for start, end in sorted(ranges):
        if start > cursor:
            gaps.append((cursor, start))
        cursor = max(cursor, end)
    tail_seconds = 0
    if cursor < now:
        tail_seconds = int((now - cursor).total_seconds())
        if tail_seconds > grace_seconds:
            gaps.append((cursor, now))
    return gaps, tail_seconds


def _iso_pairs(ranges):
    return [{"start_utc": iso_utc(s), "end_utc": iso_utc(e)} for s, e in ranges]


def build_run_record(
    *,
    now: datetime,
    beginning: datetime,
    lookback_source: str,
    lookback_capped: bool,
    last_success_before: datetime | None,
    product_names,
    products_examined: int,
    incoming,
    existing,
    feed,
    unparsed=(),
    retries=None,
) -> dict:
    """Everything the archive and status steps need; never committed itself."""
    ranges, slot_starts, parsed = scanned_ranges(product_names, beginning, now)
    gaps, tail = unscanned_ranges(ranges, beginning, now)
    return {
        "schema": RUN_RECORD_SCHEMA,
        "run_utc": iso_utc(now),
        "outcome": "success",
        "error": None,
        "query_start_utc": iso_utc(beginning),
        "query_end_utc": iso_utc(now),
        "lookback_hours": round((now - beginning).total_seconds() / 3600, 4),
        "lookback_source": lookback_source,
        "lookback_capped": lookback_capped,
        "last_successful_scan_end_utc_before_run": iso_utc(last_success_before) if last_success_before else None,
        "products_examined": products_examined,
        "slot_seconds": SLOT_SECONDS,
        "slots_examined": len(slot_starts),
        "slots_examined_utc": [iso_utc(s) for s in slot_starts],
        "slots_parsed": parsed,
        "products_unparsed": len(unparsed),
        "unparsed_products": list(unparsed),
        "unparsed_slots_utc": unparsed_slot_starts(unparsed, product_names, beginning, now),
        "max_unparsed_day_fraction": MAX_UNPARSED_DAY_FRACTION,
        # Per-product download retries (transient errors, 429 waits, 401 token refresh).
        "download_retries": retries if retries is not None else new_retry_stats(),
        "scanned_ranges": _iso_pairs(ranges),
        "scanned_end_utc": iso_utc(max(e for _, e in ranges)) if ranges else None,
        "unscanned_ranges": _iso_pairs(gaps),
        "tail_unobserved_seconds": tail,
        "incoming_features": len(incoming),
        "feed_features": len(feed["features"]),
        "feed_total_before_display_cap": feed["metadata"]["total_before_display_cap"],
        "feed_latest_detection_utc": feed["metadata"]["latest_detection_utc"],
        "note": ("Only examined 10-minute slots count as searched; the unobserved tail, gaps and unparsed "
                 "(unreadable or failed-download) product slots are unknown, not zero."),
        # Uncapped incoming detections plus the previously published feed (the
        # seed on the first archive run; idempotent afterwards).
        "features": [*existing, *incoming],
    }


def write_json(path: Path, obj) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(obj, separators=(",", ":"), ensure_ascii=False) + "\n", encoding="utf-8")


def rebuild_day_record(day: str, run_record: Path, *, now: datetime | None = None, downloader=None) -> int:
    """Fresh EUMETSAT search of one whole UTC date, for ``history.py recover --rebuild``.

    Writes ONLY the run record (never the public feed, status or archive). Its
    ``run_utc`` is the real time of this search, so recover can check it was made
    after the loss was detected; its examined slots and flashes are then checked
    against the archive's recorded scan windows and count before anything changes.
    """
    from datetime import date as _date
    now = (now or datetime.now(timezone.utc)).astimezone(timezone.utc)
    start = datetime.combine(_date.fromisoformat(day), datetime.min.time(), tzinfo=timezone.utc)
    end = min(start + timedelta(days=1), now)
    if end <= start:
        raise ValueError(f"{day} has not started yet")
    product_count, unparsed, retries = 0, [], None
    try:
        incoming, product_count, names, unparsed, retries = unpack_download((downloader or download)(start, end))
        check_unparsed(unparsed, names, start, end)
        # Flashes of an examined product timed outside the UTC date (e.g. the
        # previous day's tail of a product straddling midnight) are not this
        # date's observations: dropped from the record and counted.
        incoming, outside_day = split_by_window(incoming, start, end)
    except (TooManyUnparsed, DownloadOutage) as error:
        unparsed = error.unparsed if isinstance(error, DownloadOutage) else unparsed
        retries = error.retries if isinstance(error, DownloadOutage) else retries
        write_json(run_record, {
            "schema": RUN_RECORD_SCHEMA, "run_utc": iso_utc(now), "outcome": "failure",
            "error": f"{type(error).__name__}: {error}", "rebuild_day_utc": day,
            "query_start_utc": iso_utc(start), "query_end_utc": iso_utc(end),
            "products_examined": product_count, "products_unparsed": len(unparsed),
            "unparsed_products": unparsed, "download_retries": retries, "scanned_ranges": [], "features": [],
        })
        raise
    record = build_run_record(
        now=end, beginning=start, lookback_source="rebuild", lookback_capped=False, last_success_before=None,
        product_names=names, products_examined=product_count, incoming=incoming, existing=[],
        feed={"features": [], "metadata": {"total_before_display_cap": None, "latest_detection_utc": None}},
        unparsed=unparsed, retries=retries,
    )
    record["run_utc"] = iso_utc(now)
    record["rebuild_day_utc"] = day
    record["outside_day"] = outside_day
    record["note"] = ("Rebuild search of one UTC date for history.py recover --rebuild; not a feed run. "
                      "Only examined 10-minute slots count as searched.")
    write_json(run_record, record)
    print(f"Rebuild of {day}: {len(incoming)} flashes from {product_count} products "
          f"({record['slots_examined']} slots examined, {len(record['unscanned_ranges'])} gaps, "
          f"{record['products_unparsed']} unparsed product(s), {retries['retries']} download retries, "
          f"{outside_day} flash(es) outside the date dropped).", file=sys.stderr)
    return 0


def main(argv=None, *, now: datetime | None = None):
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    window = parser.add_mutually_exclusive_group()
    window.add_argument("--hours", type=float, default=None, help="Explicit lookback from EUMETSAT; 1-48")
    window.add_argument("--auto-window", action="store_true",
                        help=f"max({LOOKBACK_MIN_HOURS} h, now - last successful scan end + "
                             f"{LOOKBACK_MARGIN_MINUTES} min) capped at {LOOKBACK_MAX_HOURS} h")
    window.add_argument("--rebuild-day", default=None, metavar="YYYY-MM-DD",
                        help="Search one whole past UTC date and write only --run-record (for history.py recover --rebuild)")
    parser.add_argument("--retention-days", type=int, default=7)
    parser.add_argument("--out", type=Path, default=Path("data/uk_lightning.geojson"))
    parser.add_argument("--status", type=Path, default=Path("data/status.json"),
                        help="Collector status file read for the last successful scan end")
    parser.add_argument("--history-dir", type=Path, default=Path("data/history"),
                        help="Archive directory; its index is the fallback source of the last scan end")
    parser.add_argument("--run-record", type=Path, default=None,
                        help="Where to leave the uncapped run record for the archive/status steps (not committed)")
    args = parser.parse_args(argv)
    if args.rebuild_day:
        if not args.run_record:
            parser.error("--rebuild-day needs --run-record")
        return rebuild_day_record(args.rebuild_day, args.run_record)
    if args.hours is not None and not 1 <= args.hours <= LOOKBACK_MAX_HOURS:
        parser.error(f"hours must be 1..{LOOKBACK_MAX_HOURS}")
    if not 1 <= args.retention_days <= 31:
        parser.error("retention-days must be 1..31")
    now = (now or datetime.now(timezone.utc)).astimezone(timezone.utc)
    last_success, source = read_last_success(args.status, args.history_dir)
    capped = False
    if args.hours is not None:
        window, source = timedelta(hours=args.hours), "explicit"
    elif args.auto_window:
        window, capped = lookback_window(now, last_success)
    else:
        window, source = timedelta(hours=LOOKBACK_MIN_HOURS), "default"
    beginning = now - window
    print(f"Query window {iso_utc(beginning)} -> {iso_utc(now)} ({window.total_seconds() / 3600:.2f} h, "
          f"source={source}, capped={capped}, last successful scan end={iso_utc(last_success) if last_success else 'none'})",
          file=sys.stderr)
    unparsed, retries = [], None
    try:
        incoming, product_count, names, unparsed, retries = unpack_download(download(beginning, now))
        check_unparsed(unparsed, names, beginning, now)
        incoming, outside_window = split_by_window(incoming, beginning, now)
        existing = read_previous(args.out)
        result = assemble(existing, incoming, now, retention_days=args.retention_days)
        record = build_run_record(
            now=now, beginning=beginning, lookback_source=source, lookback_capped=capped,
            last_success_before=last_success, product_names=names, products_examined=product_count,
            incoming=incoming, existing=existing, feed=result, unparsed=unparsed, retries=retries,
        )
        record["outside_window"] = outside_window
    except Exception as error:  # noqa: BLE001 - the record must name any failure
        if isinstance(error, DownloadOutage):
            unparsed, retries = error.unparsed, error.retries
        if args.run_record:
            write_json(args.run_record, {
                "schema": RUN_RECORD_SCHEMA, "run_utc": iso_utc(now), "outcome": "failure",
                "error": f"{type(error).__name__}: {error}", "query_start_utc": iso_utc(beginning),
                "query_end_utc": iso_utc(now), "lookback_hours": round(window.total_seconds() / 3600, 4),
                "lookback_source": source, "lookback_capped": capped,
                "last_successful_scan_end_utc_before_run": iso_utc(last_success) if last_success else None,
                "products_examined": 0, "products_unparsed": len(unparsed), "unparsed_products": unparsed,
                "download_retries": retries, "scanned_ranges": [], "features": [],
            })
        raise
    # Refresh provenance only when a successful query returned product files.
    meta = result["metadata"]
    meta["products_examined"] = product_count
    meta["slots_examined"] = record["slots_examined"]
    meta["products_unparsed"] = record["products_unparsed"]
    meta["download_retries"] = record["download_retries"]["retries"]
    meta["query_start_utc"] = iso_utc(beginning)
    meta["query_end_utc"] = iso_utc(now)
    meta["scan_end_utc"] = record["scanned_end_utc"]
    meta["published_at_utc"] = iso_utc(now)
    meta["first_detection_utc"] = result["features"][0]["properties"]["time_utc"] if result["features"] else None
    meta["last_detection_utc"] = meta["latest_detection_utc"]
    meta["coverage_note"] = ("query_start/end are the last search window only; earlier hours of the "
                             "7-day retention were searched by earlier runs or not at all (see data/history/index.json)")
    write_json(args.out, result)
    if args.run_record:
        write_json(args.run_record, record)
    print(f"Published {len(result['features'])} genuine optical flashes from {product_count} EUMETSAT products "
          f"({record['slots_examined']} slots examined, {len(record['unscanned_ranges'])} gaps, "
          f"tail unobserved {record['tail_unobserved_seconds']} s, "
          f"{record['products_unparsed']} unparsed product(s), {record['download_retries']['retries']} download retries).")
    return 0


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

Grid

A Python command-line tool in Lightning that reads yyyy mm, using SHA-256. It refreshes grids (`refresh_grids`) and verifies grids (`verify_grids`).

ingestlightning / grid.py · lines 1–266 of 266 · Entry point · pattern cell_of (shared by 4 files)

What it does
It loads yyyy mm. Defines 11 functions or classes, including cell_of, row_digests, day_entry, day_cells, month_content. Uses libraries __future__, argparse, json, math, re. Side effects: reads or writes files.
Why it exists in the grid workflow
README: "`grid.py` and `data/history/grid/YYYY-MM.json` (`uk-lightning-history-grid.v1`): per-month counts of archived optical flashes per 0.1° cell per UTC day, regenerated with the archive, so a whole-year density view sums from at most 13 small files"
Inputs & outputs
In: JSON file YYYY-MM.json; JSON file index.json; command-line arguments.
Downstream impact
Used directly by 10 files: Verify Lightning Data Workflow (lightning); CI Verify Data (lightning); Test Backfill Parallel (lightning); Test Backfill Workflow (lightning); and 6 more. Reached from 17 other entry points, including Backfill Lightning Workflow (lightning); Backfill Parallel Lightning Workflow (lightning); Test Lightning Workflow (lightning).
What it achieves
Per-month density grid derived from the one-year archive's day shards. It accepts `--archive-dir` and `--deep`.
Why it matters
Imported by CI Verify Data and History. Run by Verify Lightning Data Workflow. Checked by 7 tests, including Test Backfill Parallel.
Application
lightning · / · Python CLI
Uses
Collect (import), History (import), __future__, argparse, json, math, re, sys, datetime, pathlib
Used by
run by Verify Lightning Data Workflow (workflow run), imported by CI Verify Data (import), run by Test Backfill Parallel (script call), run by Test Backfill Workflow (script call), run by Test CI Verify (script call), run by Test Concurrent Writers (script call), imported by Test Grid (import), imported by Test Reproduce (import), and 2 more
Produces
cell_of, row_digests, day_entry, day_cells, month_content, parse_grid, grid_path, refresh_grids, verify_grids, main
Defines here
cell_of, row_digests, day_entry, day_cells, month_content, parse_grid, grid_path, _month_rows, refresh_grids, verify_grids, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
lightning@2882145e28a0412de3a5bcfa40a12d7cd894ba90 grid.py:1-266 · blob 62b6e81596129de16823c42c0cff94920f05f272 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: unknown · users: none · canonical: unknown
#!/usr/bin/env python3
"""Per-month density grid derived from the one-year archive's day shards.

``data/history/grid/YYYY-MM.json`` (schema ``uk-lightning-history-grid.v1``)
holds, for one UTC calendar month, the number of archived optical flashes in
each 0.1-degree cell on each UTC day. Any UTC-day window therefore sums
exactly from at most 13 small files instead of hundreds of thousands of
points.

Contract:
- the grid is a pure function of the index rows and shard files of its month
  (no timestamps of its own), so an unchanged month is byte-identical;
- ``days`` lists every UTC date of the month inside retention (cutoff..today)
  with the index row's ``coverage``, ``count`` and the shard ``sha256`` list it
  was built from. A client compares those with the current index: a day whose
  row differs is STALE and must be treated as unknown, never as zero;
- ``count`` null (coverage none, or shard_lost) means never searched: unknown,
  not zero. Such days contribute no cells;
- each day's cell counts sum exactly to its row ``count``;
- ``cells`` is ``[[cell, day, n, day, n, ...], ...]`` sorted by cell then day,
  where ``cell = row * COLS + col``, ``col = floor((lon - WEST) / 0.1)``,
  ``row = floor((lat - SOUTH) / 0.1)`` (clamped to the grid) and ``day`` is
  the day of the month (1-31).

An observed flash is NOT a proven cloud-to-ground strike, and a cell count is
a density of OBSERVED optical flashes, not of ground strikes.
"""
from __future__ import annotations

import argparse
import json
import math
import re
import sys
from datetime import date
from pathlib import Path

from collect import UK_BOUNDS
from history import SCHEMA_INDEX, _load_old_index, _read_features, _serialise, _write_if_changed

SCHEMA_GRID = "uk-lightning-history-grid.v1"
CELL_DEG = 0.1
WEST, SOUTH, EAST, NORTH = UK_BOUNDS
COLS = int(round((EAST - WEST) / CELL_DEG))   # 140
ROWS = int(round((NORTH - SOUTH) / CELL_DEG))  # 120
GRID_DIR = "grid"
MONTH_PATTERN = re.compile(r"^(\d{4})-(\d{2})\.json$")
GRID_NOTE = (
    "Counts of archived satellite OPTICAL lightning flashes per 0.1-degree cell (about 7 x 11 km) per UTC day; "
    "not ground strikes. Days with count null were never searched: unknown, not zero. A day whose coverage, "
    "count or sha256 differs from the current index is stale and must be treated as unknown."
)


def cell_of(lon: float, lat: float) -> int:
    """Grid cell index of a coordinate (rounded first, so 0.1-steps never fall into the cell below)."""
    col = math.floor(round((lon - WEST) / CELL_DEG, 6))
    row = math.floor(round((lat - SOUTH) / CELL_DEG, 6))
    col = min(max(col, 0), COLS - 1)
    row = min(max(row, 0), ROWS - 1)
    return row * COLS + col


def row_digests(row: dict) -> list[str]:
    if row.get("path"):
        return [row.get("sha256") or ""]
    return [p.get("sha256") or "" for p in row.get("parts") or []]


def day_entry(row: dict) -> dict:
    return {"date": row["date"], "coverage": row.get("coverage"), "count": row.get("count"),
            "sha256": row_digests(row)}


def day_cells(archive_dir: Path, row: dict) -> dict[int, int]:
    """Cell counts of one indexed day, read from its shard file(s); must sum to the row count."""
    cells: dict[int, int] = {}
    if not row.get("count"):
        return cells
    files = [row["path"]] if row.get("path") else [p["path"] for p in row.get("parts") or []]
    total = 0
    for rel in files:
        for feature in _read_features(Path(archive_dir) / rel, row["date"]):
            lon, lat = feature["geometry"]["coordinates"][:2]
            key = cell_of(float(lon), float(lat))
            cells[key] = cells.get(key, 0) + 1
            total += 1
    if total != row["count"]:
        raise ValueError(f"{row['date']}: shards hold {total} flashes but the index count is {row['count']}")
    return cells


def month_content(month: str, entries: list[dict], cells_by_day: dict[str, dict[int, int]]) -> str:
    by_cell: dict[int, list[int]] = {}
    for entry in entries:
        dom = int(entry["date"][8:10])
        for cell, n in cells_by_day.get(entry["date"], {}).items():
            by_cell.setdefault(cell, []).extend((dom, n))
    cells = []
    for cell in sorted(by_cell):
        pairs = by_cell[cell]
        ordered = sorted(zip(pairs[0::2], pairs[1::2]))
        cells.append([cell] + [v for pair in ordered for v in pair])
    return _serialise({
        "schema": SCHEMA_GRID,
        "month": month,
        "observation": "satellite optical lightning flashes, not ground strikes",
        "bounds_wsen": list(UK_BOUNDS),
        "cell_deg": CELL_DEG,
        "cols": COLS,
        "rows": ROWS,
        "cell_rule": "cell=row*cols+col; col=floor((lon-west)/cell_deg); row=floor((lat-south)/cell_deg); clamped",
        "note": GRID_NOTE,
        "total": sum(e["count"] or 0 for e in entries),
        "days": entries,
        "cells": cells,
    })


def parse_grid(text: str, month: str) -> tuple[list[dict], dict[str, dict[int, int]]]:
    """Validate a grid file and return (days, per-day cell counts)."""
    data = json.loads(text)
    if not isinstance(data, dict) or data.get("schema") != SCHEMA_GRID or data.get("month") != month:
        raise ValueError(f"grid {month}: schema or month mismatch")
    if data.get("cols") != COLS or data.get("rows") != ROWS or data.get("cell_deg") != CELL_DEG:
        raise ValueError(f"grid {month}: geometry mismatch")
    entries = data.get("days")
    if not isinstance(entries, list):
        raise ValueError(f"grid {month}: invalid days")
    by_dom = {}
    for e in entries:
        if not isinstance(e, dict) or not str(e.get("date", "")).startswith(month + "-"):
            raise ValueError(f"grid {month}: invalid day entry")
        by_dom[int(e["date"][8:10])] = e["date"]
    cells_by_day: dict[str, dict[int, int]] = {}
    for item in data.get("cells") or []:
        if not isinstance(item, list) or len(item) < 3 or len(item) % 2 != 1:
            raise ValueError(f"grid {month}: invalid cell row")
        cell = item[0]
        if not isinstance(cell, int) or not 0 <= cell < COLS * ROWS:
            raise ValueError(f"grid {month}: cell out of range")
        for dom, n in zip(item[1::2], item[2::2]):
            if dom not in by_dom or not isinstance(n, int) or n < 1:
                raise ValueError(f"grid {month}: invalid day count")
            cells_by_day.setdefault(by_dom[dom], {})[cell] = n
    for e in entries:
        if sum(cells_by_day.get(e["date"], {}).values()) != (e.get("count") or 0):
            raise ValueError(f"grid {month}: {e['date']} cells do not sum to its count")
    return entries, cells_by_day


def grid_path(month: str) -> str:
    return f"{GRID_DIR}/{month}.json"


def _month_rows(index: dict) -> dict[str, list[dict]]:
    months: dict[str, list[dict]] = {}
    for row in index.get("days") or []:
        if isinstance(row, dict) and isinstance(row.get("date"), str):
            months.setdefault(row["date"][:7], []).append(row)
    return months


def refresh_grids(archive_dir: Path, index: dict) -> dict:
    """Bring every month grid in line with ``index``; re-read only days whose row changed.

    Months outside retention are removed. Returns {"written": [...], "removed": [...], "unchanged": n,
    "days_read": n}.
    """
    archive_dir = Path(archive_dir)
    if index.get("schema") != SCHEMA_INDEX:
        raise ValueError("grid: index schema mismatch")
    grid_dir = archive_dir / GRID_DIR
    written, removed, unchanged, days_read = [], [], 0, 0
    months = _month_rows(index)
    for month, rows in sorted(months.items()):
        target = archive_dir / grid_path(month)
        old_entries, old_cells = [], {}
        if target.exists():
            try:
                old_entries, old_cells = parse_grid(target.read_text(encoding="utf-8"), month)
            except (ValueError, KeyError, TypeError, json.JSONDecodeError):
                old_entries, old_cells = [], {}  # invalid: rebuilt from the shards
        old_by_date = {e["date"]: e for e in old_entries}
        entries, cells_by_day = [], {}
        for row in sorted(rows, key=lambda r: r["date"]):
            entry = day_entry(row)
            entries.append(entry)
            if not entry["count"]:
                continue
            if old_by_date.get(entry["date"]) == entry:
                cells_by_day[entry["date"]] = old_cells.get(entry["date"], {})
            else:
                cells_by_day[entry["date"]] = day_cells(archive_dir, row)
                days_read += 1
        if _write_if_changed(target, month_content(month, entries, cells_by_day)):
            written.append(grid_path(month))
        else:
            unchanged += 1
    if grid_dir.exists():
        for f in sorted(grid_dir.iterdir()):
            m = MONTH_PATTERN.fullmatch(f.name)
            if f.is_file() and (not m or f.name[:7] not in months):
                f.unlink()
                removed.append(f"{GRID_DIR}/{f.name}")
        if not any(grid_dir.iterdir()):
            grid_dir.rmdir()
    return {"written": written, "removed": removed, "unchanged": unchanged, "days_read": days_read}


def verify_grids(archive_dir: Path, index: dict | None = None, *, deep: bool = False) -> dict:
    """Strict check: one grid per index month whose days equal the index rows.

    ``deep`` also recounts every day from its shards.
    """
    archive_dir = Path(archive_dir)
    index = index or _load_old_index(archive_dir / "index.json")
    if index is None:
        raise ValueError("no index.json")
    months = _month_rows(index)
    checked = 0
    for month, rows in sorted(months.items()):
        target = archive_dir / grid_path(month)
        if not target.exists():
            raise ValueError(f"{target}: missing")
        entries, cells = parse_grid(target.read_text(encoding="utf-8"), month)
        expected = [day_entry(r) for r in sorted(rows, key=lambda r: r["date"])]
        if entries != expected:
            raise ValueError(f"{target}: days differ from the index (stale grid)")
        if deep:
            for row in rows:
                if (cells.get(row["date"]) or {}) != day_cells(archive_dir, row):
                    raise ValueError(f"{target}: {row['date']} cells differ from its shards")
        checked += 1
    extra = sorted(f.name for f in (archive_dir / GRID_DIR).glob("*.json") if f.name[:7] not in months) \
        if (archive_dir / GRID_DIR).exists() else []
    if extra:
        raise ValueError(f"grid files outside retention: {extra}")
    return {"months": checked}


def main(argv=None) -> int:
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    sub = parser.add_subparsers(dest="command", required=True)
    build = sub.add_parser("build", help="(Re)generate every month grid from the index and shards (idempotent)")
    build.add_argument("--archive-dir", type=Path, default=Path("data/history"))
    check = sub.add_parser("verify", help="Check every month grid against the index")
    check.add_argument("--archive-dir", type=Path, default=Path("data/history"))
    check.add_argument("--deep", action="store_true", help="Also recount every day from its shards")
    args = parser.parse_args(argv)
    index = _load_old_index(args.archive_dir / "index.json")
    if index is None:
        raise SystemExit("no index.json")
    if args.command == "build":
        print(json.dumps(refresh_grids(args.archive_dir, index)))
    else:
        print(json.dumps(verify_grids(args.archive_dir, index, deep=args.deep)))
    return 0


if __name__ == "__main__":
    try:
        raise SystemExit(main())
    except ValueError as error:
        print(f"GRID FAILURE: {error}", file=sys.stderr)
        raise SystemExit(2)