"""Walking-network round: the parent's straight-line measure against a walking-network measure of the same thing.

Only the distance changes. Region, census, allocation, stops, both-directions rule and baseline come from the parent's frozen
code and files. Offline: every input is a hashed file. Fixed by DESIGN-walk-network.md and walk-protocol.json.
"""
import argparse
import csv
from collections import defaultdict
import gzip
import hashlib
import heapq
import json
import math
from pathlib import Path
import sys

import numpy as np
from pyproj import Transformer
from scipy.sparse import coo_matrix, csr_matrix
from scipy.sparse.csgraph import connected_components, dijkstra
from scipy.spatial import cKDTree
import shapely

STUDY = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(STUDY / "src"))

from coverage import assign_ranks, load_schedule_inputs, qualifying_points  # noqa: E402
from frequency_sensitivity import membership_qualifying_points, read_tables, stop_pooled_events  # noqa: E402
from gtfs import gtfs_time  # noqa: E402
from region import digest, load_region  # noqa: E402

SOURCE_DIR = "data/walk-network-source"
ROUTES = ("14", "26", "39")
RULES = ("strict", "stop_pooled")
UNIFORM, POINT = "uniform_land_area", "all_at_representative_land_point"


def load_protocol(root=STUDY):
    return json.loads((Path(root) / "walk-protocol.json").read_text(encoding="utf-8"))


def read_snapshot(path):
    with gzip.open(path, "rt", encoding="utf-8") as lines:
        return [json.loads(line) for line in lines]


def walkable(tags, variant, network):
    """Decide whether one way can be walked under one declared network variant."""
    highway = tags.get("highway")
    if highway is None or highway in network["not_built"] or highway in network["motorway"]:
        return False
    foot, access = tags.get("foot"), tags.get("access")
    if variant != "generous":
        if foot == "no":
            return False
        if access in network["access_blocks"] and foot not in network["foot_allows"]:
            return False
    if variant == "no_trunk" and highway in network["trunk"]:
        sidewalks = (tags.get(key) for key in ("sidewalk", "sidewalk:both", "sidewalk:left", "sidewalk:right"))
        if foot not in ("yes", "designated") and not any(value in network["sidewalk_present"] for value in sidewalks):
            return False
    if variant == "roads_only" and highway in network["path_like"]:
        return False
    return True


class Network:
    """Undirected walking graph, subdivided, restricted to its largest connected component."""

    def __init__(self, ways, variant, protocol, length_scale=1.0):
        spec = protocol["network"]
        step = spec["subdivide_m"]
        projection = Transformer.from_crs(4326, 26910, always_xy=True)
        ids, xs, ys, us, vs, weights = {}, [], [], [], [], []

        def add(x, y):
            xs.append(x)
            ys.append(y)
            return len(xs) - 1

        self.way_count = 0
        self.way_length_m = {}
        for way in ways:
            if not walkable(way["tags"], variant, spec):
                continue
            self.way_count += 1
            lon, lat = zip(*way["coords"])
            px, py = projection.transform(lon, lat)
            previous = None
            total = 0.0
            for node, x, y in zip(way["nodes"], px, py):
                current = ids.get(node)
                if current is None:
                    current = ids[node] = add(x, y)
                if previous is not None and previous != current:
                    x0, y0 = xs[previous], ys[previous]
                    length = math.hypot(x - x0, y - y0)
                    total += length
                    parts = max(1, math.ceil(length / step))
                    last = previous
                    for k in range(1, parts):
                        interior = add(x0 + (x - x0) * k / parts, y0 + (y - y0) * k / parts)
                        us.append(last)
                        vs.append(interior)
                        weights.append(length / parts)
                        last = interior
                    us.append(last)
                    vs.append(current)
                    weights.append(max(length / parts, 1e-3))
                previous = current
            self.way_length_m[way["id"]] = total
        if not us:
            raise ValueError("No walkable network")
        u, v, w = np.array(us), np.array(vs), np.array(weights) * length_scale
        low, high = np.minimum(u, v), np.maximum(u, v)
        order = np.lexsort((w, high, low))
        low, high, w = low[order], high[order], w[order]
        keep = np.r_[True, (low[1:] != low[:-1]) | (high[1:] != high[:-1])]
        low, high, w = low[keep], high[keep], w[keep]
        count = len(xs)
        graph = coo_matrix((np.r_[w, w], (np.r_[low, high], np.r_[high, low])), shape=(count, count)).tocsr()
        _, labels = connected_components(graph, directed=False)
        lengths = np.bincount(labels[low], weights=w)
        main = int(np.argmax(lengths))
        self.total_length_m = float(lengths.sum())
        self.main_length_m = float(lengths[main])
        self.component_share = self.main_length_m / self.total_length_m
        self.xy = np.column_stack((xs, ys))
        self.in_main = labels == main
        self.graph = graph
        self.node_count = count
        self.osm_index = ids
        self.main_nodes = np.flatnonzero(self.in_main)
        self.tree = cKDTree(self.xy[self.main_nodes])

    def snap(self, xy):
        distance, index = self.tree.query(xy)
        return self.main_nodes[index], distance

    def describe(self):
        return {"ways": self.way_count, "length_km": self.total_length_m / 1000, "main_length_km": self.main_length_m / 1000,
                "component_share": self.component_share, "nodes": self.node_count}


class Field:
    """Land points carrying population: a lattice for uniform allocation, one point per area for point allocation."""

    def __init__(self, areas, universe_xy, cell, reach):
        tree = cKDTree(universe_xy)
        low = np.floor((universe_xy.min(axis=0) - reach - cell) / cell) * cell + cell / 2
        high = universe_xy.max(axis=0) + reach + cell
        gx, gy = np.meshgrid(np.arange(low[0], high[0], cell), np.arange(low[1], high[1], cell))
        lattice = np.column_stack((gx.ravel(), gy.ravel()))
        near, _ = tree.query(lattice, distance_upper_bound=reach + 1)
        lattice = lattice[np.isfinite(near)]
        included = [area for area in areas if area["exclusion"] is None]
        polygons = [area["regional"] for area in included]
        index = shapely.STRtree(polygons)
        points = shapely.points(lattice)
        point_ids, polygon_ids = index.query(points, predicate="within")
        first = np.full(len(lattice), -1)
        first[point_ids[::-1]] = polygon_ids[::-1]
        mask = first >= 0
        lattice, owner = lattice[mask], first[mask]
        share = np.array([cell * cell / area["land"].area for area in included])
        population = np.array([float(area["population"]) for area in included])
        self.cell = cell
        self.uids = [area["da_uid"] for area in included]
        self.population = population
        self.land_area = np.array([area["land"].area for area in included])
        self.grid_owner = owner
        self.grid_share = share[owner]
        rep = np.array([[area["representative"].x, area["representative"].y] for area in included])
        rep_in = np.array([area["point_regional_population"] > 0 for area in included])
        self.rep_owner = np.arange(len(included))
        self.rep_valid = rep_in
        self.xy = np.vstack((lattice, rep))
        self.owner = np.r_[owner, self.rep_owner]
        self.grid_count = len(lattice)
        self.region_total = sum(area["uniform_regional_population"] for area in included)

    def weights(self, allocation, population=None):
        population = self.population if population is None else population
        out = np.zeros(len(self.xy))
        if allocation == UNIFORM:
            out[: self.grid_count] = population[self.grid_owner] * self.grid_share
        else:
            out[self.grid_count:] = population * self.rep_valid
        return out


def straight_distance(field_xy, stop_xy, reach):
    distance, _ = cKDTree(np.array(stop_xy)).query(field_xy, distance_upper_bound=reach + 1)
    return distance.astype(np.float32)


def network_distances(network, field_xy, stop_sets, reach):
    """One array per stop set: access from the point, shortest path, access to the stop. Virtual sources keep it exact."""
    keys = sorted(stop_sets)
    n, k = network.node_count, len(keys)
    rows, cols, weights = [], [], []
    for offset, key in enumerate(keys):
        nodes, access = network.snap(np.array(key))
        best = {}
        for node, value in zip(nodes.tolist(), access.tolist()):
            best[node] = min(best.get(node, math.inf), value)
        for node, value in best.items():
            rows.append(n + offset)
            cols.append(node)
            weights.append(max(value, 1e-3))
    graph = coo_matrix((weights, (rows, cols)), shape=(n + k, n + k)).tocsr()
    base = network.graph
    combined = csr_matrix((n + k, n + k))
    combined = (graph + coo_matrix((base.data, base.nonzero()), shape=(n + k, n + k)).tocsr()).tocsr()
    field_nodes, field_access = network.snap(field_xy)
    result = {}
    for offset, key in enumerate(keys):
        walked = dijkstra(combined, directed=True, indices=n + offset, limit=reach)
        result[key] = (walked[field_nodes] + field_access).astype(np.float32)
    return result, field_access.astype(np.float32)


def stop_groups(root, contract, manifest):
    """The parent's stop sets: strict and every-route, per gap, plus the three corridors. Coordinates are stop identity."""
    schedule, stops, candidates = load_schedule_inputs(root, contract, manifest)
    start, end = gtfs_time(contract["service"]["window_start"]), gtfs_time(contract["service"]["window_end"])
    pooled, _ = stop_pooled_events(schedule["events"])
    groups = {}
    for gap in (900, 1200):
        groups["strict", gap] = qualifying_points(schedule["events"], stops, gap, start, end)[0]
        groups["stop_pooled", gap] = membership_qualifying_points(pooled, stops, gap, start, end)[0]
    corridors = {candidate["route"]: {d: sorted(points) for d, points in candidate["points"].items()} for candidate in candidates}
    return groups, corridors, stops, schedule


def set_key(points):
    return tuple(sorted(points))


def all_sets(groups, corridors, wanted=None):
    out = set()
    for key, routes in groups.items():
        if wanted is not None and key not in wanted:
            continue
        for directions in routes.values():
            out.update(set_key(points) for points in directions.values())
    for directions in corridors.values():
        out.update(set_key(points) for points in directions.values())
    return out


def covered(directions, distance, limit):
    if not {"0", "1"} <= set(directions):
        return None
    return (distance[set_key(directions["0"])] <= limit) & (distance[set_key(directions["1"])] <= limit)


def baseline_mask(routes, distance, limit, size):
    mask = np.zeros(size, dtype=bool)
    for directions in routes.values():
        one = covered(directions, distance, limit)
        if one is not None:
            mask |= one
    return mask


def case_counts(groups, corridors, distance, limit, gap, rule, weights):
    size = len(weights)
    base = baseline_mask(groups[rule, gap], distance, limit, size)
    counts = {route: float(weights[covered(corridors[route], distance, limit) & ~base].sum()) for route in ROUTES}
    return float(weights[base].sum()), counts


def frozen_tables(root):
    manifest = json.loads((root / "data/frequency-sensitivity-manifest.json").read_text(encoding="utf-8"))
    folder = root / manifest["directory"]
    with (folder / "pooled-sensitivity.csv").open(encoding="utf-8") as handle:
        rows = list(csv.DictReader(handle))
    with (folder / "pooled-baseline.csv").open(encoding="utf-8") as handle:
        bases = list(csv.DictReader(handle))
    return rows, bases


def plain_python_distances(network, sources, limit):
    """A second shortest-path routine, on the same graph, for the independent check. Sources: {node: start distance}."""
    graph = network.graph
    best = dict(sources)
    heap = [(value, node) for node, value in sources.items()]
    heapq.heapify(heap)
    while heap:
        value, node = heapq.heappop(heap)
        if value > best.get(node, math.inf):
            continue
        for position in range(graph.indptr[node], graph.indptr[node + 1]):
            other, step = int(graph.indices[position]), float(graph.data[position])
            candidate = value + step
            if candidate <= limit and candidate < best.get(other, math.inf):
                best[other] = candidate
                heapq.heappush(heap, (candidate, other))
    return best


def same_count_radius(groups, corridors, straight, weights, target, scan):
    """The smallest scanned radius whose straight-line count reaches the walking count, per corridor."""
    size = len(weights)
    radii = list(range(scan["scan_from_m"], scan["scan_to_m"] + 1, scan["step_m"]))
    curves = {}
    for route in ROUTES:
        curve = []
        for radius in radii:
            base = baseline_mask(groups["strict", 900], straight, radius, size)
            curve.append(float(weights[covered(corridors[route], straight, radius) & ~base].sum()))
        curves[route] = curve
    found = {}
    for route in ROUTES:
        found[route] = next((radius for radius, value in zip(radii, curves[route]) if value >= target[route]), None)
    out = {"radii_m": radii, "curves": curves, "radius_m": found, "leave_one_out": []}
    for route in ROUTES:
        others = [found[r] for r in ROUTES if r != route]
        radius = int(round(sum(others) / len(others) / scan["step_m"]) * scan["step_m"])
        predicted = curves[route][radii.index(radius)]
        out["leave_one_out"].append({"route": route, "radius_from_other_two_m": radius, "predicted_residents": predicted,
                                     "walking_residents": target[route],
                                     "error_share": (predicted - target[route]) / target[route]})
    return out


def write_csv(path, rows):
    with path.open("x", encoding="utf-8", newline="") as handle:
        writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n")
        writer.writeheader()
        writer.writerows(rows)


def snapshot_path(root, date):
    return Path(root) / SOURCE_DIR / ("osm-" + date[:10] + ".jsonl.gz")


def land_and_barriers(areas, ways, spec):
    projection = Transformer.from_crs(4326, 26910, always_xy=True)
    land = shapely.union_all([area["regional"] for area in areas if area["exclusion"] is None]).buffer(2)
    shapely.prepare(land)
    barriers = []
    for way in ways:
        tags = way["tags"]
        if tags.get("highway") in spec["motorway"] or tags.get("foot") == "no":
            lon, lat = zip(*way["coords"])
            if len(lon) >= 2:
                barriers.append(shapely.LineString(np.column_stack(projection.transform(lon, lat))))
    return land, shapely.STRtree(barriers), barriers


def compute(root=STUDY):
    root = Path(root).resolve()
    protocol = load_protocol(root)
    contract = json.loads((root / "analysis-contract.json").read_text(encoding="utf-8"))
    manifest = json.loads((root / "data/manifest.json").read_text(encoding="utf-8"))
    _region, _water, areas, _census = load_region(root)
    groups, corridors, stops, _schedule = stop_groups(root, contract, manifest)
    tables = read_tables(root, manifest)
    grid = protocol["grid"]
    reach = grid["reach_limit_m"]
    sets_all = all_sets(groups, corridors)
    universe = np.array(sorted({point for key in sets_all for point in key}))
    field = Field(areas, universe, grid["cell_m"], reach)
    uniform, point = field.weights(UNIFORM), field.weights(POINT)
    print("grid points", field.grid_count, "uniform weight in reach", round(uniform.sum()), flush=True)

    main_ways = read_snapshot(snapshot_path(root, protocol["overpass"]["main_date"]))
    network = Network(main_ways, "main", protocol)
    print("network", network.describe(), flush=True)
    straight = {key: straight_distance(field.xy, key, reach) for key in sets_all}
    walked, access = network_distances(network, field.xy, sets_all, reach)
    print("distances done", len(walked), flush=True)

    # Monotonic: walking can never be shorter than the straight line.
    violations = 0
    for key in sets_all:
        finite = np.isfinite(walked[key]) & np.isfinite(straight[key])
        violations += int((walked[key][finite] + protocol["refresh_checks"]["monotonic_tolerance_m"] < straight[key][finite]).sum())

    frozen_rows, frozen_bases = frozen_tables(root)
    frozen = {(int(r["buffer_meters"]), int(r["headway_seconds"]), r["allocation"], r["route"]): r for r in frozen_rows}
    frozen_base = {(int(r["buffer_meters"]), int(r["headway_seconds"]), r["allocation"]): r for r in frozen_bases}
    states = protocol["states"]
    cases, baselines, reproduction = [], [], []
    for limit in states["distance_m"]:
        for gap in states["gap_s"]:
            for rule in states["rule"]:
                for allocation in states["allocation"]:
                    weights = uniform if allocation == UNIFORM else point
                    line_base, line = case_counts(groups, corridors, straight, limit, gap, rule, weights)
                    walk_base, walk = case_counts(groups, corridors, walked, limit, gap, rule, weights)
                    prefix = "strict" if rule == "strict" else "stop_pooled"
                    frozen_line = {r: float(frozen[limit, gap, allocation, r][prefix + "_incremental_covered"]) for r in ROUTES}
                    frozen_b = float(frozen_base[limit, gap, allocation][prefix + "_baseline_covered"])
                    relative = protocol["reproduction"]["uniform_relative" if allocation == UNIFORM else "point_relative"]
                    absolute = protocol["reproduction"]["uniform_absolute" if allocation == UNIFORM else "point_absolute"]
                    state = []
                    for route in ROUTES:
                        difference = abs(line[route] - frozen_line[route])
                        passes = difference <= max(relative * frozen_line[route], absolute)
                        reproduction.append({"distance_m": limit, "gap_s": gap, "rule": rule, "allocation": allocation, "route": route,
                                             "frozen": frozen_line[route], "grid_straight": line[route], "difference": difference,
                                             "passes": passes})
                        state.append({"distance_m": limit, "gap_s": gap, "rule": rule, "allocation": allocation, "route": route,
                                      "frozen_straight": frozen_line[route], "grid_straight": line[route], "walking": walk[route],
                                      "retained_share": walk[route] / line[route] if line[route] else None})
                    assign_ranks(state, "grid_straight", "rank_straight")
                    assign_ranks(state, "walking", "rank_walking")
                    cases.extend(state)
                    baselines.append({"distance_m": limit, "gap_s": gap, "rule": rule, "allocation": allocation,
                                      "frozen_straight": frozen_b, "grid_straight": line_base, "walking": walk_base,
                                      "retained_share": walk_base / line_base if line_base else None})
    print("cases", len(cases), "reproduction passes", sum(r["passes"] for r in reproduction), "of", len(reproduction), flush=True)

    # Which areas: the union of the baseline and all three corridors, main case.
    limit, gap = protocol["main_state"]["distance_m"], protocol["main_state"]["gap_s"]
    def union_mask(distance):
        mask = baseline_mask(groups["strict", gap], distance, limit, len(uniform))
        for route in ROUTES:
            mask |= covered(corridors[route], distance, limit)
        return mask
    line_union, walk_union = union_mask(straight), union_mask(walked)
    lost = line_union & ~walk_union
    union_stops = np.array(sorted({p for routes in groups["strict", gap].values() for points in routes.values() for p in points}
                                  | {p for directions in corridors.values() for points in directions.values() for p in points}))
    land, barrier_tree, barriers = land_and_barriers(areas, main_ways, protocol["network"])
    lost_ids = np.flatnonzero(lost & (uniform > 0))
    _, nearest = cKDTree(union_stops).query(field.xy[lost_ids])
    segments = shapely.linestrings(np.stack((field.xy[lost_ids], union_stops[nearest]), axis=1))
    leaves = ~shapely.covers(land, segments)
    crossing = np.zeros(len(lost_ids), dtype=bool)
    seg_ids, _ = barrier_tree.query(segments, predicate="intersects")
    crossing[np.unique(seg_ids)] = True
    far = access[lost_ids] > protocol["far_from_network_m"]
    cause = np.full(len(lost_ids), 3)
    cause[far] = 2
    cause[crossing] = 1
    cause[leaves] = 0
    # first match wins: water, then excluded road, then far from the network, then street layout
    names = protocol["causes"]
    cause_totals = {names[i]: float(uniform[lost_ids[cause == i]].sum()) for i in range(4)}
    cause_by_owner = defaultdict(lambda: [0.0, 0.0, 0.0, 0.0])
    for idx, kind in zip(lost_ids, cause):
        cause_by_owner[int(field.owner[idx])][int(kind)] += float(uniform[idx])

    source = root / SOURCE_DIR
    da_csd = json.loads((source / "da-to-csd.json").read_text(encoding="utf-8"))
    per_da = []
    for position, uid in enumerate(field.uids):
        in_area = (field.owner == position)
        line_value = float(uniform[in_area & line_union].sum())
        walk_value = float(uniform[in_area & walk_union].sum())
        if line_value <= 0:
            continue
        kinds = cause_by_owner[position]
        per_da.append({"da_uid": uid, "csd_uid": da_csd[uid]["csd_uid"], "csd_name": da_csd[uid]["csd_name"],
                       "population": field.population[position], "straight_line_residents": line_value, "walking_residents": walk_value,
                       "lost_residents": line_value - walk_value, "retained_share": walk_value / line_value,
                       **{"lost_" + names[i]: kinds[i] for i in range(4)}})
    per_csd = defaultdict(lambda: {"straight_line_residents": 0.0, "walking_residents": 0.0, **{"lost_" + n: 0.0 for n in names}})
    for row in per_da:
        target = per_csd[row["csd_uid"], row["csd_name"]]
        target["straight_line_residents"] += row["straight_line_residents"]
        target["walking_residents"] += row["walking_residents"]
        for name in names:
            target["lost_" + name] += row["lost_" + name]
    per_area = [{"csd_uid": uid, "csd_name": name, **values, "lost_residents": values["straight_line_residents"] - values["walking_residents"],
                 "retained_share": values["walking_residents"] / values["straight_line_residents"]}
                for (uid, name), values in sorted(per_csd.items(), key=lambda item: -item[1]["straight_line_residents"])]

    # Per stop: how much of the circle's land a 400 metre walk reaches.
    names_by_id = {row["stop_id"]: row.get("stop_name", "") for row in tables["stops"]}
    id_by_point = defaultdict(list)
    for stop_id, xy in stops.items():
        id_by_point[xy].append(stop_id)
    field_nodes, field_access = network.snap(field.xy[: field.grid_count])
    grid_xy, grid_weight = field.xy[: field.grid_count], uniform[: field.grid_count]
    tree = cKDTree(grid_xy)
    per_stop = []
    roles = defaultdict(set)
    for route, directions in corridors.items():
        for points in directions.values():
            for p in points:
                roles[p].add("route " + route)
    for route, directions in groups["strict", gap].items():
        for points in directions.values():
            for p in points:
                roles[p].add("baseline")
    for p in sorted(roles):
        node, stop_access = network.snap(np.array([p]))
        dist = dijkstra(network.graph, directed=False, indices=int(node[0]), limit=limit)
        inside = np.array(tree.query_ball_point(p, limit))
        reached = (dist[field_nodes[inside]] + field_access[inside] + stop_access[0]) <= limit
        stop_ids = sorted(id_by_point[p])
        per_stop.append({"stop_id": stop_ids[0], "stop_name": names_by_id.get(stop_ids[0], ""), "serves": " + ".join(sorted(roles[p])),
                         "land_points_in_circle": int(len(inside)), "land_points_walked": int(reached.sum()),
                         "reachable_land_share": float(reached.mean()) if len(inside) else None,
                         "residents_in_circle": float(grid_weight[inside].sum()),
                         "residents_walked": float(grid_weight[inside][reached].sum()),
                         "snap_to_network_m": float(stop_access[0])})
    print("stops", len(per_stop), flush=True)

    # Same-count radius, against the walking counts of the main case.
    _, main_walk = case_counts(groups, corridors, walked, limit, gap, "strict", uniform)
    radius = same_count_radius(groups, corridors, straight, uniform, main_walk, protocol["same_count_radius"])

    # Worked example, picked mechanically after results: the corridor stop and point with the largest walking detour.
    worked = None
    for route in ROUTES:
        for direction, points in corridors[route].items():
            pass
    example_rows = sorted(per_da, key=lambda row: -row["lost_residents"])[:3]
    best = None
    for route in ROUTES:
        key = set_key(corridors[route]["0"])
        mask = (straight[key] <= limit) & np.isfinite(walked[key]) & (uniform > 0)
        ratio = np.where(mask, walked[key] / np.maximum(straight[key], 1), 0)
        idx = int(np.argmax(ratio))
        if best is None or ratio[idx] > best[0]:
            best = (float(ratio[idx]), idx, route)
    if best:
        idx, route = best[1], best[2]
        key = set_key(corridors[route]["0"])
        _, stop_index = cKDTree(np.array(key)).query(field.xy[idx])
        stop_xy = key[int(stop_index)]
        ids = sorted(id_by_point[stop_xy])
        worked = {"route": route, "stop_id": ids[0], "stop_name": names_by_id.get(ids[0], ""), "da_uid": field.uids[int(field.owner[idx])],
                  "straight_m": float(straight[key][idx]), "walking_m": float(walked[key][idx])}

    # Network variants, main case and every-route rule.
    wanted = {("strict", 900), ("stop_pooled", 900)}
    variant_sets = all_sets(groups, corridors, wanted)
    variants, descriptions = [], {"main": network.describe()}
    for variant in protocol["network"]["variants"]:
        if variant == "main":
            distances = walked
        else:
            other = Network(main_ways, variant, protocol)
            descriptions[variant] = other.describe()
            distances, _ = network_distances(other, field.xy, variant_sets, reach)
        for rule in RULES:
            base, counts = case_counts(groups, corridors, distances, limit, gap, rule, uniform)
            variants.append({"variant": variant, "rule": rule, "baseline": base, **{"route_" + r: counts[r] for r in ROUTES}})
    print("variants done", flush=True)

    # Drift: the same case on older maps, with the schedule and census held fixed.
    drift = []
    drift_sources = {protocol["overpass"]["main_date"]: None}
    snapshot_hashes = {protocol["overpass"]["main_date"][:10]: digest(snapshot_path(root, protocol["overpass"]["main_date"]))}
    for date in protocol["overpass"]["drift_dates"]:
        path = snapshot_path(root, date)
        if not path.exists():
            drift.append({"date": date[:10], "status": "not fetched"})
            continue
        snapshot_hashes[date[:10]] = digest(path)
        older = Network(read_snapshot(path), "main", protocol)
        distances, _ = network_distances(older, field.xy, variant_sets, reach)
        row = {"date": date[:10], "status": "run", **older.describe()}
        for rule in RULES:
            base, counts = case_counts(groups, corridors, distances, limit, gap, rule, uniform)
            row[rule + "_baseline"] = base
            for route in ROUTES:
                row[rule + "_route_" + route] = counts[route]
        drift.append(row)
        print("drift", date[:10], flush=True)
    main_row = {"date": protocol["overpass"]["main_date"][:10], "status": "run", **network.describe()}
    for rule in RULES:
        base, counts = case_counts(groups, corridors, walked, limit, gap, rule, uniform)
        main_row[rule + "_baseline"] = base
        for route in ROUTES:
            main_row[rule + "_route_" + route] = counts[route]
    drift.insert(0, main_row)

    # Grid stability at the finer cell.
    fine = Field(areas, universe, grid["fine_check_cell_m"], reach)
    fine_uniform = fine.weights(UNIFORM)
    keep_sets = all_sets({("strict", 900): groups["strict", 900]}, corridors)
    fine_walked, _ = network_distances(network, fine.xy, keep_sets, reach)
    _, fine_counts = case_counts({("strict", 900): groups["strict", 900]}, corridors, fine_walked, limit, gap, "strict", fine_uniform)
    stability = {"cell_m": grid["fine_check_cell_m"], "counts": fine_counts,
                 "relative_change": {route: abs(fine_counts[route] - main_walk[route]) / main_walk[route] for route in ROUTES}}
    print("stability", stability["relative_change"], flush=True)

    # A second shortest-path routine must match on three stop sets.
    python_check = []
    for route in ROUTES:
        key = set_key(corridors[route]["0"])
        nodes, stop_access = network.snap(np.array(key))
        sources = {}
        for node, value in zip(nodes.tolist(), stop_access.tolist()):
            sources[node] = min(sources.get(node, math.inf), max(value, 1e-3))
        best_dist = plain_python_distances(network, sources, limit)
        all_nodes, all_access = network.snap(field.xy)
        second = np.array([best_dist.get(int(node), math.inf) for node in all_nodes]) + all_access
        first = walked[key].astype(float)
        both = (first <= limit) | (second <= limit)
        python_check.append({"route": route, "points_compared": int(both.sum()),
                             "largest_difference_m": float(np.abs(first[both] - second[both]).max()) if both.any() else 0.0})
    print("python check", python_check, flush=True)

    # Router sample pairs and comparison, read only from the stored cache.
    router_pairs = make_router_pairs(protocol, field, uniform, line_union, union_stops, network)
    router = compare_router(root, protocol, network, router_pairs)

    result = {
        "schema_version": 1,
        "protocol_sha256": digest(root / "walk-protocol.json"),
        "design_sha256": digest(root / "DESIGN-walk-network.md"),
        "snapshot_sha256": snapshot_hashes,
        "region_population": field.region_total,
        "grid": {"cell_m": grid["cell_m"], "points": field.grid_count, "uniform_population_in_reach": float(uniform.sum())},
        "network": descriptions,
        "monotonic_violations": violations,
        "reproduction": {"rows": len(reproduction), "passes": sum(r["passes"] for r in reproduction),
                         "largest_difference": max(r["difference"] for r in reproduction),
                         "main": [r for r in reproduction if r["distance_m"] == limit and r["gap_s"] == gap and r["rule"] == "strict" and r["allocation"] == UNIFORM],
                         "failures": [r for r in reproduction if not r["passes"]]},
        "cases": cases, "baselines": baselines, "variants": variants, "drift": drift,
        "union": {"straight_line_residents": float(uniform[line_union].sum()), "walking_residents": float(uniform[walk_union].sum()),
                  "causes": cause_totals},
        "same_count_radius": radius, "stability": stability, "python_check": python_check, "router": router, "worked_example": worked,
        "largest_losses": example_rows,
    }
    tables_out = {"walk-cases.csv": cases, "walk-baselines.csv": baselines, "walk-areas.csv": per_area, "walk-da.csv": per_da,
                  "walk-stops.csv": per_stop, "walk-variants.csv": variants, "walk-reproduction.csv": reproduction}
    return result, tables_out


def make_router_pairs(protocol, field, uniform, line_union, union_stops, network):
    spec = protocol["router"]
    rng = np.random.default_rng(spec["seed"])
    candidates = np.flatnonzero(line_union & (uniform > 0))
    chosen = rng.choice(candidates, size=spec["pairs"], replace=False)
    _, nearest = cKDTree(union_stops).query(field.xy[chosen])
    back = Transformer.from_crs(26910, 4326, always_xy=True)
    pairs = []
    for point_index, stop_index in zip(chosen.tolist(), nearest.tolist()):
        node_a, _ = network.snap(field.xy[[point_index]])
        node_b, _ = network.snap(union_stops[[stop_index]])
        a, b = network.xy[int(node_a[0])], network.xy[int(node_b[0])]
        pairs.append({"from_node": int(node_a[0]), "to_node": int(node_b[0]), "from": back.transform(a[0], a[1]), "to": back.transform(b[0], b[1])})
    return pairs


def compare_router(root, protocol, network, pairs):
    cache = root / SOURCE_DIR / "router-cache.json"
    spec = protocol["router"]
    if not cache.exists():
        (root / SOURCE_DIR / "router-pairs.json").write_text(json.dumps([{"from": p["from"], "to": p["to"]} for p in pairs]), encoding="utf-8")
        return {"status": "no cache"}
    stored = json.loads(cache.read_text(encoding="utf-8"))
    rows = []
    for pair, answer in zip(pairs, stored["answers"]):
        distance = dijkstra(network.graph, directed=False, indices=pair["from_node"], limit=5000)[pair["to_node"]]
        rows.append({"this_network_m": float(distance), "router_m": answer})
    usable = [row for row in rows if row["router_m"] is not None and math.isfinite(row["this_network_m"])]
    absolute = sorted(abs(row["this_network_m"] - row["router_m"]) for row in usable)
    within = sum(abs(row["this_network_m"] - row["router_m"]) <= 0.1 * max(row["router_m"], 1) for row in usable)
    median = absolute[len(absolute) // 2] if absolute else None
    share = within / len(usable) if usable else None
    return {"status": "run", "pairs": len(rows), "usable": len(usable), "median_absolute_m": median, "share_within_10_percent": share,
            "passes": bool(usable and median <= spec["bar_median_absolute_m"] and share >= spec["bar_share_within_10_percent"]), "rows": rows}


def write_all(result, tables, output):
    output.mkdir(parents=True, exist_ok=False)
    with (output / "walk-results.json").open("x", encoding="utf-8") as handle:
        json.dump(result, handle, indent=1, sort_keys=True, allow_nan=False)
        handle.write("\n")
    for name, rows in tables.items():
        write_csv(output / name, rows)


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--output", type=Path, required=True)
    args = parser.parse_args()
    outcome, out_tables = compute(STUDY)
    write_all(outcome, out_tables, args.output)
    failures = outcome["reproduction"]["rows"] - outcome["reproduction"]["passes"]
    print(f"VERDICT: {'PASS' if not failures and not outcome['monotonic_violations'] else 'CHECK'} walking-network run; "
          f"reproduction {outcome['reproduction']['passes']} of {outcome['reproduction']['rows']}; "
          f"monotonic violations {outcome['monotonic_violations']}")
