"""One real trace, decided after the amended run: the frozen run's largest detour, measured again with the stitched links in place."""
import argparse
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
import walk_checks as checks  # noqa: E402


def trace(points=6, limit=1000):
    context = checks.Context(STUDY)
    ways = context.clean_inputs()["ways"]
    worked = json.loads((STUDY / "data/walk-network-frozen-run/walk-results.json").read_text(encoding="utf-8"))["worked_example"]
    network = wa.Network(ways, "main", context.protocol)
    stitched = after.Stitched(network, after.grade_separated_nodes(ways, network, context.protocol), after.STITCH_MAIN)
    stop = tuple(context.points_by_id[worked["stop_id"]])
    field = context.field.xy
    straight = np.hypot(field[:, 0] - stop[0], field[:, 1] - stop[1])
    nearest = np.argsort(straight, kind="stable")[:points]
    key = wa.set_key([stop])
    lower, _ = wa.network_distances(network, field[nearest], {key}, limit)
    upper, _ = wa.network_distances(stitched, field[nearest], {key}, limit)
    rows = [{"straight_m": round(float(straight[i]), 1), "lower_end_walk_m": round(float(lower[key][k]), 1), "upper_end_walk_m": round(float(upper[key][k]), 1)} for k, i in enumerate(nearest)]
    return {"decided": "after the amended run", "route": worked["route"], "stop_id": worked["stop_id"], "stop_name": worked["stop_name"], "points_nearest_the_stop": rows}


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--output", type=Path, required=True)
    args = parser.parse_args()
    outcome = trace()
    with args.output.open("x", encoding="utf-8") as handle:
        json.dump(outcome, handle, indent=1)
        handle.write("\n")
    first = outcome["points_nearest_the_stop"][0]
    print(f"VERDICT: PASS trace written; nearest point {first['straight_m']} m away, walk {first['lower_end_walk_m']} m at the lower end, {first['upper_end_walk_m']} m at the upper end")
