File size: 47,040 Bytes
4eb0e91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e43054
 
 
 
 
 
4eb0e91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e43054
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4eb0e91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e43054
 
4eb0e91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e43054
 
 
4eb0e91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e43054
 
4eb0e91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e43054
 
 
 
 
4eb0e91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
"""Route search with direct trips first, then one or two transfers.

The search is Dijkstra over ``(line, direction, stop position)`` nodes.
The state also remembers how many transfers have been used and which
lines have been used, so we can return distinct line combinations and
never loop back onto a line we already rode.
"""

from __future__ import annotations

import heapq
import itertools
from collections import defaultdict
from dataclasses import dataclass
from typing import Callable

from .network import (
    BUS_SPEED_M_PER_MIN,
    WALK_SPEED_M_PER_MIN,
    Edge,
    LineKey,
    Network,
    Node,
    haversine_m,
)
from .places import (
    PlaceCandidate,
    PlaceIndex,
    normalize_name,
    prefer_exact_matches,
    representative_coordinates,
)

MAX_TRANSFERS = 2
ACCESS_WALK_RADIUS_M = 1200.0
NEARBY_EXACT_STOP_RADIUS_M = 900.0
# Autour d'un lieu nommé par l'usager, un arrêt conseillé doit rester à 600 m :
# au-delà, la carte ne donne plus de nom d'arrêt (« MTOA » ouvrait « Central
# Bel Air (MTOA) », 15 km au sud) et dit de chercher l'arrêt le plus proche.
# Le calcul du trajet, lui, n'est pas restreint : une pénalité ici faisait
# disparaître les Dem Dikk 10 et 13 de Liberté 5 (terminus de Dieuppeul).
PLACE_STOP_RADIUS_M = 600.0
MAX_NEARBY_STOPS = 14
# Écart toléré entre la position générale d'un arrêt (celle qui a servi à
# compter la marche) et sa position sur une ligne donnée. Au-delà, ce n'est
# pas le même arrêt mais un homonyme : « Sipres » est situé à Amitié, près de
# l'UCAD, alors que le « SIPRES » de Dem Dikk 220 est à Rufisque. Sans ce
# garde-fou, Malika -> UCAD proposait la 220 avec descente « à 10 min à pied ».
MAX_ECART_HOMONYME_M = 1_500.0
MAX_LABELS_PER_STATE = 6
MAX_EXPANSIONS = 250_000
DETOUR_LIMIT = 1.8
DOWNTOWN_RADIUS_M = 1_500.0
MIN_LEG_MINUTES = 2.0
TRANSFER_SCORE_MINUTES = 15.0
DIRECT_ALLOWANCE_MINUTES = 15.0
MIN_TRANSFER_ADVANTAGE_MINUTES = 10.0
MAX_WALKABLE_BUS_LEG_M = 600.0
# La marche à pied suit rarement la ligne droite : 1,3 fois la distance
# vol d'oiseau, à 80 m/min (environ 4,8 km/h).
WALK_DETOUR_FACTOR = 1.3
MAX_WALK_ONLY_MINUTES = 40.0
# A trip three times slower than the best option is not a useful
# alternative.  This also catches routes with missing coordinates that
# escape the distance-based detour check.
MAX_TIME_VS_BEST = 3.0
# Un rapport ne veut rien dire sur un trajet très court : à côté d'une ligne à 2 min,
# Tata 62 (10 min, Sahm -> Colobane) passait pour absurdement lent.
MIN_TIME_MARGIN_MINUTES = 20.0
# La recherche s'arrête quand plus rien ne peut approcher le meilleur trajet trouvé :
# au-delà, un trajet serait écarté ou jamais affiché.
MAX_SCORE_ABOVE_BEST = 30.0


def walking_minutes(
    a: tuple[float, float],
    b: tuple[float, float],
) -> float:
    """Temps de marche estimé entre deux points, en minutes."""

    return haversine_m(a, b) * WALK_DETOUR_FACTOR / WALK_SPEED_M_PER_MIN


# These are the downtown / Plateau names.  A trip may pass through them
# when they are close to the start or the destination, but not as a random
# shortcut between two outer neighbourhoods.
DOWNTOWN_STOP_NAMES = {
    normalize_name(name)
    for name in (
        "Palais 1",
        "Palais 2",
        "Palais",
        "Centre-Ville",
        "Plateau",
        "Place Leclerc",
        "Place de l'Indépendance",
        "Médina",
    )
}


class RouteError(Exception):
    """Base class for route errors."""


class PlaceNotFoundError(RouteError):
    def __init__(self, query: str, suggestions: list[tuple[str, float]]) -> None:
        self.query = query
        self.suggestions = suggestions
        super().__init__(f"Unknown place: {query}")


class NoRouteFoundError(RouteError):
    pass


@dataclass(frozen=True)
class Walk:
    kind: str                      # "access", "transfer", or "egress"
    from_place: str
    to_place: str
    minutes: float
    distance_m: float | None = None
    after_leg: int = 0             # 0 = before the first leg


def _has_endpoint_walk(trip: Trip) -> bool:
    return any(
        walk.kind in {"access", "egress"} and walk.minutes > 0
        for walk in trip.walks
    )


@dataclass(frozen=True)
class Leg:
    operator: str
    line: str
    board_stop: str
    alight_stop: str
    direction: str                 # terminus shown on the bus
    num_stops: int
    minutes: float
    distance_m: float | None = None
    estimated: bool = False


@dataclass(frozen=True)
class Trip:
    legs: tuple[Leg, ...]
    walks: tuple[Walk, ...]
    total_minutes: float
    transfers: int
    line_combo: tuple[LineKey, ...]
    origin_name: str
    destination_name: str
    total_distance_m: float | None
    straight_line_m: float | None
    detour: bool
    via_downtown: bool
    ridden_stops: tuple[str, ...]
    estimated: bool = False

    @property
    def walked_minutes(self) -> float:
        return sum(walk.minutes for walk in self.walks)

    @property
    def score(self) -> float:
        return self.total_minutes + TRANSFER_SCORE_MINUTES * self.transfers


@dataclass(frozen=True)
class ResolvedPlace:
    """Un lieu déjà résolu en arrêts du réseau (par GuindiMa, pas par v2)."""

    stops: tuple[str, ...]
    coords: tuple[float, float] | None = None


@dataclass(frozen=True)
class AccessPoint:
    stop: str
    walk: Walk


def _rank_key(trip: Trip) -> tuple[float, float, float, int]:
    distance = (
        trip.total_distance_m
        if trip.total_distance_m is not None
        else float("inf")
    )
    return trip.score, trip.total_minutes, distance, trip.transfers


# Au-delà de cette marche jusqu'à l'arrêt de montée, un bus direct n'est plus
# classé sur sa seule durée : il passe après ceux qui partent tout près.
MAX_ACCESS_WALK_FOR_FASTEST_MINUTES = 10.0


def direct_rank_key(trip: Trip) -> tuple[bool, float]:
    """Entre bus directs : le plus rapide d'abord (marche + bus), si l'on monte près."""

    access = sum(walk.minutes for walk in trip.walks if walk.kind == "access")
    return access >= MAX_ACCESS_WALK_FOR_FASTEST_MINUTES, trip.total_minutes


def rank_trips(trips: list[Trip], max_trips: int | None = None) -> list[Trip]:
    """Order trips by score, promoting a direct trip within 15 minutes.

    Score is ``total_minutes + 15 * transfers``.  A direct trip is shown
    first when it is at most 15 minutes slower than the best score, because
    avoiding a transfer is worth a short wait.
    """

    # Sur une même ligne, l'arrêt demandé passe avant un voisin à pied : Tata 62
    # dessert Sahm, on ne fait pas marcher l'usager jusqu'à Fass pour gagner une
    # minute sur le papier.
    def preference(trip: Trip) -> tuple:
        return (_has_endpoint_walk(trip), *_rank_key(trip))

    unique: dict[tuple[LineKey, ...], Trip] = {}
    for trip in trips:
        current = unique.get(trip.line_combo)
        if current is None or preference(trip) < preference(current):
            unique[trip.line_combo] = trip

    ordered = sorted(unique.values(), key=_rank_key)
    if not ordered:
        return []

    best_score = ordered[0].score
    direct = [
        trip
        for trip in ordered
        if trip.transfers == 0
        and trip.score <= best_score + DIRECT_ALLOWANCE_MINUTES
    ]
    direct.sort(key=direct_rank_key)
    direct_keys = {trip.line_combo for trip in direct}
    rest = [trip for trip in ordered if trip.line_combo not in direct_keys]
    ranked = direct + rest
    return ranked if max_trips is None else ranked[:max_trips]


def _slowest_sensible(fastest: float) -> float:
    return max(fastest * MAX_TIME_VS_BEST, fastest + MIN_TIME_MARGIN_MINUTES)


def keep_sensible_trips(trips: list[Trip]) -> list[Trip]:
    """Écarte les détours par le centre et les trajets absurdement lents."""

    # Extra guard for this network: do not cross downtown just to
    # connect two outer neighbourhoods.
    non_downtown = [trip for trip in trips if not trip.via_downtown]
    if non_downtown:
        trips = non_downtown

    # Do not offer an absurdly slow "alternative" just because it has
    # fewer transfers.  If every remaining trip is slow, keep them.
    if trips:
        limit = _slowest_sensible(min(trip.total_minutes for trip in trips))
        sane = [trip for trip in trips if trip.total_minutes <= limit]
        if sane:
            trips = sane
    return trips


def _has_walkable_one_stop_leg(trip: Trip, network: Network) -> bool:
    """A one-stop bus ride under 600 m is not worth waiting for a bus."""

    for leg in trip.legs:
        if leg.num_stops != 1:
            continue
        distance = leg.distance_m
        if distance is None:
            board = network.coords(leg.board_stop)
            alight = network.coords(leg.alight_stop)
            if board is None or alight is None:
                continue
            distance = haversine_m(board, alight)
        if distance <= MAX_WALKABLE_BUS_LEG_M:
            return True
    return False


def remove_dominated_trips(trips: list[Trip], network: Network) -> list[Trip]:
    """Hide slow transfer-heavy trips and pointless one-stop bus rides.

    A trip with more transfers must save at least ten minutes over the best
    trip with fewer transfers.  One-stop bus legs under 600 m are hidden too.
    If every trip is filtered, keep the best one so the answer is never empty.
    """

    if not trips:
        return []

    candidates = [
        trip for trip in trips if not _has_walkable_one_stop_leg(trip, network)
    ]
    if not candidates:
        return trips[:1]

    kept: list[Trip] = []
    for trip in candidates:
        faster_fewer = [
            other.total_minutes
            for other in candidates
            if other.transfers < trip.transfers
        ]
        if faster_fewer:
            best_fewer = min(faster_fewer)
            advantage = best_fewer - trip.total_minutes
            if advantage < MIN_TRANSFER_ADVANTAGE_MINUTES - 1e-9:
                continue
        kept.append(trip)
    return kept or candidates[:1]


@dataclass(frozen=True)
class _Step:
    kind: str                      # "access", "ride", "transfer", "egress"
    from_stop: str
    to_stop: str
    minutes: float
    line: LineKey
    direction: int
    from_index: int | None
    to_index: int | None
    distance_m: float | None = None
    walk_minutes: float = 0.0
    walk_distance_m: float | None = None
    transfer_penalty: float = 0.0
    estimated: bool = False


@dataclass(frozen=True)
class _Label:
    node: Node
    transfers: int
    cost: float
    combo: tuple[LineKey, ...]
    steps: tuple[_Step, ...]
    rode_since_transfer: bool


class RouteEngine:
    def __init__(self, network: Network, place_index: PlaceIndex | None = None) -> None:
        self.network = network
        self.place_index = place_index or PlaceIndex.from_network(network)

    # ------------------------------------------------------------------
    # Endpoint preparation.
    # ------------------------------------------------------------------
    def _access_points(
        self,
        candidate: PlaceCandidate,
        kind: str,
        include_nearby: bool = True,
        nearby_stop_ok: Callable[[str], bool] | None = None,
    ) -> list[AccessPoint]:
        """Stops the user can reach from this place, with the walk."""

        points: dict[str, AccessPoint] = {}

        # Exact normalized stop names win: "Malika" and "Sahm" board at the
        # stop itself, without an invented walk.
        exact_stops = self.network.stops_for_normalized(candidate.normalized)
        for stop in exact_stops:
            points[stop] = AccessPoint(
                stop=stop,
                walk=Walk(
                    kind=kind,
                    from_place=candidate.name,
                    to_place=stop,
                    minutes=0.0,
                    distance_m=0.0,
                    after_leg=0,
                ),
            )

        # Exact stops also open every stop within a short walk.  This lets a
        # neighbourhood such as Médina use a nearby avenue without losing the
        # exact stop itself.  The exact stop keeps its zero-minute walk.
        # Un arrêt à la position incertaine n'ouvre rien et n'est proposé à
        # personne : « Malika Terminus », mal placé, amenait Almadies -> Malika à
        # Gadaye « à 4 min à pied », à 4 km de là.
        exact_coords = [
            coords
            for stop in exact_stops
            if (coords := self.network.coords(stop)) is not None
            and (nearby_stop_ok is None or nearby_stop_ok(stop))
        ]
        if exact_coords and include_nearby:
            nearby: list[tuple[float, str]] = []
            for stop in self.network.stop_names:
                if stop in points:
                    continue
                if nearby_stop_ok is not None and not nearby_stop_ok(stop):
                    continue
                stop_coords = self.network.coords(stop)
                if stop_coords is None:
                    continue
                distance = min(
                    haversine_m(coords, stop_coords) for coords in exact_coords
                )
                if distance > NEARBY_EXACT_STOP_RADIUS_M:
                    continue
                if (
                    distance <= 1.0
                    and normalize_name(stop) != candidate.normalized
                ):
                    continue
                nearby.append((distance, stop))
            nearby.sort()
            for distance, stop in nearby:
                points[stop] = AccessPoint(
                    stop=stop,
                    walk=Walk(
                        kind=kind,
                        from_place=candidate.name,
                        to_place=stop,
                        minutes=distance / WALK_SPEED_M_PER_MIN,
                        distance_m=distance,
                        after_leg=0,
                    ),
                )

        # A place that is not itself a stop (for example "Palais", which is
        # near Palais 1 and Palais 2) can use the nearest stops.
        if not points and candidate.has_coordinates:
            origin = (float(candidate.lat), float(candidate.lon))
            nearby: list[tuple[float, str]] = []
            for stop in self.network.stop_names:
                stop_coords = self.network.coords(stop)
                if stop_coords is None:
                    continue
                distance = haversine_m(origin, stop_coords)
                if distance <= ACCESS_WALK_RADIUS_M:
                    nearby.append((distance, stop))
            nearby.sort()
            for distance, stop in nearby[:MAX_NEARBY_STOPS]:
                points[stop] = AccessPoint(
                    stop=stop,
                    walk=Walk(
                        kind=kind,
                        from_place=candidate.name,
                        to_place=stop,
                        minutes=distance / WALK_SPEED_M_PER_MIN,
                        distance_m=distance,
                        after_leg=0,
                    ),
                )

        return list(points.values())

    def _candidates_for(self, place: ResolvedPlace) -> list[PlaceCandidate]:
        """Les arrêts résolus, sous la forme que le reste du moteur connaît.

        Chacun est un arrêt exact : montée sans marche, et les arrêts proches
        restent ouverts par l'élargissement habituel de ``_access_points``.
        """

        candidats = []
        for stop in place.stops:
            coords = self.network.coords(stop)
            candidats.append(
                PlaceCandidate(
                    name=stop,
                    normalized=normalize_name(stop),
                    score=100.0,
                    lat=coords[0] if coords else None,
                    lon=coords[1] if coords else None,
                    is_stop=True,
                    is_place=False,
                    stop_names=(stop,),
                )
            )
        return candidats

    def _noeud_au_lieu_marche(self, node: Node, access: AccessPoint) -> bool:
        """Vrai si l'arrêt de ce nœud est bien celui vers lequel on a marché.

        Une marche (distance > 0) est mesurée depuis la position générale de
        l'arrêt. Si la ligne place son arrêt du même nom à plus de
        MAX_ECART_HOMONYME_M de là, c'est un homonyme lointain : on n'y monte
        pas et on n'y descend pas. Un arrêt pris tel quel (marche nulle, nom
        dit par l'usager) n'est pas concerné.
        """

        if access.walk.distance_m <= 0:
            return True
        stop = self.network.stop_for(node)
        general = self.network.coords(stop)
        sur_ligne = self.network.position_on_line(self.network.line_for(node), node.index)
        if general is None or sur_ligne is None:
            return True
        return haversine_m(general, sur_ligne) <= MAX_ECART_HOMONYME_M

    def _endpoint_map(
        self,
        candidates: list[PlaceCandidate],
        kind: str,
        include_nearby: bool = True,
        nearby_stop_ok: Callable[[str], bool] | None = None,
    ) -> dict[str, AccessPoint]:
        result: dict[str, AccessPoint] = {}
        for candidate in candidates:
            for point in self._access_points(
                candidate, kind, include_nearby, nearby_stop_ok
            ):
                current = result.get(point.stop)
                if current is None or point.walk.minutes < current.walk.minutes:
                    result[point.stop] = point
        return result

    @staticmethod
    def _is_downtown_endpoint(
        candidates: list[PlaceCandidate],
        coords: tuple[float, float] | None,
        centre: tuple[float, float] | None,
    ) -> bool:
        if any(candidate.normalized in DOWNTOWN_STOP_NAMES for candidate in candidates):
            return True
        if centre is not None and coords is not None:
            return haversine_m(coords, centre) <= DOWNTOWN_RADIUS_M
        return False

    # ------------------------------------------------------------------
    # Public API.
    # ------------------------------------------------------------------
    def find_trips(
        self,
        origin: str,
        destination: str,
        max_trips: int = 3,
        operator: str | None = None,
        first_line: LineKey | None = None,
        origin_place: ResolvedPlace | None = None,
        destination_place: ResolvedPlace | None = None,
        nearby_stop_ok: Callable[[str], bool] | None = None,
        direct_only: bool = False,
    ) -> list[Trip]:
        """Les meilleurs trajets.  ``origin_place`` et ``destination_place``
        remplacent la recherche par nom quand l'appelant a déjà résolu le lieu ;
        ``nearby_stop_ok`` dit quels arrêts peuvent servir d'arrêt « proche » ;
        ``direct_only`` se limite aux bus directs entre les arrêts demandés.
        """

        max_trips = max(1, max_trips)
        origin_matches = (
            self._candidates_for(origin_place)
            if origin_place is not None
            else prefer_exact_matches(self.place_index.match(origin), origin)
        )
        if not origin_matches:
            raise PlaceNotFoundError(origin, self.place_index.suggestions(origin))

        destination_matches = (
            self._candidates_for(destination_place)
            if destination_place is not None
            else prefer_exact_matches(
                self.place_index.match(destination), destination
            )
        )
        if not destination_matches:
            raise PlaceNotFoundError(
                destination, self.place_index.suggestions(destination)
            )

        origin_points = self._endpoint_map(
            origin_matches, "access", include_nearby=False
        )
        destination_points = self._endpoint_map(
            destination_matches, "egress", include_nearby=False
        )
        expanded_origin_points = self._endpoint_map(
            origin_matches, "access", nearby_stop_ok=nearby_stop_ok
        )
        expanded_destination_points = self._endpoint_map(
            destination_matches, "egress", nearby_stop_ok=nearby_stop_ok
        )
        if not expanded_origin_points:
            raise PlaceNotFoundError(origin, self.place_index.suggestions(origin))
        if not expanded_destination_points:
            raise PlaceNotFoundError(
                destination, self.place_index.suggestions(destination)
            )

        origin_coords = (origin_place and origin_place.coords) or (
            representative_coordinates(origin_matches)
        )
        destination_coords = (destination_place and destination_place.coords) or (
            representative_coordinates(destination_matches)
        )

        # La marche peut battre le bus sur les courtes distances.  On garde
        # ce trajet à part : il ne remplace le bus que s'il est plus rapide.
        walk_trip: Trip | None = None
        if origin_coords is not None and destination_coords is not None:
            walk_time = walking_minutes(origin_coords, destination_coords)
            if walk_time <= MAX_WALK_ONLY_MINUTES:
                straight = haversine_m(origin_coords, destination_coords)
                walk_distance = straight * WALK_DETOUR_FACTOR
                walk_trip = Trip(
                    legs=(),
                    walks=(
                        Walk(
                            kind="walk",
                            from_place=origin,
                            to_place=destination,
                            minutes=walk_time,
                            distance_m=walk_distance,
                            after_leg=0,
                        ),
                    ),
                    total_minutes=walk_time,
                    transfers=0,
                    line_combo=(),
                    origin_name=origin,
                    destination_name=destination,
                    total_distance_m=walk_distance,
                    straight_line_m=straight,
                    detour=False,
                    via_downtown=False,
                    ridden_stops=(),
                )

        centre = self.network.downtown_centre
        origin_is_downtown = self._is_downtown_endpoint(
            origin_matches, origin_coords, centre
        )
        destination_is_downtown = self._is_downtown_endpoint(
            destination_matches, destination_coords, centre
        )

        def search(
            access_points: dict[str, AccessPoint],
            egress_points: dict[str, AccessPoint],
        ) -> list[Trip]:
            return self._search(
                origin_points=access_points,
                destination_points=egress_points,
                origin_name=origin,
                destination_name=destination,
                origin_coords=origin_coords,
                destination_coords=destination_coords,
                origin_is_downtown=origin_is_downtown,
                destination_is_downtown=destination_is_downtown,
                max_trips=max_trips,
                operator=operator,
                first_line=first_line,
                # Sans bus trouvé, rien ne bornerait la recherche : la marche le fait.
                score_limit=walk_trip.total_minutes if walk_trip else float("inf"),
            )

        # Comme v1 : le trajet direct d'abord.  S'il existe, inutile de chercher
        # des changements que l'affichage ne proposera pas.
        def direct(
            access_points: dict[str, AccessPoint],
            egress_points: dict[str, AccessPoint],
        ) -> list[Trip]:
            return self._direct_trips(
                access_points,
                egress_points,
                operator,
                first_line,
                origin_name=origin,
                destination_name=destination,
                origin_coords=origin_coords,
                destination_coords=destination_coords,
                origin_is_downtown=origin_is_downtown,
                destination_is_downtown=destination_is_downtown,
            )

        trips = direct(origin_points, destination_points)
        if not trips and not direct_only:
            trips = search(origin_points, destination_points)
            if (
                expanded_origin_points != origin_points
                or expanded_destination_points != destination_points
            ):
                # Si la recherche exacte a trouvé, les arrêts proches ne peuvent plus
                # ajouter qu'un bus direct : un changement avec marche serait écarté
                # plus bas.  Inutile de refaire toute la recherche (jusqu'à 7 s).
                trips += (
                    direct(expanded_origin_points, expanded_destination_points)
                    if trips
                    else search(expanded_origin_points, expanded_destination_points)
                )
        # L'appelant de ``direct_only`` trie d'abord les arrêts selon ses règles :
        # c'est lui qui applique ensuite ce filtre, sinon un arrêt qu'il écartera
        # pourrait disqualifier les bons.
        if not direct_only:
            trips = keep_sensible_trips(trips)

        # Un bus direct depuis l'arrêt demandé jusqu'à l'arrêt demandé : aucun
        # voisin à pied ne le remplace.  Les arrêts proches ne servent que s'il
        # n'y en a pas.
        if any(
            trip.transfers == 0 and not _has_endpoint_walk(trip) for trip in trips
        ):
            trips = [trip for trip in trips if not _has_endpoint_walk(trip)]

        # The exact stop remains the primary choice.  A nearby stop may add a
        # direct option, but it must not replace a normal exact-stop route
        # with a walk plus extra transfers.
        if any(not _has_endpoint_walk(trip) for trip in trips):
            trips = [
                trip
                for trip in trips
                if trip.transfers == 0 or not _has_endpoint_walk(trip)
            ]

        # ``rank_trips`` ne garde que le plus court par ligne : en direct seul, le
        # choix de l'arrêt sur chaque ligne revient à l'appelant.
        result = (
            list(trips)
            if direct_only
            else remove_dominated_trips(rank_trips(trips), self.network)[:max_trips]
        )

        if walk_trip is not None:
            fastest_bus = min(
                (trip.total_minutes for trip in trips), default=None
            )
            if fastest_bus is None or walk_trip.total_minutes < fastest_bus:
                result = [walk_trip] + result
                result = result[:max_trips]

        if not result:
            raise NoRouteFoundError(
                f"No bus trip found between {origin!r} and {destination!r}."
            )
        return result

    # ------------------------------------------------------------------
    # Search.
    # ------------------------------------------------------------------
    @staticmethod
    def _start_label(stop: str, access: AccessPoint, node: Node) -> _Label:
        access_step = _Step(
            kind="access",
            from_stop=access.walk.from_place,
            to_stop=stop,
            minutes=access.walk.minutes,
            line=node.line,
            direction=node.direction,
            from_index=None,
            to_index=node.index,
            walk_minutes=access.walk.minutes,
            walk_distance_m=access.walk.distance_m,
        )
        return _Label(
            node=node,
            transfers=0,
            cost=access.walk.minutes,
            combo=(node.line,),
            steps=(access_step,),
            rode_since_transfer=False,
        )

    def _direct_trips(
        self,
        origin_points: dict[str, AccessPoint],
        destination_points: dict[str, AccessPoint],
        operator: str | None,
        first_line: LineKey | None,
        **contexte,
    ) -> list[Trip]:
        """Tous les bus directs entre ces arrêts, en suivant simplement chaque ligne.

        À part de la recherche par score : un direct lent ne doit pas être perdu
        derrière des trajets à changements.  Tata 54 fait Keur Massar -> UCAD sans
        changement, et l'usager le préfère à trois bus plus courts sur la carte.
        """

        trips: list[Trip] = []
        for stop, access in origin_points.items():
            for node in self.network.nodes_at_stop(stop):
                if first_line is not None and node.line != first_line:
                    continue
                if operator is not None and node.line[0] != operator:
                    continue
                if not self._noeud_au_lieu_marche(node, access):
                    continue
                label = self._start_label(stop, access, node)
                while True:
                    ride = next(
                        (
                            edge
                            for edge in self.network.adjacency[label.node]
                            if edge.kind == "ride"
                        ),
                        None,
                    )
                    if ride is None:
                        break
                    label = self._advance_ride(label, ride)
                    destination = destination_points.get(
                        self.network.stop_for(label.node)
                    )
                    if destination is not None and self._noeud_au_lieu_marche(
                        label.node, destination
                    ):
                        trips.append(
                            self._build_trip(
                                label=label, destination=destination, **contexte
                            )
                        )
        return trips

    def _search(
        self,
        origin_points: dict[str, AccessPoint],
        destination_points: dict[str, AccessPoint],
        origin_name: str,
        destination_name: str,
        origin_coords: tuple[float, float] | None,
        destination_coords: tuple[float, float] | None,
        origin_is_downtown: bool,
        destination_is_downtown: bool,
        max_trips: int,
        operator: str | None = None,
        first_line: LineKey | None = None,
        score_limit: float = float("inf"),
    ) -> list[Trip]:
        queue: list[tuple[float, int, float, int, _Label]] = []
        counter = itertools.count()
        best_score = score_limit

        # Recherche guidée (A*) : le temps minimal restant, à vol d'oiseau, s'ajoute à
        # la priorité.  Sans cela, 72 000 correspondances font explorer toute la ville
        # avant d'avancer vers l'arrivée (jusqu'à 44 s par requête).
        goals = [
            coords
            for stop in destination_points
            if (coords := self.network.coords(stop)) is not None
        ]
        remaining_by_stop: dict[str, float] = {}

        def remaining(node: Node) -> float:
            stop = self.network.stop_for(node)
            value = remaining_by_stop.get(stop)
            if value is None:
                here = self.network.coords(stop)
                value = (
                    min(haversine_m(here, goal) for goal in goals)
                    / BUS_SPEED_M_PER_MIN
                    if here is not None and goals
                    else 0.0
                )
                remaining_by_stop[stop] = value
            return value

        best: dict[tuple[Node, int], list[_Label]] = defaultdict(list)
        recorded: dict[tuple[LineKey, ...], Trip] = {}
        accepted: list[Trip] = []

        for stop, access in origin_points.items():
            for node in self.network.nodes_at_stop(stop):
                if first_line is not None and node.line != first_line:
                    continue
                if operator is not None and node.line[0] != operator:
                    continue
                if not self._noeud_au_lieu_marche(node, access):
                    continue
                self._push(
                    queue, best, counter, self._start_label(stop, access, node), remaining
                )

        expansions = 0
        while queue:
            score_so_far, _, _, _, label = heapq.heappop(queue)
            state = (label.node, label.transfers)
            if not any(existing is label for existing in best[state]):
                continue

            expansions += 1
            if expansions > MAX_EXPANSIONS:
                break
            if score_so_far >= best_score + MAX_SCORE_ABOVE_BEST:
                break

            # Queue order is score order, so this lower bound is final.
            if len(accepted) >= max_trips:
                worst_score = max(trip.score for trip in accepted)
                if score_so_far >= worst_score:
                    break

            stop = self.network.stop_for(label.node)
            destination = destination_points.get(stop)
            if (
                destination is not None
                and label.rode_since_transfer
                and self._noeud_au_lieu_marche(label.node, destination)
            ):
                trip = self._build_trip(
                    label=label,
                    destination=destination,
                    origin_name=origin_name,
                    destination_name=destination_name,
                    origin_coords=origin_coords,
                    destination_coords=destination_coords,
                    origin_is_downtown=origin_is_downtown,
                    destination_is_downtown=destination_is_downtown,
                )
                best_score = min(best_score, trip.score)
                current = recorded.get(trip.line_combo)
                if current is None or self._trip_rank(trip) < self._trip_rank(current):
                    recorded[trip.line_combo] = trip

                if not trip.via_downtown:
                    accepted.append(trip)
                    accepted = self._best_accepted(accepted, max_trips)

            for edge in self.network.adjacency[label.node]:
                if edge.kind == "ride":
                    self._push(
                        queue,
                        best,
                        counter,
                        self._advance_ride(label, edge),
                        remaining,
                    )
                else:
                    if label.transfers >= MAX_TRANSFERS:
                        continue
                    if not label.rode_since_transfer:
                        continue
                    if operator is not None and edge.target.line[0] != operator:
                        continue
                    if edge.target.line in label.combo:
                        continue
                    self._push(
                        queue,
                        best,
                        counter,
                        self._advance_transfer(label, edge),
                        remaining,
                    )

        return list(recorded.values())

    @staticmethod
    def _trip_rank(
        trip: Trip,
    ) -> tuple[bool, bool, float, int, float, float]:
        # Prefer a clean trip over a detour, and a non-downtown trip over a
        # downtown shortcut, even if the clean version is slightly slower.
        score, minutes, distance, transfers = _rank_key(trip)
        return (
            trip.detour,
            trip.via_downtown,
            score,
            transfers,
            minutes,
            distance,
        )

    @staticmethod
    def _best_accepted(trips: list[Trip], max_trips: int) -> list[Trip]:
        unique: dict[tuple[LineKey, ...], Trip] = {}
        for trip in trips:
            current = unique.get(trip.line_combo)
            if current is None or _rank_key(trip) < _rank_key(current):
                unique[trip.line_combo] = trip

        if not unique:
            return []
        limit = _slowest_sensible(
            min(trip.total_minutes for trip in unique.values())
        )
        reasonable = [
            trip for trip in unique.values() if trip.total_minutes <= limit
        ]
        return rank_trips(reasonable, max_trips)

    def _push(
        self,
        queue: list[tuple[float, int, float, int, _Label]],
        best: dict[tuple[Node, int], list[_Label]],
        counter,
        label: _Label,
        remaining: Callable[[Node], float],
    ) -> None:
        state = (label.node, label.transfers)
        current = best[state]

        # A state can be reached with different line combinations.  Keep
        # a small set of them, but never keep the same combination twice.
        for existing in list(current):
            if (
                existing.combo == label.combo
                and existing.rode_since_transfer == label.rode_since_transfer
            ):
                if existing.cost <= label.cost + 1e-9:
                    return
                current.remove(existing)

        current.append(label)
        current.sort(key=lambda item: item.cost)
        if len(current) > MAX_LABELS_PER_STATE:
            del current[MAX_LABELS_PER_STATE:]

        heapq.heappush(
            queue,
            (
                label.cost
                + TRANSFER_SCORE_MINUTES * label.transfers
                + remaining(label.node),
                label.transfers,
                label.cost,
                next(counter),
                label,
            ),
        )

    def _advance_ride(self, label: _Label, edge: Edge) -> _Label:
        from_stop = self.network.stop_for(label.node)
        to_stop = self.network.stop_for(edge.target)
        step = _Step(
            kind="ride",
            from_stop=from_stop,
            to_stop=to_stop,
            minutes=edge.minutes,
            line=label.node.line,
            direction=label.node.direction,
            from_index=label.node.index,
            to_index=edge.target.index,
            distance_m=edge.distance_m,
            estimated=edge.estimated,
        )
        return _Label(
            node=edge.target,
            transfers=label.transfers,
            cost=label.cost + edge.minutes,
            combo=label.combo,
            steps=label.steps + (step,),
            rode_since_transfer=True,
        )

    def _advance_transfer(self, label: _Label, edge: Edge) -> _Label:
        from_stop = self.network.stop_for(label.node)
        to_stop = self.network.stop_for(edge.target)
        step = _Step(
            kind="transfer",
            from_stop=from_stop,
            to_stop=to_stop,
            minutes=edge.minutes,
            line=edge.target.line,
            direction=edge.target.direction,
            from_index=label.node.index,
            to_index=edge.target.index,
            walk_minutes=edge.walk_minutes,
            walk_distance_m=edge.walk_distance_m,
            transfer_penalty=edge.transfer_penalty,
        )
        return _Label(
            node=edge.target,
            transfers=label.transfers + 1,
            cost=label.cost + edge.minutes,
            combo=label.combo + (edge.target.line,),
            steps=label.steps + (step,),
            rode_since_transfer=False,
        )

    # ------------------------------------------------------------------
    # Turning a search label into a friendly Trip.
    # ------------------------------------------------------------------
    def _build_trip(
        self,
        label: _Label,
        destination: AccessPoint,
        origin_name: str,
        destination_name: str,
        origin_coords: tuple[float, float] | None,
        destination_coords: tuple[float, float] | None,
        origin_is_downtown: bool,
        destination_is_downtown: bool,
    ) -> Trip:
        alight_stop = self.network.stop_for(label.node)
        egress_step = _Step(
            kind="egress",
            from_stop=alight_stop,
            to_stop=destination.walk.to_place,
            minutes=destination.walk.minutes,
            line=label.node.line,
            direction=label.node.direction,
            from_index=label.node.index,
            to_index=None,
            walk_minutes=destination.walk.minutes,
            walk_distance_m=destination.walk.distance_m,
        )
        steps = label.steps + (egress_step,)

        legs: list[Leg] = []
        walks: list[Walk] = []
        ridden_stops: list[str] = []
        current: dict | None = None
        minimum_leg_extra = 0.0

        def finish_leg() -> None:
            nonlocal current, minimum_leg_extra
            if current is None:
                return
            line = self.network.lines[current["line"]]
            billed_minutes = max(MIN_LEG_MINUTES, current["minutes"])
            minimum_leg_extra += billed_minutes - current["minutes"]
            legs.append(
                Leg(
                    operator=line.company,
                    line=line.name,
                    board_stop=current["board_stop"],
                    alight_stop=current["alight_stop"],
                    direction=line.terminus_for(current["direction"]),
                    num_stops=abs(
                        int(current["end_index"]) - int(current["start_index"])
                    ),
                    minutes=billed_minutes,
                    distance_m=current["distance"],
                    estimated=current["estimated"],
                )
            )
            current = None

        for step in steps:
            if step.kind == "access":
                if step.walk_minutes > 0 or (step.walk_distance_m or 0) > 0:
                    walks.append(
                        Walk(
                            kind="access",
                            from_place=step.from_stop,
                            to_place=step.to_stop,
                            minutes=step.walk_minutes,
                            distance_m=step.walk_distance_m,
                            after_leg=0,
                        )
                    )
            elif step.kind == "ride":
                if (
                    current is None
                    or current["line"] != step.line
                    or current["direction"] != step.direction
                ):
                    finish_leg()
                    current = {
                        "line": step.line,
                        "direction": step.direction,
                        "board_stop": step.from_stop,
                        "alight_stop": step.to_stop,
                        "start_index": step.from_index,
                        "end_index": step.to_index,
                        "minutes": step.minutes,
                        "distance": step.distance_m,
                        "estimated": step.estimated,
                    }
                else:
                    current["alight_stop"] = step.to_stop
                    current["end_index"] = step.to_index
                    current["minutes"] += step.minutes
                    current["estimated"] = current["estimated"] or step.estimated
                    if (
                        current["distance"] is None
                        or step.distance_m is None
                    ):
                        current["distance"] = None
                    else:
                        current["distance"] += step.distance_m
                for stop in (step.from_stop, step.to_stop):
                    if not ridden_stops or ridden_stops[-1] != stop:
                        ridden_stops.append(stop)
            elif step.kind == "transfer":
                finish_leg()
                if step.walk_minutes > 0 or (step.walk_distance_m or 0) > 0:
                    walks.append(
                        Walk(
                            kind="transfer",
                            from_place=step.from_stop,
                            to_place=step.to_stop,
                            minutes=step.walk_minutes,
                            distance_m=step.walk_distance_m,
                            after_leg=len(legs),
                        )
                    )
            elif step.kind == "egress":
                finish_leg()
                if step.walk_minutes > 0 or (step.walk_distance_m or 0) > 0:
                    walks.append(
                        Walk(
                            kind="egress",
                            from_place=step.from_stop,
                            to_place=step.to_stop,
                            minutes=step.walk_minutes,
                            distance_m=step.walk_distance_m,
                            after_leg=len(legs),
                        )
                    )

        finish_leg()

        total_minutes = sum(step.minutes for step in steps) + minimum_leg_extra

        total_distance: float | None = 0.0
        for step in steps:
            if step.kind == "ride":
                if step.distance_m is None:
                    total_distance = None
                    break
                total_distance += step.distance_m
            else:
                total_distance += step.walk_distance_m or 0.0

        straight_line: float | None = None
        if origin_coords is not None and destination_coords is not None:
            straight_line = haversine_m(origin_coords, destination_coords)

        detour = bool(
            total_distance is not None
            and straight_line is not None
            and total_distance > DETOUR_LIMIT * straight_line
        )
        via_downtown = self._passes_downtown(
            ridden_stops,
            origin_is_downtown=origin_is_downtown,
            destination_is_downtown=destination_is_downtown,
        )

        return Trip(
            legs=tuple(legs),
            walks=tuple(walks),
            total_minutes=total_minutes,
            transfers=label.transfers,
            line_combo=label.combo,
            origin_name=origin_name,
            destination_name=destination_name,
            total_distance_m=total_distance,
            straight_line_m=straight_line,
            detour=detour,
            via_downtown=via_downtown,
            ridden_stops=tuple(ridden_stops),
            estimated=any(leg.estimated for leg in legs),
        )

    def _passes_downtown(
        self,
        ridden_stops: list[str],
        origin_is_downtown: bool,
        destination_is_downtown: bool,
    ) -> bool:
        if origin_is_downtown or destination_is_downtown:
            return False

        if any(normalize_name(stop) in DOWNTOWN_STOP_NAMES for stop in ridden_stops):
            return True

        centre = self.network.downtown_centre
        if centre is None:
            return False
        for stop in ridden_stops:
            coords = self.network.coords(stop)
            if coords is not None and haversine_m(coords, centre) <= DOWNTOWN_RADIUS_M:
                return True
        return False