"""Walking-network round, the amended run: everything here was decided after seeing the frozen run.

See DESIGN-walk-network-amendment.md. The frozen code and results are read, never changed.
"""
import argparse
from collections import defaultdict
import json
from pathlib import Path
import sys

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

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

import walk_access as wa  # noqa: E402
from region import digest, load_region  # noqa: E402

STITCH_MAIN = 15
STITCH_SWEEP = (10, 25)


def grade_separated_nodes(ways, network, protocol):
    """Nodes on a way tagged as a bridge or a tunnel, found by distance so subdivided nodes count too."""
    projection = Transformer.from_crs(4326, 26910, always_xy=True)
    lines = []
    for way in ways:
        tags = way["tags"]
        separated = tags.get("bridge") not in (None, "no") or tags.get("tunnel") not in (None, "no")
        if separated and wa.walkable(tags, "main", protocol["network"]) and len(way["coords"]) >= 2:
            lon, lat = zip(*way["coords"])
            lines.append(shapely.LineString(np.column_stack(projection.transform(lon, lat))))
    flags = np.zeros(network.node_count, dtype=bool)
    if lines:
        hits, _ = shapely.STRtree(lines).query(shapely.points(network.xy), predicate="dwithin", distance=0.5)
        flags[np.unique(hits)] = True
    return flags


class Stitched:
    """The frozen network plus straight links between close nodes, largest component recomputed."""

    def __init__(self, base, flags, stitch_m):
        pairs = cKDTree(base.xy).query_pairs(stitch_m, output_type="ndarray")
        keep = ~(flags[pairs[:, 0]] | flags[pairs[:, 1]])
        pairs = pairs[keep]
        lengths = np.hypot(*(base.xy[pairs[:, 0]] - base.xy[pairs[:, 1]]).T)
        lengths = np.maximum(lengths, 1e-3)
        graph = base.graph.tocoo()
        low = np.r_[graph.row, pairs[:, 0], pairs[:, 1]]
        high = np.r_[graph.col, pairs[:, 1], pairs[:, 0]]
        weight = np.r_[graph.data, lengths, lengths]
        order = np.lexsort((weight, high, low))
        low, high, weight = low[order], high[order], weight[order]
        unique = np.r_[True, (low[1:] != low[:-1]) | (high[1:] != high[:-1])]
        self.graph = coo_matrix((weight[unique], (low[unique], high[unique])), shape=graph.shape).tocsr()
        _, labels = connected_components(self.graph, directed=False)
        counts = np.bincount(labels)
        main = int(np.argmax(counts))
        self.node_count = base.node_count
        self.xy = base.xy
        self.main_nodes = np.flatnonzero(labels == main)
        self.tree = cKDTree(self.xy[self.main_nodes])
        self.links_added = int(len(pairs))
        self.stitch_m = stitch_m

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


def compute(root=wa.STUDY):
    root = Path(root).resolve()
    protocol = wa.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 = wa.stop_groups(root, contract, manifest)
    grid, reach = protocol["grid"], protocol["grid"]["reach_limit_m"]
    sets_all = wa.all_sets(groups, corridors)
    universe = np.array(sorted({point for key in sets_all for point in key}))
    field = wa.Field(areas, universe, grid["cell_m"], reach)
    uniform, point = field.weights(wa.UNIFORM), field.weights(wa.POINT)
    main_ways = wa.read_snapshot(wa.snapshot_path(root, protocol["overpass"]["main_date"]))
    base = wa.Network(main_ways, "main", protocol)
    flags = grade_separated_nodes(main_ways, base, protocol)
    straight = {key: wa.straight_distance(field.xy, key, reach) for key in sets_all}
    frozen_walked, frozen_access = wa.network_distances(base, field.xy, sets_all, reach)
    stitched_net = Stitched(base, flags, STITCH_MAIN)
    walked, access = wa.network_distances(stitched_net, field.xy, sets_all, reach)
    print("stitched links", stitched_net.links_added, flush=True)

    limit, gap = protocol["main_state"]["distance_m"], protocol["main_state"]["gap_s"]
    states = protocol["states"]
    cases, baselines = [], []
    for reach_limit in states["distance_m"]:
        for one_gap in states["gap_s"]:
            for rule in states["rule"]:
                for allocation in states["allocation"]:
                    weights = uniform if allocation == wa.UNIFORM else point
                    line_base, line = wa.case_counts(groups, corridors, straight, reach_limit, one_gap, rule, weights)
                    frozen_base, frozen = wa.case_counts(groups, corridors, frozen_walked, reach_limit, one_gap, rule, weights)
                    walk_base, walk = wa.case_counts(groups, corridors, walked, reach_limit, one_gap, rule, weights)
                    state = [{"distance_m": reach_limit, "gap_s": one_gap, "rule": rule, "allocation": allocation, "route": route,
                              "straight": line[route], "frozen_walking": frozen[route], "stitched_walking": walk[route]} for route in wa.ROUTES]
                    wa.assign_ranks(state, "straight", "rank_straight")
                    wa.assign_ranks(state, "frozen_walking", "rank_frozen")
                    wa.assign_ranks(state, "stitched_walking", "rank_stitched")
                    cases.extend(state)
                    baselines.append({"distance_m": reach_limit, "gap_s": one_gap, "rule": rule, "allocation": allocation,
                                      "straight": line_base, "frozen_walking": frozen_base, "stitched_walking": walk_base})
    # Stitch sweep.
    sweep = []
    wanted = {("strict", gap), ("stop_pooled", gap)}
    wanted_sets = wa.all_sets(groups, corridors, wanted)
    for stitch in STITCH_SWEEP:
        other = Stitched(base, flags, stitch)
        distances, _ = wa.network_distances(other, field.xy, wanted_sets, reach)
        for rule in wa.RULES:
            base_count, counts = wa.case_counts(groups, corridors, distances, limit, gap, rule, uniform)
            sweep.append({"stitch_m": stitch, "rule": rule, "baseline": base_count, **{"route_" + r: counts[r] for r in wa.ROUTES}})
    print("sweep", flush=True)

    # Same-count radius on the stitched network.
    _, main_walk = wa.case_counts(groups, corridors, walked, limit, gap, "strict", uniform)
    radius = wa.same_count_radius(groups, corridors, straight, uniform, main_walk, protocol["same_count_radius"])

    # Same total, same people? Compare the buffer that matches the count with the walking measure itself.
    agreement = []
    for name, net_distance, target in (("frozen", frozen_walked, None), ("stitched", walked, radius)):
        for route in wa.ROUTES:
            if target is None:
                frozen_results = json.loads((root / "data/walk-network-frozen-run/walk-results.json").read_text(encoding="utf-8"))
                match = frozen_results["same_count_radius"]["radius_m"][route]
            else:
                match = target["radius_m"][route]
            line_base = wa.baseline_mask(groups["strict", gap], straight, match, len(uniform))
            walk_base = wa.baseline_mask(groups["strict", gap], net_distance, limit, len(uniform))
            line_set = wa.covered(corridors[route], straight, match) & ~line_base
            walk_set = wa.covered(corridors[route], net_distance, limit) & ~walk_base
            both = float(uniform[line_set & walk_set].sum())
            agreement.append({"network": name, "route": route, "radius_m": match, "buffer_residents": float(uniform[line_set].sum()),
                              "walking_residents": float(uniform[walk_set].sum()), "residents_in_both": both,
                              "share_of_walking_in_buffer": both / float(uniform[walk_set].sum())})

    # Areas and causes on the stitched network.
    def union_mask(distance):
        mask = wa.baseline_mask(groups["strict", gap], distance, limit, len(uniform))
        for route in wa.ROUTES:
            mask |= wa.covered(corridors[route], distance, limit)
        return mask
    line_union, walk_union, frozen_union = union_mask(straight), union_mask(walked), union_mask(frozen_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 = wa.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
    names = protocol["causes"]
    cause_totals = {names[i]: float(uniform[lost_ids[cause == i]].sum()) for i in range(4)}
    by_owner = defaultdict(lambda: [0.0, 0.0, 0.0, 0.0])
    for idx, kind in zip(lost_ids, cause):
        by_owner[int(field.owner[idx])][int(kind)] += float(uniform[idx])
    da_csd = json.loads((root / wa.SOURCE_DIR / "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())
        if line_value <= 0:
            continue
        walk_value = float(uniform[in_area & walk_union].sum())
        frozen_value = float(uniform[in_area & frozen_union].sum())
        kinds = by_owner[position]
        per_da.append({"da_uid": uid, "csd_uid": da_csd[uid]["csd_uid"], "csd_name": da_csd[uid]["csd_name"],
                       "straight_line_residents": line_value, "frozen_walking_residents": frozen_value, "stitched_walking_residents": walk_value,
                       "lost_residents_stitched": line_value - walk_value, "retained_share_stitched": walk_value / line_value,
                       **{"lost_" + names[i]: kinds[i] for i in range(4)}})
    per_csd = defaultdict(lambda: {"straight_line_residents": 0.0, "frozen_walking_residents": 0.0, "stitched_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"]]
        for key in target:
            target[key] += row[key]
    per_area = [{"csd_uid": uid, "csd_name": name, **values,
                 "lost_residents_stitched": values["straight_line_residents"] - values["stitched_walking_residents"],
                 "retained_share_frozen": values["frozen_walking_residents"] / values["straight_line_residents"],
                 "retained_share_stitched": values["stitched_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 on the stitched network.
    tables = wa.read_tables(root, manifest)
    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)
    roles = defaultdict(set)
    for route, directions in corridors.items():
        for points in directions.values():
            for p in points:
                roles[p].add("route " + route)
    for directions in groups["strict", gap].values():
        for points in directions.values():
            for p in points:
                roles[p].add("baseline")
    grid_xy, grid_weight = field.xy[: field.grid_count], uniform[: field.grid_count]
    tree = cKDTree(grid_xy)
    field_nodes, field_access = stitched_net.snap(grid_xy)
    from scipy.sparse.csgraph import dijkstra  # local: only this block needs a single-source run
    per_stop = []
    for p in sorted(roles):
        node, stop_access = stitched_net.snap(np.array([p]))
        dist = dijkstra(stitched_net.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())})

    # Drift on the stitched network.
    drift = []
    for date in [protocol["overpass"]["main_date"], *protocol["overpass"]["drift_dates"]]:
        ways = wa.read_snapshot(wa.snapshot_path(root, date))
        older = wa.Network(ways, "main", protocol)
        older_net = Stitched(older, grade_separated_nodes(ways, older, protocol), STITCH_MAIN)
        distances, _ = wa.network_distances(older_net, field.xy, wanted_sets, reach)
        row = {"date": date[:10], "ways": older.way_count, "length_km": older.total_length_m / 1000,
               "path_like_km": sum(older.way_length_m[w["id"]] for w in ways if w["id"] in older.way_length_m and w["tags"].get("highway") in protocol["network"]["path_like"]) / 1000}
        for rule in wa.RULES:
            base_count, counts = wa.case_counts(groups, corridors, distances, limit, gap, rule, uniform)
            row[rule + "_baseline"] = base_count
            for route in wa.ROUTES:
                row[rule + "_route_" + route] = counts[route]
        drift.append(row)
        print("drift", date[:10], flush=True)

    tables_out = {"walk-stitched-cases.csv": cases, "walk-stitched-baselines.csv": baselines, "walk-stitched-areas.csv": per_area,
                  "walk-stitched-da.csv": per_da, "walk-stitched-stops.csv": per_stop}
    result = {"schema_version": 1, "amendment_sha256": digest(root / "DESIGN-walk-network-amendment.md"),
              "frozen_results_sha256": digest(root / "data/walk-network-frozen-run/walk-results.json"),
              "stitch_m": STITCH_MAIN, "links_added": stitched_net.links_added, "grade_separated_nodes": int(flags.sum()),
              "cases": cases, "baselines": baselines, "sweep": sweep, "same_count_radius": radius, "agreement": agreement,
              "union": {"straight_line_residents": float(uniform[line_union].sum()), "frozen_walking_residents": float(uniform[frozen_union].sum()),
                        "stitched_walking_residents": float(uniform[walk_union].sum()), "causes": cause_totals},
              "drift": drift}
    return result, tables_out


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--output", type=Path, required=True)
    args = parser.parse_args()
    outcome, out_tables = compute(wa.STUDY)
    wa.write_all(outcome, out_tables, args.output)
    print("VERDICT: PASS amended walking-network run written")
