File size: 48,903 Bytes
567bad0
 
8f17b5a
567bad0
4ef265f
 
567bad0
 
 
 
 
 
 
 
4ef265f
 
567bad0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4ef265f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
567bad0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20d6c33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
567bad0
 
 
6a6544b
567bad0
 
 
 
 
 
 
 
6a6544b
567bad0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20d6c33
 
567bad0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20d6c33
 
 
67694a2
 
 
 
 
 
 
20d6c33
67694a2
 
 
 
 
 
 
 
567bad0
 
 
 
 
 
 
 
 
6a6544b
67694a2
6a6544b
 
 
 
 
 
 
 
 
 
 
 
 
567bad0
20d6c33
 
 
 
67694a2
 
 
 
6a6544b
20d6c33
 
6a6544b
67694a2
20d6c33
 
567bad0
 
20d6c33
567bad0
 
 
 
 
 
4ef265f
567bad0
 
 
 
 
 
 
 
 
 
 
 
8f17b5a
 
567bad0
 
 
4ef265f
567bad0
4ef265f
 
 
567bad0
4ef265f
567bad0
 
4ef265f
 
567bad0
 
 
 
5a58093
4ef265f
 
567bad0
 
 
4ef265f
567bad0
4ef265f
567bad0
 
 
4ef265f
567bad0
 
 
 
 
5a58093
567bad0
5a58093
567bad0
4ef265f
20d6c33
4ef265f
 
 
 
aaa5f52
4ef265f
5a58093
4ef265f
 
5a58093
4ef265f
 
 
5a58093
 
 
 
567bad0
 
5a58093
 
611fdac
34dd717
 
20d6c33
 
 
 
567bad0
 
 
 
 
8f17b5a
20d6c33
567bad0
 
 
 
 
 
 
 
 
4ef265f
567bad0
 
 
 
 
 
4ef265f
567bad0
 
 
 
 
4ef265f
567bad0
 
4ef265f
 
20d6c33
 
67694a2
 
20d6c33
567bad0
 
 
 
4ef265f
5a58093
4ef265f
 
 
 
5a58093
4ef265f
20d6c33
 
 
 
aaa5f52
4ef265f
 
 
 
 
 
 
 
 
20d6c33
4ef265f
 
567bad0
 
 
 
 
 
 
 
5a58093
567bad0
 
 
 
 
 
 
e91a716
567bad0
 
4ef265f
e91a716
 
567bad0
 
e91a716
567bad0
e91a716
567bad0
e91a716
20d6c33
 
e91a716
611fdac
e91a716
5a58093
e91a716
 
 
 
4c4118f
e91a716
5a58093
567bad0
 
e91a716
 
20d6c33
4ef265f
e91a716
5a58093
 
 
567bad0
5a58093
 
 
 
567bad0
 
5a58093
4ef265f
 
5a58093
4ef265f
5a58093
4ef265f
 
567bad0
4ef265f
567bad0
 
 
 
 
 
 
 
 
5a58093
e91a716
 
567bad0
611fdac
4ef265f
 
567bad0
5a58093
567bad0
 
 
e91a716
567bad0
 
 
 
5a58093
567bad0
 
 
 
 
5a58093
567bad0
5a58093
567bad0
 
 
e91a716
567bad0
 
4ef265f
567bad0
5a58093
567bad0
4ef265f
567bad0
20d6c33
 
5a58093
567bad0
5a58093
567bad0
 
20d6c33
5a58093
 
567bad0
e91a716
5a58093
20d6c33
 
 
 
 
 
567bad0
5a58093
e91a716
 
 
 
5a58093
20d6c33
 
 
 
 
4ef265f
567bad0
20d6c33
 
 
 
 
 
e91a716
 
20d6c33
 
 
e91a716
4ef265f
e91a716
4ef265f
20d6c33
 
 
 
 
 
 
 
 
 
 
 
34dd717
20d6c33
aaa5f52
20d6c33
 
34dd717
20d6c33
 
 
611fdac
4ef265f
 
20d6c33
 
 
 
 
 
 
 
4ef265f
 
 
 
20d6c33
 
e91a716
20d6c33
e91a716
 
 
20d6c33
4ef265f
 
 
20d6c33
 
 
 
 
 
 
 
 
 
4ef265f
 
20d6c33
4ef265f
20d6c33
e91a716
20d6c33
 
 
 
 
 
 
 
 
 
 
 
5a58093
4ef265f
34dd717
20d6c33
67694a2
20d6c33
 
 
 
 
 
 
34dd717
 
20d6c33
 
 
 
 
 
5a58093
 
20d6c33
 
 
 
 
 
 
 
 
 
 
 
 
 
4ef265f
20d6c33
 
 
 
 
aaa5f52
4ef265f
 
20d6c33
e91a716
 
4ef265f
20d6c33
4ef265f
20d6c33
e91a716
 
 
 
4ef265f
 
 
20d6c33
e91a716
 
20d6c33
 
e91a716
 
 
 
20d6c33
 
 
 
 
 
 
 
 
 
 
 
 
aaa5f52
e91a716
20d6c33
 
e91a716
4ef265f
 
 
 
e91a716
 
 
20d6c33
e91a716
 
 
 
20d6c33
e91a716
20d6c33
e91a716
 
20d6c33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4ef265f
20d6c33
4ef265f
20d6c33
 
e91a716
 
67694a2
e91a716
 
20d6c33
e91a716
20d6c33
e91a716
20d6c33
e91a716
 
20d6c33
e91a716
20d6c33
567bad0
e91a716
567bad0
 
e91a716
567bad0
 
 
 
 
 
 
 
4ef265f
567bad0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4ef265f
567bad0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4ef265f
567bad0
4ef265f
 
567bad0
4ef265f
 
 
 
 
 
 
 
 
 
 
20d6c33
4ef265f
567bad0
 
 
 
 
 
 
4ef265f
 
 
 
 
 
 
567bad0
 
 
4ef265f
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
#!/usr/bin/env python3
"""
Route Em -- Hugging Face Space (Docker SDK).

Shortest closed route covering every road on BOTH sides. Directed Chinese Postman,
solved exactly by min-cost flow. Serves on 0.0.0.0:$PORT (HF sets PORT=7860).
"""

import os
import traceback

import requests
from flask import Flask, jsonify, render_template_string, request

# HF Space containers only allow writes to /tmp. Set this BEFORE osmnx imports,
# or the app dies on boot with a permission error.
os.environ.setdefault("HOME", "/tmp")
os.environ.setdefault("MPLCONFIGDIR", "/tmp/mpl")
os.environ.setdefault("XDG_CACHE_HOME", "/tmp/cache")

from collections import defaultdict

import networkx as nx
import osmnx as ox

M_PER_MI = 1609.344

# Guard rails so a fat-fingered giant box doesn't hang the machine.
MAX_REQUIRED_PASSES = 6000
MAX_AREA_SQ_MI = 25.0


class RouteError(Exception):
    """Something the user can fix -- shown in the UI as a friendly message."""


# ---------------------------------------------------------------- area guards
def bbox_area_sq_mi(b):
    import math

    mid = math.radians((b["north"] + b["south"]) / 2)
    h = (b["north"] - b["south"]) * 69.0
    w = (b["east"] - b["west"]) * 69.0 * math.cos(mid)
    return abs(h * w)


def polygon_area_sq_mi(geojson_polygon):
    """Rough but adequate: scale degrees to miles at the polygon's latitude."""
    import math

    from shapely.geometry import shape

    poly = shape(geojson_polygon)
    mid = math.radians(poly.centroid.y)
    return abs(poly.area) * 69.0 * (69.0 * math.cos(mid))


# ---------------------------------------------------------------- load
def graph_from_bbox(north, south, east, west, walking=False, include_service=False):
    net = "walk" if walking else "drive"
    try:
        G = ox.graph_from_bbox(
            (min(west, east), min(south, north), max(west, east), max(south, north)),
            network_type=net,
        )
    except Exception as exc:
        raise RouteError(
            "No road network found in that box. Try a slightly bigger area, "
            f"or one that actually contains streets. ({exc})"
        )
    return _clean(G, include_service)


def graph_from_polygon(geojson_polygon, walking=False, include_service=False):
    from shapely.geometry import shape

    poly = shape(geojson_polygon)
    net = "walk" if walking else "drive"
    try:
        G = ox.graph_from_polygon(poly, network_type=net)
    except Exception as exc:
        raise RouteError(f"No road network found in that area. ({exc})")
    return _clean(G, include_service)


def _clean(G, include_service):
    # Alleys, driveways and parking aisles are not delivery streets.
    if not include_service:
        drop = [
            (u, v, k)
            for u, v, k, d in G.edges(keys=True, data=True)
            if str(d.get("highway", "")).startswith("service")
            or "driveway" in str(d.get("service", ""))
            or "parking_aisle" in str(d.get("service", ""))
        ]
        G.remove_edges_from(drop)
        G.remove_nodes_from(list(nx.isolates(G)))
    if G.number_of_edges() == 0:
        raise RouteError("That area has no deliverable streets in OpenStreetMap.")
    return G


# ---------------------------------------------------------------- both sides
def build_both_sides(G, walking=False):
    """One directed edge per required pass. Two-way street -> two passes."""
    R = nx.MultiDiGraph()
    R.graph["crs"] = G.graph.get("crs", "epsg:4326")
    for n, d in G.nodes(data=True):
        R.add_node(n, **d)

    for u, v, k, d in G.edges(keys=True, data=True):
        L = float(d.get("length", 0.0))
        name = d.get("name", "unnamed road")
        if isinstance(name, list):
            name = name[0]
        oneway = bool(d.get("oneway", False)) and not walking

        R.add_edge(u, v, length=L, name=name, required=True)
        if not oneway and not G.has_edge(v, u):
            # Two-way street that OSM only stored one way -- add the return curb.
            R.add_edge(v, u, length=L, name=name, required=True)

    R.remove_nodes_from(list(nx.isolates(R)))
    if R.number_of_edges() > MAX_REQUIRED_PASSES:
        raise RouteError(
            f"That area needs {R.number_of_edges():,} passes "
            f"(limit {MAX_REQUIRED_PASSES:,}). Draw a smaller box -- "
            "one neighborhood at a time."
        )
    return R


# ---------------------------------------------------------------- solve
def solve_dcpp(R):
    """Returns (R_connected, EulerianGraph, repeat_edges)."""
    if not nx.is_strongly_connected(R):
        big = max(nx.strongly_connected_components(R), key=len)
        excluded = R.number_of_nodes() - len(big)
        R = R.subgraph(big).copy()
        R.graph["excluded_nodes"] = excluded
    else:
        R.graph["excluded_nodes"] = 0

    if R.number_of_edges() == 0:
        raise RouteError("No connected road network in that area.")

    # excess > 0 -> more ways OUT than IN -> node needs extra INBOUND passes.
    # So every repeat path runs FROM a deficit node TO a surplus node.
    imbalance = {n: R.out_degree(n) - R.in_degree(n) for n in R.nodes}
    surplus = [n for n, b in imbalance.items() if b > 0]
    deficit = [n for n, b in imbalance.items() if b < 0]

    repeats = []
    if surplus:
        sp = {t: nx.single_source_dijkstra_path_length(R, t, weight="length") for t in deficit}
        paths = {t: nx.single_source_dijkstra_path(R, t, weight="length") for t in deficit}

        F = nx.DiGraph()
        for n in surplus + deficit:
            F.add_node(n, demand=imbalance[n])  # +ve consumes flow, -ve supplies it
        for t in deficit:
            for s in surplus:
                if s in sp[t]:
                    F.add_edge(t, s, weight=int(round(sp[t][s])), capacity=R.number_of_nodes())

        try:
            _, flow = nx.network_simplex(F)
        except nx.NetworkXUnfeasible:
            raise RouteError(
                "Could not balance the network -- some streets are unreachable "
                "(likely a one-way trap at the edge of the box). Try a bigger box."
            )

        for t, targets in flow.items():
            for s, units in targets.items():
                for _ in range(units):
                    p = paths[t][s]
                    repeats += list(zip(p[:-1], p[1:]))

    E = nx.MultiDiGraph(R)
    for u, v in repeats:
        d = min(R[u][v].values(), key=lambda x: x["length"])
        E.add_edge(u, v, length=d["length"], name=d.get("name"), required=False)
    return R, E, repeats


def build_route(E, start_node=None):
    if not nx.is_eulerian(E):
        raise RouteError("Internal: graph did not become Eulerian.")
    steps = []
    for u, v, k in nx.eulerian_circuit(E, source=start_node, keys=True):
        d = E[u][v][k]
        steps.append(
            {
                "u": u,
                "v": v,
                "length": d["length"],
                "name": d.get("name") or "unnamed road",
                "deadhead": not d.get("required", True),
            }
        )
    return steps


# ---------------------------------------------------------------- pair helper
def _pair(u, v):
    """Stable key for the physical street between two nodes (both directions share it)."""
    return "%s_%s" % (min(u, v), max(u, v))


# ---------------------------------------------------------------- drive-each-street-once
def solve_cpp_once(G, walking=False):
    """Undirected Chinese Postman: cover every street ONCE, minimal driving.
    Returns (U_required_undirected, E_eulerian, repeat_edges)."""
    U = nx.MultiGraph()
    U.graph["crs"] = G.graph.get("crs", "epsg:4326")
    for n, d in G.nodes(data=True):
        U.add_node(n, **d)

    seen = set()
    for u, v, k, d in G.edges(keys=True, data=True):
        if (v, u, k) in seen:        # reverse of an already-added two-way street
            continue
        seen.add((u, v, k))
        name = d.get("name", "unnamed road")
        if isinstance(name, list):
            name = name[0]
        U.add_edge(u, v, length=float(d.get("length", 0.0)), name=name, required=True)

    U.remove_nodes_from(list(nx.isolates(U)))
    if U.number_of_edges() == 0:
        raise RouteError("That area has no deliverable streets in OpenStreetMap.")
    if not nx.is_connected(U):
        U = U.subgraph(max(nx.connected_components(U), key=len)).copy()
    if U.number_of_edges() > MAX_REQUIRED_PASSES:
        raise RouteError(
            "That area needs %d street passes (limit %d). Draw a smaller area."
            % (U.number_of_edges(), MAX_REQUIRED_PASSES))

    # make it Eulerian: min-weight matching of odd-degree nodes, duplicate those paths
    import itertools

    odd = [n for n, deg in U.degree() if deg % 2 == 1]
    E = nx.MultiGraph(U)
    repeats = []
    if odd:
        dist, path = {}, {}
        for o in odd:
            dl, pp = nx.single_source_dijkstra(U, o, weight="length")
            dist[o], path[o] = dl, pp
        K = nx.Graph()
        for a, b in itertools.combinations(odd, 2):
            if b in dist[a]:
                K.add_edge(a, b, weight=dist[a][b])
        for a, b in nx.min_weight_matching(K):
            p = path[a][b]
            for x, y in zip(p[:-1], p[1:]):
                seg = min(U[x][y].values(), key=lambda e: e["length"])
                E.add_edge(x, y, length=seg["length"], name=seg.get("name"), required=False)
                repeats.append((x, y))
    return U, E, repeats


# ---------------------------------------------------------------- outputs
def compute_stats(R, steps, repeats):
    total_m = sum(s["length"] for s in steps)
    required_m = sum(s["length"] for s in steps if not s["deadhead"])
    dead_m = sum(s["length"] for s in steps if s["deadhead"])

    by_road = defaultdict(float)
    for s in steps:
        if not s["deadhead"]:
            by_road[s["name"]] += s["length"]

    return {
        "required_passes": sum(1 for s in steps if not s["deadhead"]),
        "streets": len(by_road),
        "min_mi": required_m / M_PER_MI,
        "deadhead_mi": dead_m / M_PER_MI,
        "total_mi": total_m / M_PER_MI,
        "efficiency_pct": required_m / total_m * 100 if total_m else 0,
        "overhead_pct": dead_m / required_m * 100 if required_m else 0,
        "repeats": len(repeats),
        "steps": len(steps),
        "drive_min": total_m / M_PER_MI / 12.0 * 60,
        "walk_min": total_m / M_PER_MI / 2.5 * 60,
        "excluded_nodes": R.graph.get("excluded_nodes", 0),
        "longest": sorted(
            [{"name": n, "mi": m / M_PER_MI} for n, m in by_road.items()],
            key=lambda x: -x["mi"],
        )[:15],
    }


def route_geojson(E, steps):
    """Each move as a LineString, tagged with its order so the map can color-ramp it."""
    feats = []
    for i, s in enumerate(steps):
        feats.append(
            {
                "type": "Feature",
                "geometry": {
                    "type": "LineString",
                    "coordinates": [
                        [E.nodes[s["u"]]["x"], E.nodes[s["u"]]["y"]],
                        [E.nodes[s["v"]]["x"], E.nodes[s["v"]]["y"]],
                    ],
                },
                "properties": {
                    "order": i + 1,
                    "name": s["name"],
                    "mi": round(s["length"] / M_PER_MI, 3),
                    "deadhead": s["deadhead"],
                    "pair": s.get("pair"),
                    "needed": s.get("needed", 1),
                },
            }
        )
    return {"type": "FeatureCollection", "features": feats}


def turn_by_turn(steps):
    """Collapse consecutive moves on the same street into single instructions."""
    out, cur = [], None
    for s in steps:
        if cur and cur["name"] == s["name"] and cur["deadhead"] == s["deadhead"]:
            cur["mi"] += s["length"] / M_PER_MI
        else:
            if cur:
                out.append(cur)
            cur = {"name": s["name"], "mi": s["length"] / M_PER_MI, "deadhead": s["deadhead"]}
    if cur:
        out.append(cur)
    for i, o in enumerate(out):
        o["step"] = i + 1
        o["mi"] = round(o["mi"], 2)
    return out


# ---------------------------------------------------------------- one-shot
def solve(G, walking=False, start_lat=None, start_lon=None, coverage="both"):
    """Graph in, everything out. Verifies full coverage before returning.

    coverage="once"    : drive every street a single time (minimal driving).
    coverage="figure8" : drive the whole efficient loop ONE way, then the SAME loop in
                         reverse -- a there-and-back so you cover the opposite side of
                         every street on the way back. Predictable, no zig-zag.
    coverage="optimal" : shortest-distance route that still covers both directions of
                         every two-way street (directed Chinese Postman). Least total
                         miles, but interleaves the two sides so it doubles back a lot.
    """
    if coverage == "optimal" or coverage == "both":
        # directed both-sides, minimum total distance (the original solver)
        R = build_both_sides(G, walking)
        R, E, repeats = solve_dcpp(R)
    else:
        # both "once" and "figure8" start from the efficient single-pass loop
        R, E, repeats = solve_cpp_once(G, walking)
        R.graph.setdefault("excluded_nodes", 0)

    start = None
    if start_lat is not None and start_lon is not None:
        try:
            start = ox.nearest_nodes(E, float(start_lon), float(start_lat))
        except Exception:
            start = None

    steps = build_route(E, start)

    if coverage == "figure8":
        # append the same loop reversed: swap each move's direction, reverse order.
        back = [
            {"u": s["v"], "v": s["u"], "length": s["length"],
             "name": s["name"], "deadhead": s["deadhead"]}
            for s in reversed(steps)
        ]
        steps = steps + back

    # required passes per street, counted straight from the final route
    needed = defaultdict(int)
    for s in steps:
        if not s["deadhead"]:
            needed[_pair(s["u"], s["v"])] += 1
    for s in steps:
        pk = _pair(s["u"], s["v"])
        s["pair"] = pk
        s["needed"] = 0 if s["deadhead"] else needed.get(pk, 1)

    # Hard guarantee: every required street is covered at least what the graph asks for.
    need_ct = defaultdict(int)
    for u, v in R.edges():
        need_ct[_pair(u, v)] += 1
    have = defaultdict(int)
    for s in steps:
        if not s["deadhead"]:
            have[s["pair"]] += 1
    short = [p for p, c in need_ct.items() if have[p] < c]
    if short:
        raise RouteError("Internal: %d streets not fully covered." % len(short))

    return {
        "coverage": coverage,
        "stats": compute_stats(R, steps, repeats),
        "geojson": route_geojson(E, steps),
        "directions": turn_by_turn(steps),
    }


# Keep osmnx's HTTP cache in /tmp -- the only writable path on a Space.
ox.settings.cache_folder = "/tmp/osmnx_cache"
ox.settings.use_cache = True
ox.settings.log_console = False
ox.settings.requests_timeout = 180
ox.settings.overpass_rate_limit = True


# ============================================================ the page
PAGE = r'''<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Route Em</title>
<link rel="icon" type="image/svg+xml" href="data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2064%2064%22%3E%3Crect%20width%3D%2264%22%20height%3D%2264%22%20rx%3D%2213%22%20fill%3D%22%230f1115%22%2F%3E%3Cpath%20d%3D%22M8%2017%2022%2012%2042%2019%2056%2013%2056%2047%2042%2053%2022%2046%208%2051Z%22%20fill%3D%22%23232a36%22%2F%3E%3Cpath%20d%3D%22M8%2017%2022%2012%2042%2019%2056%2013%2056%2024%2042%2030%2022%2023%208%2028Z%22%20fill%3D%22%232b3342%22%2F%3E%3Cpath%20d%3D%22M22%2012%2022%2046M42%2019%2042%2053%22%20stroke%3D%22%230f1115%22%20stroke-width%3D%221.6%22%20opacity%3D%22.85%22%2F%3E%3Cpath%20d%3D%22M15%2044%20Q17%2033%2027%2033%20Q38%2033%2037%2024%20Q36%2017%2047%2019%22%20fill%3D%22none%22%20stroke%3D%22%234f8cff%22%20stroke-width%3D%224.2%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%2F%3E%3Ccircle%20cx%3D%2215%22%20cy%3D%2244%22%20r%3D%224.4%22%20fill%3D%22%232ecc71%22%20stroke%3D%22%230f1115%22%20stroke-width%3D%221.6%22%2F%3E%3Ccircle%20cx%3D%2247%22%20cy%3D%2219%22%20r%3D%224.4%22%20fill%3D%22%23e6c85a%22%20stroke%3D%22%230f1115%22%20stroke-width%3D%221.6%22%2F%3E%3C%2Fsvg%3E">
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css">
<link rel="stylesheet" href="https://unpkg.com/leaflet-draw@1.0.4/dist/leaflet.draw.css">
<style>
  :root{--bg:#0f1115;--panel:#171a21;--line:#262b36;--txt:#e7eaf0;--dim:#98a1b3;--acc:#4f8cff;--ok:#2ecc71;--bad:#d7263d;--warm:#e6c85a}
  *{box-sizing:border-box}
  body{margin:0;font:14px/1.5 -apple-system,Segoe UI,Roboto,sans-serif;background:var(--bg);color:var(--txt);height:100vh;display:flex;flex-direction:column;overflow:hidden}
  header{padding:12px 18px;border-bottom:1px solid var(--line);display:flex;align-items:center;gap:16px;flex-shrink:0}
  h1{margin:0;font-size:16px;font-weight:650}
  .sub{color:var(--dim);font-size:12px}
  main{flex:1;display:grid;grid-template-columns:320px 1fr 330px;min-height:0}
  .pane{border-right:1px solid var(--line);display:flex;flex-direction:column;min-height:0}
  .pane:last-child{border-right:0;border-left:1px solid var(--line);overflow-y:auto}
  .hd{padding:10px 14px;font-size:11px;text-transform:uppercase;letter-spacing:.9px;color:var(--dim);border-bottom:1px solid var(--line);flex-shrink:0}
  #drop{flex:1;margin:14px;border:2px dashed var(--line);border-radius:10px;display:flex;align-items:center;justify-content:center;text-align:center;color:var(--dim);cursor:pointer;overflow:hidden;transition:.15s}
  #drop:hover,#drop.hot{border-color:var(--acc);background:#4f8cff10}
  #drop img{width:100%;height:100%;object-fit:contain}
  #drop .ph{padding:24px}
  #drop .ph b{color:var(--txt);display:block;margin-bottom:6px;font-size:15px}
  #map{flex:1;background:#0b0d11}
  .ctl{padding:10px 14px;border-bottom:1px solid var(--line);display:flex;gap:8px;flex-wrap:wrap;align-items:center;flex-shrink:0}
  input[type=text]{flex:1;min-width:140px;background:#0b0d11;border:1px solid var(--line);color:var(--txt);padding:9px 11px;border-radius:7px;font-size:13px}
  input[type=text]:focus{outline:0;border-color:var(--acc)}
  button{background:var(--acc);color:#fff;border:0;padding:9px 15px;border-radius:7px;font-weight:600;cursor:pointer;font-size:13px}
  button:hover{filter:brightness(1.12)}
  button:disabled{opacity:.4;cursor:not-allowed}
  button.sec{background:#252a35}
  label.ck{display:flex;align-items:center;gap:6px;color:var(--dim);font-size:12px;cursor:pointer;white-space:nowrap}
  .msg{margin:14px;padding:11px 13px;border-radius:8px;font-size:13px;display:none}
  .msg.err{display:block;background:#d7263d22;border:1px solid #d7263d55;color:#ffb3bd}
  .msg.info{display:block;background:#4f8cff18;border:1px solid #4f8cff44;color:#bcd4ff}
  .stat{padding:10px 14px;border-bottom:1px solid var(--line);display:flex;justify-content:space-between;align-items:baseline;gap:10px}
  .stat span{color:var(--dim);font-size:12px}
  .stat b{font-size:15px;font-variant-numeric:tabular-nums}
  .stat.big b{font-size:24px;color:var(--acc)}
  .stat.good b{color:var(--ok)}
  .stat.warn b{color:var(--bad)}
  .street{padding:6px 14px;display:flex;justify-content:space-between;gap:8px;font-size:12px;color:var(--dim);border-bottom:1px solid #1c2028;border-left:3px solid transparent}
  .street b{color:var(--txt);font-variant-numeric:tabular-nums;font-weight:500}
  .street.now{background:#ffffff14;color:var(--txt)}
  .empty{padding:26px 16px;color:var(--dim);font-size:13px;text-align:center;line-height:1.7}
  .mapwrap{position:relative;flex:1;display:flex;min-height:0}
  #play{position:absolute;left:50%;transform:translateX(-50%);bottom:16px;z-index:1000;background:#0f1115f2;border:1px solid var(--line);border-radius:12px;padding:8px 12px;display:none;gap:9px;align-items:center;flex-wrap:wrap;max-width:min(620px,92%);box-shadow:0 4px 18px rgba(0,0,0,.55)}
  #play.on{display:flex}
  #scrub{flex:1;min-width:160px;-webkit-appearance:none;appearance:none;height:5px;border-radius:3px;background:#2b3342;outline:0;cursor:pointer}
  #scrub::-webkit-slider-thumb{-webkit-appearance:none;width:15px;height:15px;border-radius:50%;background:var(--acc);cursor:pointer;border:2px solid #0f1115}
  #scrub::-moz-range-thumb{width:15px;height:15px;border-radius:50%;background:var(--acc);border:2px solid #0f1115;cursor:pointer}
  #pp{min-width:82px;padding:9px 12px;text-align:center;background:#22c55e;color:#05130a}
  select{background:#252a35;color:var(--txt);border:1px solid var(--line);border-radius:7px;padding:8px;font-size:12px;cursor:pointer}
  .hud{position:absolute;top:12px;left:12px;z-index:900;background:#0f1115f2;border:1px solid var(--line);border-radius:9px;padding:10px 13px;min-width:200px;display:none}
  .hud.on{display:block}
  .hud .now{font-size:15px;font-weight:650;margin-bottom:3px}
  .hud .leg{display:inline-block;font-size:10px;font-weight:700;padding:1px 7px;border-radius:9px;color:#05070c;margin-bottom:5px}
  .hud .meta{font-size:11px;color:var(--dim);font-variant-numeric:tabular-nums}
  .hud .bar{height:4px;background:#2b3342;border-radius:3px;margin-top:7px;overflow:hidden}
  .hud .bar i{display:block;height:100%;background:var(--acc);width:0}
  .legend{position:absolute;top:12px;right:12px;z-index:900;background:#0f1115f2;border:1px solid var(--line);padding:10px 12px;border-radius:9px;font-size:11px;line-height:1.7;display:none;max-width:190px}
  .legend .ttl{font-weight:700;color:var(--txt);margin-bottom:5px;font-size:11px;text-transform:uppercase;letter-spacing:.6px}
  .legend .lg{display:flex;align-items:center;gap:7px;color:var(--dim)}
  .sw{display:inline-block;width:16px;height:4px;border-radius:2px;flex-shrink:0}
  .spin{width:14px;height:14px;border:2px solid #ffffff44;border-top-color:#fff;border-radius:50%;display:inline-block;animation:s .7s linear infinite;vertical-align:-2px;margin-right:7px}
  @keyframes s{to{transform:rotate(360deg)}}
  .truck{filter:drop-shadow(0 2px 5px rgba(0,0,0,.7))}
  .arrow{pointer-events:none}
  #map.routed .leaflet-tile-pane{filter:brightness(.72) saturate(.85)}
  .pin{font:700 10px sans-serif;color:#fff;text-align:center;line-height:1;text-shadow:0 1px 3px #000;white-space:nowrap}
  .pin svg{display:block;margin:0 auto}
  .modeseg{display:flex;border:1px solid var(--line);border-radius:8px;overflow:hidden}
  .modeseg button{background:#252a35;border-radius:0;padding:8px 10px;font-size:12px}
  .modeseg button.on{background:var(--acc);color:#fff}
  #gps.on{background:var(--bad)}
</style>
</head>
<body>

<header>
  <h1>Route Em</h1>
  <span class="sub">The shortest driving loop that covers every street in your area</span>
</header>

<main>
  <div class="pane">
    <div class="hd">1 &nbsp;Drop your screenshot</div>
    <div id="drop">
      <div class="ph">
        <b>Drag your map screenshot here</b>
        Or click to choose a file.<br>
        It stays on your machine &mdash; it's your reference for matching the map.
      </div>
      <input type="file" id="file" accept="image/*" hidden>
    </div>
  </div>

  <div class="pane">
    <div class="hd">2 &nbsp;Find the area, then outline it</div>
    <div class="ctl">
      <input type="text" id="q" placeholder="ZIP code, address, or neighborhood...">
      <button id="find" class="sec">Find</button>
    </div>
    <div class="ctl">
      <button id="poly" class="sec">Draw shape</button>
      <button id="box" class="sec">Draw box</button>
      <button id="clear" class="sec">Clear</button>
      <label class="ck"><input type="checkbox" id="walking"> Walking</label>
      <label class="ck"><input type="checkbox" id="svc"> Alleys</label>
      <select id="coverage" title="How thoroughly to cover each street">
        <option value="once" selected>Drive each street once</option>
        <option value="figure8">Both sides — loop then reverse (figure-8)</option>
        <option value="optimal">Both sides — shortest distance</option>
      </select>
      <button id="solve" disabled>Solve route</button>
    </div>
    <div class="mapwrap">
      <div id="map"></div>
      <div class="hud" id="hud">
        <div class="leg" id="hudLeg">Leg 1</div>
        <div class="now" id="hudStreet">&mdash;</div>
        <div class="meta" id="hudMeta">&mdash;</div>
        <div class="bar"><i id="hudBar"></i></div>
      </div>
      <div class="legend" id="legend"></div>
      <div id="play">
        <div class="modeseg">
          <button id="mSim" class="on">&#9654; Simulate</button>
          <button id="mTrack">&#9673; Track</button>
        </div>
        <button id="pp">&#9654; Play</button>
        <button id="restart" class="sec">&#8634;</button>
        <input type="range" id="scrub" min="0" max="1000" value="0">
        <select id="speed">
          <option value="0.5">0.5&times;</option>
          <option value="1" selected>1&times;</option>
          <option value="2">2&times;</option>
          <option value="4">4&times;</option>
          <option value="8">8&times;</option>
        </select>
        <button id="gps" class="sec" style="display:none">Start GPS</button>
        <label class="ck"><input type="checkbox" id="follow" checked> Follow</label>
        <label class="ck"><input type="checkbox" id="arrowsOn" checked> Arrows</label>
      </div>
    </div>
  </div>

  <div class="pane">
    <div class="hd">3 &nbsp;Your route</div>
    <div id="msg" class="msg"></div>
    <div id="out">
      <div class="empty">Drop a screenshot, find the area,<br>outline it, and hit <b>Solve route</b>.</div>
    </div>
  </div>
</main>

<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
<script src="https://unpkg.com/leaflet-draw@1.0.4/dist/leaflet.draw.js"></script>
<script>
// ===== screenshot drop (reference only; never uploaded) =====
const drop = document.getElementById('drop'), file = document.getElementById('file');
drop.onclick = () => file.click();
file.onchange = e => e.target.files[0] && showShot(e.target.files[0]);
['dragenter','dragover'].forEach(t => drop.addEventListener(t, e => { e.preventDefault(); drop.classList.add('hot'); }));
['dragleave','drop'].forEach(t => drop.addEventListener(t, e => { e.preventDefault(); drop.classList.remove('hot'); }));
drop.addEventListener('drop', e => {
  const f = e.dataTransfer.files[0];
  if (f && f.type.startsWith('image/')) showShot(f); else msg('That file is not an image.', 'err');
});
function showShot(f){ const img=document.createElement('img'); img.src=URL.createObjectURL(f); drop.innerHTML=''; drop.appendChild(img); }

// ===== map + basemaps =====
const map = L.map('map', {zoomControl:false}).setView([39.83, -98.58], 4);
L.control.zoom({position:'bottomleft'}).addTo(map);
const streets = L.tileLayer('https://{s}.basemaps.cartocdn.com/rastertiles/voyager/{z}/{x}/{y}{r}.png',
  {maxZoom:19, attribution:'&copy; OpenStreetMap, &copy; CARTO'});
const satellite = L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
  {maxZoom:19, maxNativeZoom:19, attribution:'Imagery &copy; Esri'});
const ESRI='https://server.arcgisonline.com/ArcGIS/rest/services/Reference/';
const roadLabels=L.tileLayer(ESRI+'World_Transportation/MapServer/tile/{z}/{y}/{x}',{maxZoom:19});
const placeLabels=L.tileLayer(ESRI+'World_Boundaries_and_Places/MapServer/tile/{z}/{y}/{x}',{maxZoom:19});
const satHybrid=L.layerGroup([satellite, roadLabels, placeLabels]);
streets.addTo(map);
L.control.layers({'Street':streets,'Satellite':satHybrid},{},{position:'bottomleft',collapsed:false}).addTo(map);
map.createPane('routePane'); map.getPane('routePane').style.zIndex = 450;

const drawn = new L.FeatureGroup().addTo(map);
// all map-layer handles declared ONCE, here
let arrowLayer=null, truck=null, startMarker=null, shape=null,
    partialLine=null, startPin=null;

const SHAPE_STYLE={color:'#4f8cff', weight:2, fillOpacity:.06};
const boxTool  = new L.Draw.Rectangle(map, {shapeOptions:SHAPE_STYLE});
const polyTool = new L.Draw.Polygon(map, {shapeOptions:SHAPE_STYLE, allowIntersection:false,
  showArea:false, drawError:{color:'#d7263d', message:'Edges cannot cross'}});

document.getElementById('box').onclick = () => { polyTool.disable(); drawn.clearLayers(); boxTool.enable();
  msg('Drag a rectangle around the neighborhood.', 'info'); };
document.getElementById('poly').onclick = () => { boxTool.disable(); drawn.clearLayers(); polyTool.enable();
  msg('Click each corner of your area. Click the first point again to close it.', 'info'); };

map.on(L.Draw.Event.CREATED, e => {
  drawn.clearLayers(); drawn.addLayer(e.layer);
  if (e.layerType === 'rectangle') {
    const b = e.layer.getBounds();
    shape = {kind:'bbox', bounds:{north:b.getNorth(), south:b.getSouth(), east:b.getEast(), west:b.getWest()}};
  } else {
    const ring = e.layer.getLatLngs()[0].map(p => [p.lng, p.lat]); ring.push(ring[0]);
    shape = {kind:'polygon', polygon:{type:'Polygon', coordinates:[ring]}};
  }
  document.getElementById('solve').disabled = false;
  msg('Area set. Shift-click the map to set where you start &amp; end. Then Solve.', 'info');
});

map.on('click', e => {
  if (!e.originalEvent.shiftKey) return;
  if (startMarker) map.removeLayer(startMarker);
  startMarker = L.marker(e.latlng).addTo(map).bindTooltip('Start / End').openTooltip();
});

document.getElementById('clear').onclick = () => {
  stop(); drawn.clearLayers();
  [baseLayer, doneLayer, partialLine, arrowLayer, truck, startMarker, startPin].forEach(l => l && map.removeLayer(l));
  baseLayer = doneLayer = partialLine = arrowLayer = truck = startMarker = startPin = shape = null;
  document.getElementById('solve').disabled = true;
  document.getElementById('map').classList.remove('routed');
  document.getElementById('play').classList.remove('on');
  document.getElementById('hud').classList.remove('on');
  document.getElementById('legend').style.display = 'none';
  document.getElementById('out').innerHTML = '<div class="empty">Outline an area and hit <b>Solve route</b>.</div>';
  msg('');
};

// ===== geocode =====
const q = document.getElementById('q');
document.getElementById('find').onclick = find;
q.onkeydown = e => { if (e.key === 'Enter') find(); };
async function find(){
  const term = q.value.trim(); if (!term) return;
  msg('Looking up "' + term + '"...', 'info');
  try {
    const r = await fetch('/geocode?q=' + encodeURIComponent(term));
    const d = await r.json();
    if (!r.ok) return msg(d.error, 'err');
    map.fitBounds([[d.bounds.south, d.bounds.west],[d.bounds.north, d.bounds.east]]);
    if (map.getZoom() > 16) map.setZoom(16);
    msg('Found ' + d.label + '. Now <b>Draw shape</b> or <b>Draw box</b>.', 'info');
  } catch (err) { msg('Lookup failed: ' + err, 'err'); }
}

// ===== solve =====
const solveBtn = document.getElementById('solve');
solveBtn.onclick = async () => {
  if (!shape) return;
  const orig = solveBtn.innerHTML;
  solveBtn.disabled = true; solveBtn.innerHTML = '<span class="spin"></span>Solving...';
  msg('Pulling roads from OpenStreetMap and solving. Bigger areas take a minute.', 'info');
  const body = Object.assign({}, shape, {
    walking: document.getElementById('walking').checked,
    include_service: document.getElementById('svc').checked,
    coverage: document.getElementById('coverage').value });
  if (startMarker) { body.start_lat = startMarker.getLatLng().lat; body.start_lon = startMarker.getLatLng().lng; }
  try {
    const r = await fetch('/solve', {method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify(body)});
    const d = await r.json();
    if (!r.ok) { msg(d.error, 'err'); return; }
    render(d); msg('Ready. Press &#9654; Play to drive the route \u2014 the blue TRUCK START pin is where it begins.', 'info');
  } catch (err) { msg('Solve failed: ' + err, 'err'); }
  finally { solveBtn.disabled = false; solveBtn.innerHTML = orig; }
};
// ===== route data =====
let PATH=[], TOTAL_M=0, DRIVE_MIN=0, STEPS=[];
let routeGroup=null, segLine=[], pairSegs={}, doneCount={}, paintedUpto=0;

const C_NONE='#ef4444';   // not covered  (red)
const C_HALF='#ffd21e';   // one side done (yellow)
const C_FULL='#22c55e';   // fully covered (green)
const C_DEAD='#9aa4b2';   // deadhead / connector (grey, dashed)

function bearing(a, b){
  const r=Math.PI/180;
  const y=Math.sin((b.lng-a.lng)*r)*Math.cos(b.lat*r);
  const x=Math.cos(a.lat*r)*Math.sin(b.lat*r)-Math.sin(a.lat*r)*Math.cos(b.lat*r)*Math.cos((b.lng-a.lng)*r);
  return (Math.atan2(y,x)*180/Math.PI+360)%360;
}
function segColor(pair){
  const need = PAIR_NEED[pair] || 1, have = doneCount[pair] || 0;
  return have<=0 ? C_NONE : (have>=need ? C_FULL : C_HALF);
}
let PAIR_NEED={};

function render(d){
  stop(); stopTracking();
  [routeGroup, partialLine, truck, startPin].forEach(l => l && map.removeLayer(l));

  const feats=d.geojson.features;
  PATH=[]; TOTAL_M=0; PAIR_NEED={};
  feats.forEach(f=>{
    const c=f.geometry.coordinates;
    const a=L.latLng(c[0][1],c[0][0]), b=L.latLng(c[1][1],c[1][0]);
    const len=map.distance(a,b), p=f.properties;
    if (!p.deadhead && p.needed) PAIR_NEED[p.pair]=p.needed;
    PATH.push({a,b,len,cum:TOTAL_M,name:p.name,deadhead:p.deadhead,pair:p.pair,needed:p.needed,order:p.order});
    TOTAL_M+=len;
  });
  DRIVE_MIN=d.stats.drive_min; STEPS=d.directions;

  // draw one polyline per segment (required = red base, deadhead = grey dashed), keep refs
  routeGroup=L.layerGroup([], {pane:'routePane'}).addTo(map);
  segLine=[]; pairSegs={};
  PATH.forEach((s,i)=>{
    L.polyline([s.a,s.b],{pane:'routePane',color:'#05070c',weight:s.deadhead?6:8.5,opacity:.55,lineCap:'round'}).addTo(routeGroup);
    const ln=L.polyline([s.a,s.b],{pane:'routePane',
      color:s.deadhead?C_DEAD:C_NONE, weight:s.deadhead?3.5:5.5, opacity:.95,
      lineCap:'round', dashArray:s.deadhead?'2,7':null}).addTo(routeGroup);
    ln.bindTooltip('#'+s.order+' '+s.name+(s.deadhead?' — connector (no delivery)':''));
    segLine[i]=ln;
    if (!s.deadhead){ (pairSegs[s.pair]=pairSegs[s.pair]||[]).push(i); }
  });

  partialLine=L.polyline([],{pane:'routePane',color:C_HALF,weight:6.5,opacity:1,lineCap:'round'}).addTo(map);
  buildArrows();
  startPin=L.marker(PATH[0].a,{zIndexOffset:1100, icon:flagIcon()}).addTo(map);
  truck=L.marker(PATH[0].a,{icon:truckIcon(0), zIndexOffset:1200, interactive:false}).addTo(map);

  const bb=L.latLngBounds([]); PATH.forEach(s=>{bb.extend(s.a); bb.extend(s.b);});
  map.fitBounds(bb,{padding:[30,30]});
  buildLegend(d.coverage);
  document.getElementById('map').classList.add('routed');
  document.getElementById('play').classList.add('on');
  document.getElementById('hud').classList.add('on');
  renderStats(d.stats, d.coverage);
  setMode('sim'); resetTravel(); seek(0);
  msg('Ready. Press &#9654; Play (or switch to Track). Checkered flag = start/finish.', 'info');
}

function recolorPair(pair){
  const c=segColor(pair);
  (pairSegs[pair]||[]).forEach(i => segLine[i].setStyle({color:c}));
}

function buildArrows(){
  if (arrowLayer) map.removeLayer(arrowLayer);
  arrowLayer=L.layerGroup();
  const stride=Math.max(1,Math.ceil(PATH.length/80));
  PATH.forEach((s,i)=>{
    if (i%stride || s.len<28) return;
    const mid=L.latLng((s.a.lat+s.b.lat)/2,(s.a.lng+s.b.lng)/2);
    L.marker(mid,{interactive:false, icon:L.divIcon({className:'',iconSize:[16,16],iconAnchor:[8,8],
      html:'<div class="arrow" style="transform:rotate('+bearing(s.a,s.b)+'deg)">'+
           '<svg width="16" height="16" viewBox="0 0 16 16"><path d="M8 2 L12 12 L8 9.6 L4 12 Z" fill="#111" stroke="#fff" stroke-width="1"/></svg></div>'})}).addTo(arrowLayer);
  });
  if (document.getElementById('arrowsOn').checked) arrowLayer.addTo(map);
}
document.getElementById('arrowsOn').onchange=e=>{ if(!arrowLayer)return; e.target.checked?arrowLayer.addTo(map):map.removeLayer(arrowLayer); };

function flagIcon(){
  let sq='';
  for (let r=0;r<3;r++) for (let c=0;c<4;c++) if ((r+c)%2===0) sq+='<rect x="'+(6+c*4)+'" y="'+(3+r*4)+'" width="4" height="4" fill="#111"/>';
  return L.divIcon({className:'',iconSize:[64,40],iconAnchor:[6,34],html:
    '<div class="pin"><svg width="26" height="34" viewBox="0 0 26 34">'+
    '<rect x="4" y="2" width="2" height="30" fill="#e7eaf0"/>'+
    '<rect x="6" y="3" width="16" height="12" fill="#fff" stroke="#05070c" stroke-width="1"/>'+sq+
    '</svg><div style="margin-top:-3px">START / FINISH</div></div>'});
}

// garbage truck, nose points the drive direction
function truckIcon(deg){
  return L.divIcon({className:'',iconSize:[40,40],iconAnchor:[20,20],
    html:'<div class="truck" style="transform:rotate('+deg+'deg)">'+
      '<svg width="40" height="40" viewBox="0 0 40 40">'+
        '<circle cx="20" cy="20" r="17" fill="#05070c" opacity=".55"/>'+
        '<g transform="translate(20,20) rotate(90)">'+
          '<rect x="-11" y="-7" width="12" height="14" rx="1.5" fill="#3ea34a"/>'+   /* refuse body */
          '<rect x="-12.5" y="-7" width="2.5" height="14" fill="#2f8038"/>'+          /* rear */
          '<rect x="1" y="-6" width="8" height="13" rx="1.5" fill="#dfe8ff"/>'+       /* cab */
          '<rect x="6.5" y="-5" width="3.5" height="5" rx="1" fill="#9fc2ff"/>'+      /* windshield */
          '<rect x="-9" y="-8.5" width="9" height="2" rx="1" fill="#2f8038"/>'+       /* lid */
          '<circle cx="-6" cy="8" r="2.4" fill="#111"/>'+
          '<circle cx="5" cy="8" r="2.4" fill="#111"/>'+
          '<circle cx="-6" cy="-8" r="2.4" fill="#111"/>'+
          '<circle cx="5" cy="-8" r="2.4" fill="#111"/>'+
        '</g></svg></div>'});
}

function buildLegend(cov){
  const both = cov!=='once';
  let h='<div class="ttl">Coverage</div>'+
    '<div class="lg"><span class="sw" style="background:'+C_NONE+'"></span>not covered</div>';
  if (both) h+='<div class="lg"><span class="sw" style="background:'+C_HALF+'"></span>one side done</div>';
  h+='<div class="lg"><span class="sw" style="background:'+C_FULL+'"></span>'+(both?'both sides done':'covered')+'</div>'+
     '<div class="lg"><span class="sw" style="background:'+C_DEAD+'"></span>connector (no delivery)</div>'+
     '<div class="lg" style="margin-top:5px"><span class="sw" style="background:#fff"></span>start / finish (checkered)</div>';
  const el=document.getElementById('legend'); el.innerHTML=h; el.style.display='block';
}

// ===== Simulate vs Track (real GPS) =====
let mode='sim', watchId=null, maxReached=0, gpsMark=null;
const mSim=document.getElementById('mSim'), mTrack=document.getElementById('mTrack'), gpsBtn=document.getElementById('gps');

// ===== animation =====
let pos=0, playing=false, raf=null, last=0;
const pp=document.getElementById('pp'), scrub=document.getElementById('scrub'),
      speedSel=document.getElementById('speed'), followCk=document.getElementById('follow');
const simControls=[pp, document.getElementById('restart'), scrub, speedSel];
pp.onclick=()=>playing?stop():play();
document.getElementById('restart').onclick=()=>{ seek(0); play(); };
scrub.oninput=()=>{ stop(); seek(TOTAL_M*(scrub.value/1000)); };

function setMode(m){
  mode=m;
  mSim.classList.toggle('on', m==='sim');
  mTrack.classList.toggle('on', m==='track');
  if (m==='sim'){ stopTracking(); gpsBtn.style.display='none'; simControls.forEach(el=>el.style.display=''); }
  else { stop(); gpsBtn.style.display=''; simControls.forEach(el=>el.style.display='none'); }
}
mSim.onclick=()=>setMode('sim');
mTrack.onclick=()=>setMode('track');

function resetTravel(){
  doneCount={}; paintedUpto=0; maxReached=0;
  PATH.forEach((s,i)=>{ if(segLine[i]) segLine[i].setStyle({color:s.deadhead?C_DEAD:C_NONE}); });
  if (partialLine) partialLine.setLatLngs([]);
}

function play(){
  if (!PATH.length) return;
  if (pos>=TOTAL_M-0.5){ pos=0; resetTravel(); }
  playing=true; pp.innerHTML='&#10073;&#10073; Pause';
  last=performance.now(); raf=requestAnimationFrame(tick);
}
function stop(){ playing=false; pp.innerHTML='&#9654; Play'; if(raf)cancelAnimationFrame(raf); raf=null; }
function tick(now){
  if(!playing) return;
  const dt=Math.min((now-last)/1000,0.1); last=now;
  pos += (TOTAL_M/75)*parseFloat(speedSel.value)*dt;
  if (pos>=TOTAL_M){ seek(TOTAL_M); stop(); return; }
  seek(pos); raf=requestAnimationFrame(tick);
}

function seek(m){
  if(!PATH.length) return;
  pos=Math.max(0,Math.min(m,TOTAL_M));
  let lo=0,hi=PATH.length-1,i=0;
  while(lo<=hi){ const mid=(lo+hi)>>1,s=PATH[mid];
    if(pos<s.cum)hi=mid-1; else if(pos>s.cum+s.len)lo=mid+1; else {i=mid;break;}
    i=Math.min(lo,PATH.length-1); }
  const s=PATH[i];
  const f=s.len?Math.max(0,Math.min((pos-s.cum)/s.len,1)):0;
  const here=L.latLng(s.a.lat+(s.b.lat-s.a.lat)*f, s.a.lng+(s.b.lng-s.a.lng)*f);

  if (i<paintedUpto) resetTravel();
  while (paintedUpto<i){
    const p=PATH[paintedUpto];
    if (!p.deadhead){ doneCount[p.pair]=(doneCount[p.pair]||0)+1; recolorPair(p.pair); }
    paintedUpto++;
  }
  // current segment: show the part covered so far, tinted to its FUTURE state
  if (s.deadhead){ partialLine.setLatLngs([]); }
  else {
    const willHave=(doneCount[s.pair]||0)+1, need=PAIR_NEED[s.pair]||1;
    partialLine.setStyle({color: willHave>=need ? C_FULL : C_HALF});
    partialLine.setLatLngs([s.a, here]);
  }
  truck.setLatLng(here); truck.setIcon(truckIcon(bearing(s.a,s.b)));
  if (followCk.checked && (playing||mode==='track') && !map.getBounds().pad(-0.28).contains(here))
    map.panTo(here,{animate:true,duration:.5});
  scrub.value=Math.round((pos/TOTAL_M)*1000);
  updateHud(s);
}

function updateHud(s){
  const pct=pos/TOTAL_M;
  const leg=document.getElementById('hudLeg');
  leg.textContent=Math.round(pct*100)+'% driven';
  leg.style.background=s.deadhead?C_DEAD:C_FULL;
  document.getElementById('hudStreet').innerHTML=(s.deadhead?'<span style="color:'+C_DEAD+'">&#8631; </span>':'')+s.name;
  document.getElementById('hudMeta').textContent=
    (pos/1609.344).toFixed(2)+' / '+(TOTAL_M/1609.344).toFixed(2)+' mi  ·  ~'+Math.round(DRIVE_MIN*pct)+' min in';
  document.getElementById('hudBar').style.width=(pct*100)+'%';
  document.getElementById('hudBar').style.background=C_FULL;
  let acc=0,idx=0;
  for(let k=0;k<STEPS.length;k++){ acc+=STEPS[k].mi*1609.344; idx=k; if(pos<=acc)break; }
  document.querySelectorAll('#out .street.now').forEach(r=>r.classList.remove('now'));
  const row=document.querySelector('#out .street[data-step="'+(idx+1)+'"]');
  if(row){ row.classList.add('now'); if(playing)row.scrollIntoView({block:'nearest'}); }
}

// ===== GPS tracking =====
function projectToRoute(ll){
  let best=Infinity,bestCum=0;
  for(const s of PATH){
    const latR=(s.a.lat+s.b.lat)/2*Math.PI/180,k=Math.cos(latR)*111320;
    const bx=(s.b.lng-s.a.lng)*k,by=(s.b.lat-s.a.lat)*111320;
    const px=(ll.lng-s.a.lng)*k,py=(ll.lat-s.a.lat)*111320;
    const L2=bx*bx+by*by||1e-9; let t=(px*bx+py*by)/L2; t=Math.max(0,Math.min(1,t));
    const dx=px-bx*t,dy=py-by*t,dd=Math.hypot(dx,dy);
    if(dd<best){best=dd;bestCum=s.cum+t*s.len;}
  }
  return {dist:best,cum:bestCum};
}
function startTracking(){
  if(!('geolocation' in navigator)){ msg('This device has no location support.','err'); return; }
  if(!PATH.length){ msg('Solve a route first.','err'); return; }
  resetTravel();
  gpsBtn.textContent='Stop GPS'; gpsBtn.classList.add('on');
  msg('Tracking your location — drive the route, streets fill in as you cover them.','info');
  watchId=navigator.geolocation.watchPosition(onPos,onGpsErr,{enableHighAccuracy:true,maximumAge:1000,timeout:20000});
}
function stopTracking(){
  if(watchId!=null){ navigator.geolocation.clearWatch(watchId); watchId=null; }
  if(gpsMark){ map.removeLayer(gpsMark); gpsMark=null; }
  gpsBtn.textContent='Start GPS'; gpsBtn.classList.remove('on');
}
gpsBtn.onclick=()=>(watchId==null?startTracking():stopTracking());
function onPos(p){
  if(!PATH.length) return;
  const ll=L.latLng(p.coords.latitude,p.coords.longitude);
  const pr=projectToRoute(ll);
  if(pr.cum>maxReached) maxReached=pr.cum;
  seek(maxReached);
  if(!gpsMark) gpsMark=L.circleMarker(ll,{radius:6,color:'#fff',weight:2,fillColor:'#3b82f6',fillOpacity:.9,pane:'routePane'}).addTo(map);
  else gpsMark.setLatLng(ll);
  if(followCk.checked) map.panTo(ll,{animate:true,duration:.5});
}
function onGpsErr(e){ msg('Location error: '+e.message+'. Allow location access (page must be HTTPS).','err'); stopTracking(); }

// ===== stats =====
function renderStats(s, cov){
  const row=(l,v,c)=>'<div class="stat '+(c||'')+'"><span>'+l+'</span><b>'+v+'</b></div>';
  let h='';
  h+=row('Mode', cov==='once'?'Each street once':(cov==='optimal'?'Both sides — shortest':'Both sides — figure-8'));
  h+=row('Total route', s.total_mi.toFixed(2)+' mi','big');
  h+=row('Delivering', s.min_mi.toFixed(2)+' mi','good');
  h+=row('Backtrack (deadhead)', s.deadhead_mi.toFixed(2)+' mi','warn');
  h+=row('Efficiency', s.efficiency_pct.toFixed(1)+'%');
  h+=row('Streets', s.streets.toLocaleString());
  h+=row('Est. driving time', Math.round(s.drive_min)+' min');
  if(s.excluded_nodes) h+='<div class="msg info" style="display:block">'+s.excluded_nodes+' intersection(s) were unreachable and left out.</div>';
  h+='<div class="hd" style="margin-top:8px">Turn-by-turn (in drive order)</div>';
  STEPS.forEach(x=>{
    const col=x.deadhead?C_DEAD:C_FULL;
    h+='<div class="street" data-step="'+x.step+'" style="border-left-color:'+col+'"><span>'+x.step+'. '+
       (x.deadhead?'<i style="color:'+C_DEAD+'">(connector)</i> ':'')+x.name+'</span><b>'+x.mi.toFixed(2)+'</b></div>';
  });
  document.getElementById('out').innerHTML=h;
}

function msg(t, cls){ const m=document.getElementById('msg'); m.innerHTML=t||''; m.className='msg'+(t?' '+cls:''); }
</script>
</body>
</html>
'''


# ============================================================ web app
app = Flask(__name__)
UA = {"User-Agent": "route-em/1.0 (personal delivery route tool)"}


@app.route("/")
def index():
    return render_template_string(PAGE)


@app.route("/health")
def health():
    return jsonify({"status": "ok"})


@app.route("/geocode")
def geocode():
    q = (request.args.get("q") or "").strip()
    if not q:
        return jsonify({"error": "Type a ZIP code, address, or neighborhood."}), 400
    try:
        r = requests.get(
            "https://nominatim.openstreetmap.org/search",
            params={"q": q, "format": "json", "limit": 1, "countrycodes": "us"},
            headers=UA, timeout=20,
        )
        r.raise_for_status()
        hits = r.json()
    except Exception as exc:
        return jsonify({"error": "Lookup failed: %s" % exc}), 502

    if not hits:
        return jsonify({"error": "Couldn't find '%s'. Try adding the city and state." % q}), 404

    h = hits[0]
    s, n, w, e = [float(x) for x in h["boundingbox"]]  # nominatim order: S,N,W,E
    return jsonify({
        "label": h.get("display_name", q),
        "lat": float(h["lat"]), "lon": float(h["lon"]),
        "bounds": {"south": s, "north": n, "west": w, "east": e},
    })


@app.route("/solve", methods=["POST"])
def solve_route():
    """Accepts either {"kind":"bbox","bounds":{...}} or {"kind":"polygon","polygon":{geojson}}."""
    d = request.get_json(force=True)
    walking = bool(d.get("walking"))
    service = bool(d.get("include_service"))
    try:
        if d.get("kind") == "polygon" or "polygon" in d:
            poly = d["polygon"]
            area = polygon_area_sq_mi(poly)
            _check_area(area)
            G = graph_from_polygon(poly, walking=walking, include_service=service)
        else:
            b = d["bounds"]
            _check_area(bbox_area_sq_mi(b))
            G = graph_from_bbox(b["north"], b["south"], b["east"], b["west"],
                                walking=walking, include_service=service)

        return jsonify(solve(G, walking=walking, coverage=d.get("coverage", "both"),
                             start_lat=d.get("start_lat"), start_lon=d.get("start_lon")))
    except RouteError as exc:
        return jsonify({"error": str(exc)}), 400
    except Exception as exc:
        traceback.print_exc()
        return jsonify({"error": "Unexpected error: %s" % exc}), 500


def _check_area(area):
    if area > MAX_AREA_SQ_MI:
        raise RouteError(
            "That area is about %.0f sq mi -- too big to solve (limit %.0f). "
            "Outline something smaller; a paper route is usually well under 1 sq mi."
            % (area, MAX_AREA_SQ_MI)
        )


if __name__ == "__main__":
    app.run(host="0.0.0.0", port=int(os.environ.get("PORT", 7860)), debug=False)