"""Refresh checks for the walking-network measure, and the faults they are scored on.

A team refreshing the measure would run `evaluate` on each new input set. Each check must fail on a fault of its kind before it
counts. The planted faults are a self-test: one author wrote them and the checks. Blind faults live in their own file.
"""
import argparse
import copy
import json
import math
from pathlib import Path
import sys

import numpy as np
from pyproj import Transformer
from scipy.sparse.csgraph import dijkstra

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

import walk_access as wa  # noqa: E402
import walk_after as after  # noqa: E402
from region import load_region  # noqa: E402

CHECKS = ("schema", "way_count_drift", "length_drift", "component_share", "stop_snap", "monotonic", "population_total",
          "straight_line_reproduction", "bridge_sentinels", "service_date", "corridor_drift")


class Context:
    """What stays fixed across refreshes: the land grid, the stop-set membership by id, and the published straight-line counts."""

    def __init__(self, root=STUDY):
        root = Path(root)
        self.root = root
        self.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"))
        _r, _w, self.areas, _c = load_region(root)
        groups, corridors, stops, _s = wa.stop_groups(root, contract, manifest)
        tables = wa.read_tables(root, manifest)
        self.points_by_id = stops
        ids_by_point = {}
        for stop_id, xy in stops.items():
            ids_by_point.setdefault(xy, []).append(stop_id)
        def ids(points):
            return sorted(ids_by_point[point][0] for point in points)
        self.baseline_ids = {route: {d: ids(p) for d, p in directions.items()} for route, directions in groups["strict", 900].items()}
        self.corridor_ids = {route: {d: ids(p) for d, p in directions.items()} for route, directions in corridors.items()}
        used = {i for block in (self.baseline_ids, self.corridor_ids) for dirs in block.values() for group in dirs.values() for i in group}
        names = {row["stop_id"]: row for row in tables["stops"]}
        self.stop_table = [{"stop_id": i, "stop_name": names[i].get("stop_name", ""), "lon": float(names[i]["stop_lon"]), "lat": float(names[i]["stop_lat"])} for i in sorted(used)]
        calendar = tables.get("feed_info") or []
        dates = sorted({row["start_date"] for row in tables.get("calendar", [])} | {row["end_date"] for row in tables.get("calendar", [])})
        self.feed_start = (calendar[0].get("feed_start_date") if calendar else None) or (dates[0] if dates else "")
        self.feed_end = (calendar[0].get("feed_end_date") if calendar else None) or (dates[-1] if dates else "")
        universe = np.array(sorted({p for key in wa.all_sets(groups, corridors) for p in key}))
        self.field = wa.Field(self.areas, universe, self.protocol["grid"]["cell_m"], self.protocol["grid"]["reach_limit_m"])
        self.area_table = [{"da_uid": uid, "population": int(self.field.population[i]), "land_area_m2": float(self.field.land_area[i])}
                           for i, uid in enumerate(self.field.uids)]
        s, w, n, e = self.protocol["overpass"]["bbox_s_w_n_e"]
        self.bbox = (s, w, n, e)
        rows, bases = wa.frozen_tables(root)
        self.frozen = {r["route"]: float(r["strict_incremental_covered"]) for r in rows
                       if int(r["buffer_meters"]) == 400 and int(r["headway_seconds"]) == 900 and r["allocation"] == wa.UNIFORM}

    def clean_inputs(self, date=None):
        date = date or self.protocol["overpass"]["main_date"]
        return {"ways": wa.read_snapshot(wa.snapshot_path(self.root, date)), "stops": copy.deepcopy(self.stop_table),
                "areas": copy.deepcopy(self.area_table),
                "service": {"date": self.protocol["refresh_checks"]["service_date"], "feed_start": self.feed_start, "feed_end": self.feed_end},
                "length_scale": 1.0}


def sentinels(ways, protocol, count):
    projection = Transformer.from_crs(4326, 26910, always_xy=True)
    bridges = []
    for way in ways:
        tags = way["tags"]
        if tags.get("bridge") in (None, "no") or not wa.walkable(tags, "main", protocol["network"]) or len(way["nodes"]) < 2:
            continue
        lon, lat = zip(*way["coords"])
        x, y = projection.transform(lon, lat)
        length = sum(math.hypot(x[i + 1] - x[i], y[i + 1] - y[i]) for i in range(len(x) - 1))
        bridges.append((length, way["id"], way["nodes"][0], way["nodes"][-1]))
    bridges.sort(key=lambda row: (-row[0], row[1]))
    return [{"way": way_id, "start": start, "end": end} for _length, way_id, start, end in bridges[:count]]


def measure(inputs, context, sentinel_pairs=None):
    """Run the whole pipeline on one input set and return the numbers every check needs."""
    protocol, field = context.protocol, context.field
    network = wa.Network(inputs["ways"], "main", protocol, length_scale=inputs.get("length_scale", 1.0))
    flags = after.grade_separated_nodes(inputs["ways"], network, protocol)
    stitched = after.Stitched(network, flags, after.STITCH_MAIN)
    projection = Transformer.from_crs(4326, 26910, always_xy=True)
    coords = {row["stop_id"]: projection.transform(row["lon"], row["lat"]) for row in inputs["stops"]}
    missing = 0
    def points(ids):
        nonlocal missing
        found = []
        for stop_id in ids:
            if stop_id in coords:
                found.append(coords[stop_id])
            else:
                missing += 1
        return found or [(0.0, 0.0)]
    groups = {("strict", 900): {r: {d: points(i) for d, i in dirs.items()} for r, dirs in context.baseline_ids.items()}}
    corridors = {r: {d: points(i) for d, i in dirs.items()} for r, dirs in context.corridor_ids.items()}
    sets = wa.all_sets(groups, corridors)
    population = np.zeros(len(field.uids))
    by_uid = {row["da_uid"]: row for row in inputs["areas"]}
    position = {uid: i for i, uid in enumerate(field.uids)}
    for uid, row in by_uid.items():
        if uid in position:
            population[position[uid]] = row["population"]
    weights = field.weights(wa.UNIFORM, population)
    reach = protocol["grid"]["reach_limit_m"]
    straight = {key: wa.straight_distance(field.xy, key, reach) for key in sets}
    walked, _ = wa.network_distances(stitched, field.xy, sets, reach)
    _, line = wa.case_counts(groups, corridors, straight, 400, 900, "strict", weights)
    _, walk = wa.case_counts(groups, corridors, walked, 400, 900, "strict", weights)
    tolerance = protocol["refresh_checks"]["monotonic_tolerance_m"]
    violations = 0
    for key in sets:
        finite = np.isfinite(walked[key]) & np.isfinite(straight[key])
        violations += int((walked[key][finite] + tolerance < straight[key][finite]).sum())
    stop_xy = np.array(list(coords.values())) if coords else np.zeros((1, 2))
    _, snap = network.snap(stop_xy)
    sentinel_distance = {}
    if sentinel_pairs:
        for pair in sentinel_pairs:
            a, b = network.osm_index.get(pair["start"]), network.osm_index.get(pair["end"])
            value = math.inf
            if a is not None and b is not None and network.in_main[a] and network.in_main[b]:
                value = float(dijkstra(network.graph, directed=False, indices=a, limit=5000)[b])
            sentinel_distance[str(pair["way"])] = value
    return {"ways": len(inputs["ways"]), "length_km": network.total_length_m / 1000, "component_share": network.component_share,
            "snap_share": float((snap <= protocol["refresh_checks"]["stop_snap_m"]).mean()), "monotonic_violations": violations,
            "population_total": sum(row["population"] for row in inputs["areas"]), "area_count": len(inputs["areas"]),
            "line": line, "walk": walk, "sentinels": sentinel_distance, "missing_stops": missing}


def schema_ok(inputs, context):
    s, w, n, e = context.bbox
    seen = set()
    margin = 0.05
    for way in inputs["ways"]:
        if way["id"] in seen or len(way["nodes"]) != len(way["coords"]) or len(way["nodes"]) < 2 or "highway" not in way["tags"]:
            return False
        seen.add(way["id"])
        for lon, lat in way["coords"]:
            if not (w - margin <= lon <= e + margin and s - margin <= lat <= n + margin):
                return False
    ids = [row["stop_id"] for row in inputs["stops"]]
    if len(ids) != len(set(ids)):
        return False
    return all(w <= row["lon"] <= e and s <= row["lat"] <= n for row in inputs["stops"])


def evaluate(inputs, context, reference, sentinel_pairs):
    """Every check, with its verdict. A pipeline crash on a refresh fails every measured check, which is the right alarm."""
    bars = context.protocol["refresh_checks"]
    verdict = {"schema": schema_ok(inputs, context)}
    try:
        now = measure(inputs, context, sentinel_pairs)
    except Exception as error:  # a refresh that breaks the pipeline has been caught, whatever broke it
        verdict.update({check: False for check in CHECKS if check != "schema"})
        verdict["pipeline_error"] = type(error).__name__
        return verdict, None
    verdict["way_count_drift"] = abs(now["ways"] - reference["ways"]) <= bars["way_count_drift_bar"] * reference["ways"]
    verdict["length_drift"] = abs(now["length_km"] - reference["length_km"]) <= bars["length_drift_bar"] * reference["length_km"]
    verdict["component_share"] = now["component_share"] >= bars["component_share_floor"]
    verdict["stop_snap"] = now["snap_share"] >= bars["stop_snap_share_floor"]
    verdict["monotonic"] = now["monotonic_violations"] == 0
    verdict["population_total"] = now["population_total"] == bars["population_total"] and now["area_count"] == bars["area_count"]
    verdict["straight_line_reproduction"] = all(
        abs(now["line"][route] - context.frozen[route]) <= bars["straight_line_reproduction_relative"] * context.frozen[route] for route in wa.ROUTES)
    verdict["bridge_sentinels"] = all(
        now["sentinels"].get(key, math.inf) <= bars["sentinel_factor"] * value for key, value in reference["sentinels"].items())
    date = bars["service_date"].replace("-", "")
    service = inputs["service"]
    verdict["service_date"] = (service["date"].replace("-", "") == date and service["feed_start"] <= date <= service["feed_end"]
                               and now["missing_stops"] == 0)
    verdict["corridor_drift"] = all(
        abs(now["walk"][route] - reference["walk"][route]) <= bars["corridor_drift_bar"] * reference["walk"][route] for route in wa.ROUTES)
    return verdict, now


def planted_faults():
    """The ten faults the protocol names. Each takes and returns the input tables."""
    def stops_shifted_100m_east(i):
        for row in i["stops"]:
            row["lon"] += 100 / (111320 * math.cos(math.radians(row["lat"])))
        return i

    def stops_lat_lon_swapped(i):
        for row in i["stops"]:
            row["lon"], row["lat"] = row["lat"], row["lon"]
        return i

    def footways_dropped(i):
        i["ways"] = [w for w in i["ways"] if w["tags"].get("highway") not in ("footway", "path", "steps", "cycleway")]
        return i

    def bridges_removed(i):
        i["ways"] = [w for w in i["ways"] if w["tags"].get("bridge") in (None, "no")]
        return i

    def ten_percent_of_areas_lose_population(i):
        for row in i["areas"][::10]:
            row["population"] = 0
        return i

    def half_the_network_truncated(i):
        i["ways"] = i["ways"][: len(i["ways"]) // 2]
        return i

    def network_in_wrong_zone(i):
        for way in i["ways"]:
            way["coords"] = [[lon + 6.0, lat] for lon, lat in way["coords"]]
        return i

    def edge_lengths_halved(i):
        i["length_scale"] = 0.5
        return i

    def service_date_outside_feed(i):
        i["service"]["feed_start"] = "20200101"
        i["service"]["feed_end"] = "20201231"
        return i

    def response_way_count_collapsed(i):
        i["ways"] = i["ways"][:: 40]
        return i

    return [stops_shifted_100m_east, stops_lat_lon_swapped, footways_dropped, bridges_removed, ten_percent_of_areas_lose_population,
            half_the_network_truncated, network_in_wrong_zone, edge_lengths_halved, service_date_outside_feed, response_way_count_collapsed]


def run_fault(fault, context, reference, pairs):
    inputs = fault(context.clean_inputs())
    verdict, _ = evaluate(inputs, context, reference, pairs)
    failed = [check for check in CHECKS if verdict.get(check) is False]
    return {"fault": fault.__name__, "caught": bool(failed), "failed_checks": failed, "pipeline_error": verdict.get("pipeline_error")}


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--output", type=Path, required=True)
    args = parser.parse_args()
    context = Context(STUDY)
    clean = context.clean_inputs()
    pairs = sentinels(clean["ways"], context.protocol, context.protocol["refresh_checks"]["sentinel_count"])
    reference = measure(clean, context, pairs)
    verdict, _ = evaluate(clean, context, reference, pairs)
    print("clean", verdict, flush=True)
    last_year = context.clean_inputs(context.protocol["overpass"]["drift_dates"][0])
    last_reference = measure(last_year, context, pairs)
    real, _ = evaluate(clean, context, last_reference, pairs)
    print("real refresh", real, flush=True)
    rows = []
    for fault in planted_faults():
        rows.append(run_fault(fault, context, reference, pairs))
        print(rows[-1], flush=True)
    output = {"sentinels": pairs, "reference": reference, "clean": verdict, "real_refresh_from_year_old_map": real,
              "real_refresh_year_old_reference": last_reference, "planted": rows, "planted_caught": sum(row["caught"] for row in rows),
              "planted_total": len(rows), "checks": list(CHECKS)}
    with args.output.open("x", encoding="utf-8") as handle:
        json.dump(output, handle, indent=1, sort_keys=True, default=lambda value: None if value == math.inf else float(value))
        handle.write("\n")
    print(f"VERDICT: planted faults caught {output['planted_caught']} of {output['planted_total']}")
