"""Walking-network round: the runs declared after the first version of the page (DESIGN-walk-network-review.md).

Part "split": each corridor's walking count split into residents of its straight-line count who can still walk to it (kept)
and residents who count only because today's baseline shrinks on foot (moved in). Part "blind": each stored blind fault run
once more through the committed refresh harness, to record how far it moved each corridor's count. Scores do not change.

Reads the frozen code and the stored sources. Changes no stored result. No network, no key.
"""
import argparse
import csv
import json
from pathlib import Path
import sys

import numpy as np

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 digest, load_region  # noqa: E402

DESIGN = "DESIGN-walk-network-review.md"
FROZEN = "data/walk-network-frozen-run/walk-results.json"
AMENDED = "data/walk-network-amended-run/walk-results.json"
CHECKS = "data/walk-network-checks"
CASES = (("strict", wa.UNIFORM), ("strict", wa.POINT), ("stop_pooled", wa.UNIFORM))
EXACT = 1e-9  # relative, recomputed walking count against the stored one
SET_TOLERANCE = 1e-6  # residents


def split(groups, corridors, straight, walked, limit, gap, rule, weights):
    """Straight-line set S per corridor, the walking set W, kept = S and W, moved in = W outside S."""
    size = len(weights)
    line_base = wa.baseline_mask(groups[rule, gap], straight, limit, size)
    walk_base = wa.baseline_mask(groups[rule, gap], walked, limit, size)
    routes = {}
    for route in wa.ROUTES:
        line_set = wa.covered(corridors[route], straight, limit) & ~line_base
        walk_set = wa.covered(corridors[route], walked, limit) & ~walk_base
        kept, moved = line_set & walk_set, walk_set & ~line_set
        routes[route] = {"straight": float(weights[line_set].sum()), "walking": float(weights[walk_set].sum()),
                         "kept": float(weights[kept].sum()), "moved_in": float(weights[moved].sum()),
                         "moved_in_not_from_line_baseline": float(weights[moved & ~(line_base & ~walk_base)].sum())}
    return {"straight_baseline": float(weights[line_base].sum()), "walking_baseline": float(weights[walk_base].sum()), "routes": routes}


def stored_counts(frozen, amended):
    """Walking counts already stored, keyed by (network, rule, allocation): {route or 'baseline': value}."""
    out = {}
    for c in frozen["cases"]:
        if c["distance_m"] == 400 and c["gap_s"] == 900:
            out.setdefault(("first_rule", c["rule"], c["allocation"]), {})[c["route"]] = c["walking"]
            out.setdefault(("straight", c["rule"], c["allocation"]), {})[c["route"]] = c["grid_straight"]
    for b in frozen["baselines"]:
        if b["distance_m"] == 400 and b["gap_s"] == 900:
            out[("first_rule", b["rule"], b["allocation"])]["baseline"] = b["walking"]
            out[("straight", b["rule"], b["allocation"])]["baseline"] = b["grid_straight"]
    for c in amended["cases"]:
        if c["distance_m"] == 400 and c["gap_s"] == 900:
            out.setdefault(("links_15m", c["rule"], c["allocation"]), {})[c["route"]] = c["stitched_walking"]
    for b in amended["baselines"]:
        if b["distance_m"] == 400 and b["gap_s"] == 900:
            out[("links_15m", b["rule"], b["allocation"])]["baseline"] = b["stitched_walking"]
    for s in amended["sweep"]:
        out[(f"links_{s['stitch_m']}m", s["rule"], wa.UNIFORM)] = {"baseline": s["baseline"], **{r: s["route_" + r] for r in wa.ROUTES}}
    for v in frozen["variants"]:
        if v["variant"] == "roads_only":
            out[("roads_only_first_rule", v["rule"], wa.UNIFORM)] = {"baseline": v["baseline"], **{r: v["route_" + r] for r in wa.ROUTES}}
    return out


def close(a, b):
    return abs(a - b) <= EXACT * max(abs(b), 1.0)


def run_split(root):
    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"))
    frozen = json.loads((root / FROZEN).read_text(encoding="utf-8"))
    amended = json.loads((root / AMENDED).read_text(encoding="utf-8"))
    stored = stored_counts(frozen, amended)
    _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"]
    universe = np.array(sorted({point for key in wa.all_sets(groups, corridors) for point in key}))
    field = wa.Field(areas, universe, grid["cell_m"], reach)
    weights = {wa.UNIFORM: field.weights(wa.UNIFORM), wa.POINT: field.weights(wa.POINT)}
    limit, gap = protocol["main_state"]["distance_m"], protocol["main_state"]["gap_s"]
    wanted_sets = wa.all_sets(groups, corridors, {("strict", gap), ("stop_pooled", gap)})
    straight = {key: wa.straight_distance(field.xy, key, reach) for key in wanted_sets}

    failures = []
    # Positive control: on the straight-line distances themselves nothing can move in and kept equals S.
    for rule, allocation in CASES:
        control = split(groups, corridors, straight, straight, limit, gap, rule, weights[allocation])
        for route, row in control["routes"].items():
            if abs(row["kept"] - row["straight"]) > SET_TOLERANCE or row["moved_in"] > SET_TOLERANCE:
                failures.append(f"control {rule} {allocation} {route}")
            if not close(row["straight"], stored[("straight", rule, allocation)][route]):
                failures.append(f"straight {rule} {allocation} {route}: {row['straight']} against {stored[('straight', rule, allocation)][route]}")
    print("control and straight-line counts checked", flush=True)

    main_ways = wa.read_snapshot(wa.snapshot_path(root, protocol["overpass"]["main_date"]))
    base = wa.Network(main_ways, "main", protocol)
    flags = after.grade_separated_nodes(main_ways, base, protocol)
    networks = [("first_rule", lambda: base)]
    networks += [(f"links_{m}m", (lambda m=m: after.Stitched(base, flags, m))) for m in (10, 15, 25)]
    networks.append(("roads_only_first_rule", lambda: wa.Network(main_ways, "roads_only", protocol)))
    rows = []
    for name, build in networks:
        network = build()
        walked, _ = wa.network_distances(network, field.xy, wanted_sets, reach)
        for rule, allocation in CASES:
            result = split(groups, corridors, straight, walked, limit, gap, rule, weights[allocation])
            reference = stored.get((name, rule, allocation))
            if reference is not None:
                if not close(result["walking_baseline"], reference["baseline"]):
                    failures.append(f"{name} {rule} {allocation} baseline: {result['walking_baseline']} against {reference['baseline']}")
            for route, row in result["routes"].items():
                if reference is not None and not close(row["walking"], reference[route]):
                    failures.append(f"{name} {rule} {allocation} {route}: {row['walking']} against {reference[route]}")
                if abs(row["kept"] + row["moved_in"] - row["walking"]) > SET_TOLERANCE or row["kept"] > row["straight"] + SET_TOLERANCE:
                    failures.append(f"{name} {rule} {allocation} {route}: split does not add up")
                if row["moved_in_not_from_line_baseline"] > SET_TOLERANCE:
                    failures.append(f"{name} {rule} {allocation} {route}: {row['moved_in_not_from_line_baseline']} moved in from outside the baseline")
                rows.append({"network": name, "rule": rule, "allocation": allocation, "route": route,
                             "straight_line_count": row["straight"], "walking_count": row["walking"], "kept": row["kept"],
                             "moved_in": row["moved_in"], "same_people_share": row["kept"] / row["straight"],
                             "count_ratio": row["walking"] / row["straight"], "straight_baseline": result["straight_baseline"],
                             "walking_baseline": result["walking_baseline"], "stored_walking_count_matched": reference is not None})
        print(name, "done", flush=True)
    result = {"schema_version": 1, "design_sha256": digest(root / DESIGN), "frozen_results_sha256": digest(root / FROZEN),
              "amended_results_sha256": digest(root / AMENDED), "case": {"distance_m": limit, "gap_s": gap},
              "rows": rows, "rows_checked_against_stored": sum(r["stored_walking_count_matched"] for r in rows),
              "failures": failures}
    return result


def run_blind(root):
    import walk_blind
    import walk_checks as checks
    root = Path(root).resolve()
    context = checks.Context(root)
    stored = json.loads((root / CHECKS / "refresh-checks.json").read_text(encoding="utf-8"))
    scores = json.loads((root / CHECKS / "blind-faults.json").read_text(encoding="utf-8"))
    by_fault = {row["fault"]: row for row in scores["rows"]}
    reference = stored["reference"]
    rows, failures = [], []
    for fault in walk_blind.load_faults(root / CHECKS / "blind_faults.py.txt"):
        inputs = fault(context.clean_inputs())
        verdict, now = checks.evaluate(inputs, context, reference, stored["sentinels"])
        failed = [check for check in checks.CHECKS if verdict.get(check) is False]
        if failed != by_fault[fault.__name__]["failed_checks"]:
            failures.append(f"{fault.__name__}: {failed} against {by_fault[fault.__name__]['failed_checks']}")
        row = {"fault": fault.__name__, "caught": bool(failed), "failed_checks": failed, "pipeline_error": verdict.get("pipeline_error")}
        if now is not None:
            row["walking_count"] = {r: now["walk"][r] for r in wa.ROUTES}
            row["walking_change"] = {r: (now["walk"][r] - reference["walk"][r]) / reference["walk"][r] for r in wa.ROUTES}
            row["straight_line_change"] = {r: (now["line"][r] - reference["line"][r]) / reference["line"][r] for r in wa.ROUTES}
            row["largest_walking_change"] = max(abs(v) for v in row["walking_change"].values())
        rows.append(row)
        print(row["fault"], failed, row.get("largest_walking_change"), flush=True)
    per_check = {check: sum(check in row["failed_checks"] for row in rows) for check in checks.CHECKS}
    broad = ("corridor_drift", "straight_line_reproduction")
    without_broad = sum(any(c not in broad for c in row["failed_checks"]) for row in rows)
    result = {"schema_version": 1, "design_sha256": digest(root / DESIGN), "scores_sha256": digest(root / CHECKS / "blind-faults.json"),
              "reference_walking_count": {r: reference["walk"][r] for r in wa.ROUTES}, "rows": rows,
              "caught": sum(row["caught"] for row in rows), "total": len(rows), "faults_caught_per_check": per_check,
              "caught_without_corridor_drift_and_reproduction": without_broad, "failures": failures}
    return result


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)


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--part", choices=("split", "blind"), required=True)
    parser.add_argument("--output", type=Path, required=True, help="an existing folder")
    args = parser.parse_args()
    if args.part == "split":
        outcome = run_split(wa.STUDY)
        with (args.output / "walk-same-people.json").open("x", encoding="utf-8") as handle:
            json.dump(outcome, handle, indent=1, sort_keys=True)
            handle.write("\n")
        write_csv(args.output / "walk-same-people.csv", outcome["rows"])
    else:
        outcome = run_blind(wa.STUDY)
        with (args.output / "blind-fault-effects.json").open("x", encoding="utf-8") as handle:
            json.dump(outcome, handle, indent=1, sort_keys=True)
            handle.write("\n")
    ok = not outcome["failures"]
    print(f"VERDICT: {'PASS' if ok else 'FAIL'} review {args.part}; failures {len(outcome['failures'])}")
    sys.exit(0 if ok else 1)
