"""Causal fixtures for the walking-network measure: each test can fail if the distance logic breaks."""
import json
from pathlib import Path
import sys
import unittest

import numpy as np
from pyproj import Transformer

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

import walk_access as wa  # noqa: E402

PROTOCOL = wa.load_protocol(STUDY)
TO_LONLAT = Transformer.from_crs(26910, 4326, always_xy=True)
ORIGIN = (475000.0, 5365000.0)


def way(way_id, nodes, points, **tags):
    """Build a way from model-metre offsets around a fixed origin."""
    coords = [list(TO_LONLAT.transform(ORIGIN[0] + x, ORIGIN[1] + y)) for x, y in points]
    return {"id": way_id, "nodes": nodes, "coords": coords, "tags": {"highway": "residential", **tags}}


def at(x, y):
    return (ORIGIN[0] + x, ORIGIN[1] + y)


class WalkableTests(unittest.TestCase):
    spec = PROTOCOL["network"]

    def test_motorway_never_walkable(self):
        for variant in self.spec["variants"]:
            self.assertFalse(wa.walkable({"highway": "motorway"}, variant, self.spec))

    def test_private_access_depends_on_variant(self):
        tags = {"highway": "service", "access": "private"}
        self.assertFalse(wa.walkable(tags, "main", self.spec))
        self.assertTrue(wa.walkable(tags, "generous", self.spec))
        self.assertTrue(wa.walkable({**tags, "foot": "yes"}, "main", self.spec))

    def test_roads_only_drops_paths_and_no_trunk_drops_bare_trunk(self):
        self.assertFalse(wa.walkable({"highway": "footway"}, "roads_only", self.spec))
        self.assertTrue(wa.walkable({"highway": "footway"}, "main", self.spec))
        self.assertFalse(wa.walkable({"highway": "trunk"}, "no_trunk", self.spec))
        self.assertTrue(wa.walkable({"highway": "trunk", "sidewalk": "both"}, "no_trunk", self.spec))
        self.assertTrue(wa.walkable({"highway": "trunk"}, "main", self.spec))

    def test_not_built_is_out(self):
        self.assertFalse(wa.walkable({"highway": "construction"}, "generous", self.spec))


class NetworkTests(unittest.TestCase):
    def detour(self):
        # Two streets 100 m apart, joined only 500 m along: a river between them.
        return [way(1, [1, 2], [(0, 0), (500, 0)]), way(2, [3, 4], [(0, 100), (500, 100)]), way(3, [2, 4], [(500, 0), (500, 100)])]

    def test_detour_is_measured_along_the_street(self):
        network = wa.Network(self.detour(), "main", PROTOCOL)
        stop = wa.set_key([at(0, 0)])
        field = np.array([at(0, 100)])
        walked, _ = wa.network_distances(network, field, {stop}, 2000)
        self.assertAlmostEqual(float(walked[stop][0]), 1100.0, delta=0.5)
        self.assertAlmostEqual(float(wa.straight_distance(field, stop, 2000)[0]), 100.0, delta=0.01)

    def test_subdivision_conserves_length_and_duplicate_ways_do_not_double_it(self):
        network = wa.Network(self.detour(), "main", PROTOCOL)
        self.assertAlmostEqual(network.total_length_m, 1100.0, delta=0.5)
        doubled = wa.Network(self.detour() + [way(9, [1, 2], [(0, 0), (500, 0)])], "main", PROTOCOL)
        self.assertLess(doubled.total_length_m, 1701.0)
        stop = wa.set_key([at(0, 0)])
        walked, _ = wa.network_distances(doubled, np.array([at(500, 0)]), {stop}, 2000)
        self.assertAlmostEqual(float(walked[stop][0]), 500.0, delta=0.5)

    def test_island_falls_out_of_the_main_component(self):
        ways = self.detour() + [way(5, [8, 9], [(0, 900), (20, 900)])]
        network = wa.Network(ways, "main", PROTOCOL)
        self.assertLess(network.component_share, 1.0)
        node, distance = network.snap(np.array([at(10, 900)]))
        self.assertGreater(float(distance[0]), 700.0)

    def test_two_stop_sets_do_not_shortcut_through_each_other(self):
        network = wa.Network(self.detour(), "main", PROTOCOL)
        left, right = wa.set_key([at(0, 0)]), wa.set_key([at(0, 100)])
        walked, _ = wa.network_distances(network, np.array([at(0, 100)]), {left, right}, 2000)
        self.assertAlmostEqual(float(walked[left][0]), 1100.0, delta=0.5)
        self.assertAlmostEqual(float(walked[right][0]), 0.001, delta=0.01)

    def test_access_legs_count_toward_the_limit(self):
        network = wa.Network(self.detour(), "main", PROTOCOL)
        # Both legs end on mapped way ends, so the expected sum does not depend on how a way is subdivided.
        stop = wa.set_key([at(0, -30)])
        walked, access = wa.network_distances(network, np.array([at(500, -40)]), {stop}, 2000)
        self.assertAlmostEqual(float(access[0]), 40.0, delta=0.2)
        self.assertAlmostEqual(float(walked[stop][0]), 30 + 500 + 40, delta=0.5)

    def test_second_routine_matches(self):
        network = wa.Network(self.detour(), "main", PROTOCOL)
        node, _ = network.snap(np.array([at(0, 0)]))
        other = wa.plain_python_distances(network, {int(node[0]): 0.0}, 2000)
        far, _ = network.snap(np.array([at(0, 100)]))
        self.assertAlmostEqual(other[int(far[0])], 1100.0, delta=0.5)


class AlgebraTests(unittest.TestCase):
    def test_both_directions_required_and_baseline_subtracted(self):
        a, b, c = wa.set_key([(0.0, 0.0)]), wa.set_key([(1.0, 0.0)]), wa.set_key([(2.0, 0.0)])
        distance = {a: np.array([100.0, 500.0, 100.0]), b: np.array([100.0, 100.0, 100.0]), c: np.array([100.0, 900.0, 900.0])}
        groups = {("strict", 900): {"x": {"0": list(c), "1": list(c)}}}
        corridors = {route: {"0": list(a), "1": list(b)} for route in wa.ROUTES}
        base, counts = wa.case_counts(groups, corridors, distance, 400, 900, "strict", np.array([1.0, 10.0, 100.0]))
        self.assertEqual(base, 1.0)
        self.assertEqual(counts["14"], 100.0)

    def test_route_with_one_direction_covers_nothing(self):
        a = wa.set_key([(0.0, 0.0)])
        self.assertIsNone(wa.covered({"0": list(a)}, {a: np.array([1.0])}, 400))


if __name__ == "__main__":
    unittest.main()
