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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
import os
import math
import folium
import folium.plugins
import xml.etree.ElementTree as ET
import heapq
from flask import Flask, render_template, request, jsonify, session
from werkzeug.utils import secure_filename
import importlib.util
import sys
import json
import copy

# Torch and image libraries
import torch
import torch.nn as nn
from torchvision import models
import torchvision.transforms as transforms
from PIL import Image

SEVERITY_MULTIPLIERS = {
    "none": 1.0,
    "minor": 2.0,
    "moderate": 3.0,
    "severe": 4.0
}

# Global variables for default map data (for Hugging Face deployment)
DEFAULT_MAP_DATA = {
    'nodes': None,
    'ways': None,
    'cameras': None,
    'meta': None,
    'osm_nodes': None,
    'graph': None,
    'txt_path': None,
    'osm_path': None
}

# In-memory cache for uploaded map data (survives across requests)
UPLOADED_MAP_CACHE = {
    'nodes': None,
    'ways': None,
    'cameras': None,
    'meta': None,
    'osm_nodes': None,
    'graph': None,
    'txt_path': None,
    'osm_path': None,
    'timestamp': None
}

# Global accident store (survives across requests)
GLOBAL_ACCIDENTS = {}


# =====================================================
# Image preprocessing (MUST match training - ImageNet normalization)
# =====================================================
accident_transform = transforms.Compose([
    transforms.Resize((224, 224)),
    transforms.ToTensor(),
    transforms.Normalize(
        mean=[0.485, 0.456, 0.406],  # ImageNet mean
        std=[0.229, 0.224, 0.225]    # ImageNet std
    )
])

MODEL_DIR = "model/saved_models/"


# Based on ur directory structure, load the appropriate model
def load_model(model_name):
    FILE_MAP = {
        "mobilenet": "mobilenet/version_2/mobilenet_v2_final.pth",
        "resnet": "resnet/version_2/resnet18_final.pth",
        "efficientnet": "efficientnet/version_2/efficientnet_b0_final.pth"
    }

    path = MODEL_DIR + FILE_MAP[model_name]

    # Load the saved state_dict first
    state = torch.load(path, map_location="cpu")

    # -------------------------------
    # MOBILENET V2
    # -------------------------------
    if model_name == "mobilenet":
        model = models.mobilenet_v2(weights=None)

        # Check if trained with Sequential head
        if "classifier.2.weight" in state:
            model.classifier = nn.Sequential(
                nn.Dropout(0.2),
                nn.Linear(1280, 256),
                nn.ReLU(),
                nn.Linear(256, 4)
            )
        else:
            model.classifier[1] = nn.Linear(1280, 4)

        model.load_state_dict(state)

    # -------------------------------
    # RESNET18
    # -------------------------------
    elif model_name == "resnet":
        model = models.resnet18(weights=None)

        state = torch.load(path, map_location="cpu")

        # Detect YOUR exact architecture (ReLU + Linear)
        if "fc.1.weight" in state and "fc.0.weight" not in state:
            model.fc = nn.Sequential(
                nn.ReLU(),              # fc.0
                nn.Linear(512, 4)       # fc.1
            )
        else:
            model.fc = nn.Linear(512, 4)

        model.load_state_dict(state)

    # -------------------------------
    # EFFICIENTNET B0
    # -------------------------------
    elif model_name == "efficientnet":
        model = models.efficientnet_b0(weights=None)

        # EfficientNet uses classifier[1] normally, but
        # if Sequential was used in training β†’ build it again
        if "classifier.2.weight" in state:
            model.classifier = nn.Sequential(
                nn.Dropout(0.2),
                nn.Linear(1280, 256),
                nn.ReLU(),
                nn.Linear(256, 4)
            )
        else:
            model.classifier[1] = nn.Linear(1280, 4)

        model.load_state_dict(state)

    else:
        raise ValueError("Unknown model type")

    model.eval()
    print(f"βœ… Loaded model: {path}")
    return model




# =====================================================
# Load models once on server start
# =====================================================
mobilenet_model = load_model("mobilenet")
resnet_model = load_model("resnet")
# Load EfficientNet if available; fall back gracefully
try:
    efficientnet_model = load_model("efficientnet")
except Exception as e:
    print("Failed to load EfficientNet model:", e)
    efficientnet_model = None
# ============================================================================
# UTILITY FUNCTIONS
# ============================================================================

def load_default_map_data():
    """Load default map files if they exist (optional - for convenience)"""
    default_txt = 'heritage_assignment_15_time_asymmetric-1.txt'
    default_osm = 'map.osm'
    
    if os.path.exists(default_txt) and os.path.exists(default_osm):
        try:
            print(f"πŸ—ΊοΈ  Loading default map files: {default_txt}, {default_osm}")
            nodes, ways, cameras, meta = parse_map_data_file(default_txt)
            osm_nodes, graph = load_osm_graph(default_osm)
            
            DEFAULT_MAP_DATA['nodes'] = nodes
            DEFAULT_MAP_DATA['ways'] = ways
            DEFAULT_MAP_DATA['cameras'] = cameras
            DEFAULT_MAP_DATA['meta'] = meta
            DEFAULT_MAP_DATA['osm_nodes'] = osm_nodes
            DEFAULT_MAP_DATA['graph'] = graph
            DEFAULT_MAP_DATA['txt_path'] = default_txt
            DEFAULT_MAP_DATA['osm_path'] = default_osm
            
            print(f"βœ… Default map loaded: {len(nodes)} nodes, {len(ways)} ways")
            return True
        except Exception as e:
            print(f"⚠️  Failed to load default map: {e}")
            return False
    else:
        print("ℹ️  No default map files found (optional). Users will upload their own files.")
    return False


def get_current_map_data():
    """Get current map data - from cache (uploaded) or default map"""
    import copy
    
    # Priority 1: Check uploaded files cache FIRST (regardless of session)
    if UPLOADED_MAP_CACHE['nodes'] is not None:
        # ALWAYS use cached ways (which includes accidents) - don't rely on session
        ways = copy.deepcopy(UPLOADED_MAP_CACHE['ways'])
        accidents_count = sum(1 for w in ways if w.get('accident', False))
        print(f"βœ… Using uploaded map cache (accidents applied: {accidents_count})")
        return (
            UPLOADED_MAP_CACHE['nodes'],
            ways,
            UPLOADED_MAP_CACHE['cameras'],
            UPLOADED_MAP_CACHE['meta'],
            UPLOADED_MAP_CACHE['osm_nodes'],
            UPLOADED_MAP_CACHE['graph'],
            UPLOADED_MAP_CACHE['txt_path'],
            UPLOADED_MAP_CACHE['osm_path']
        )
    
    # Priority 2: Use default map if available
    if DEFAULT_MAP_DATA['nodes'] is not None:
        # ALWAYS use cached ways (which includes accidents) - don't rely on session
        ways = copy.deepcopy(DEFAULT_MAP_DATA['ways'])
        accidents_count = sum(1 for w in ways if w.get('accident', False))
        print(f"βœ… Using default map (accidents applied: {accidents_count})")
        return (
            DEFAULT_MAP_DATA['nodes'],
            ways,
            DEFAULT_MAP_DATA['cameras'],
            DEFAULT_MAP_DATA['meta'],
            DEFAULT_MAP_DATA['osm_nodes'],
            DEFAULT_MAP_DATA['graph'],
            DEFAULT_MAP_DATA['txt_path'],
            DEFAULT_MAP_DATA['osm_path']
        )
    
    # Priority 3: Try loading from file paths in session (last resort)
    txt_path = session.get('txt_path')
    osm_path = session.get('osm_path')
    if txt_path and osm_path and os.path.exists(txt_path) and os.path.exists(osm_path):
        try:
            print(f"⚠️  Loading from disk: {txt_path}, {osm_path}")
            nodes, ways, cameras, meta = parse_map_data_file(txt_path)
            osm_nodes, graph = load_osm_graph(osm_path)
            return nodes, ways, cameras, meta, osm_nodes, graph, txt_path, osm_path
        except Exception as e:
            print(f"❌ Error loading from disk: {e}")
    
    print("❌ No map data available")
    print(f"   - Uploaded cache: {UPLOADED_MAP_CACHE['nodes'] is not None}")
    print(f"   - Default map: {DEFAULT_MAP_DATA['nodes'] is not None}")
    print(f"   - Session: {dict(session)}")
    return None, None, None, None, None, None, None, None

def load_func_from_path(path, func_name):
    """Dynamically load a function from a Python file"""
    # Prepare module metadata so we can import a function from an arbitrary file
    module_dir = os.path.dirname(path)
    spec = importlib.util.spec_from_file_location(func_name, path)
    mod = importlib.util.module_from_spec(spec)

    added = False
    try:
        # Insert the module directory temporarily to resolve relative imports
        if module_dir not in sys.path:
            sys.path.insert(0, module_dir)
            added = True
        # Execute the module so the requested function becomes available
        spec.loader.exec_module(mod)
    finally:
        if added:
            try:
                # Always clean up sys.path even if the import fails
                sys.path.remove(module_dir)
            except ValueError:
                pass

    return getattr(mod, func_name)


def split_csv_allow_commas(line, min_fields):
    """Parse CSV line while respecting commas inside parentheses"""
    # Accumulate parsed pieces and track parentheses depth to honor commas inside pairs
    parts = []
    buf = []
    depth = 0

    for ch in line:
        if ch == '(':
            # Increase depth because commas inside parentheses must be preserved
            depth += 1
            buf.append(ch)
        elif ch == ')':
            # Drop depth (with floor at 0) once a closing parenthesis is seen
            depth = max(depth - 1, 0)
            buf.append(ch)
        elif ch == ',':
            if depth == 0:
                # Split on commas only if we are not inside parentheses
                parts.append("".join(buf).strip())
                buf = []
            else:
                buf.append(ch)
        else:
            buf.append(ch)

    if buf:
        # Flush the final buffer after iterating through the line
        parts.append("".join(buf).strip())

    if len(parts) < min_fields:
        raise ValueError(f"Line '{line}' parsed into too few fields: {parts}")
    return parts


def haversine_km(lat1, lon1, lat2, lon2):
    """Calculate distance between two coordinates in kilometers"""
    # Earth radius in kilometers for the haversine formula
    R = 6371.0
    la1, la2 = math.radians(lat1), math.radians(lat2)
    dla = la2 - la1
    dlo = math.radians(lon2 - lon1)
    # Classic haversine distance computation with spherical adjustment
    a = math.sin(dla/2)**2 + math.cos(la1)*math.cos(la2)*math.sin(dlo/2)**2
    return R * 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))


def is_header(line):
    """Check if line is a section header"""
    # Headers are bracketed (e.g., [NODES]) in the custom format
    return line.startswith("[") and line.endswith("]")


def ignore_line(line):
    """Check if line should be ignored"""
    # Skip blank lines and comments when reading the dataset
    return (not line.strip()) or line.strip().startswith("#")

# ============================================================================
# FILE PARSING FUNCTIONS
# ============================================================================

def parse_map_data_file(path):
    """Parse the custom map data file format"""
    # Track which section we are reading so each line is interpreted correctly
    section = None
    nodes = {}
    ways = []
    cameras = {}
    meta = {"start": None, "goals": [], "accident_multiplier": None}

    with open(path, "r", encoding="utf-8") as f:
        for raw in f:
            line = raw.strip()
            if ignore_line(line):
                continue
            if is_header(line):
                # Switch parsing mode whenever a new header is encountered
                section = line.upper()
                continue

            if section == "[NODES]":
                p = split_csv_allow_commas(line, 4)
                nid, lat, lon, label = p[0], float(p[1]), float(p[2]), p[3]
                nodes[nid] = {"lat": lat, "lon": lon, "label": label}

            elif section == "[WAYS]":
                p = split_csv_allow_commas(line, 6)
                time_val = float(p[5])

                ways.append({
                    "way_id": p[0],
                    "from": p[1],
                    "to": p[2],
                    "road_name": p[3],
                    "highway_type": p[4],
                    "time_min": time_val,          
                    "original_time": time_val,     
                    "accident": False
                    
                })

            elif section == "[CAMERAS]":
                p = split_csv_allow_commas(line, 2)
                cameras[p[0]] = p[1]

            elif section == "[META]":
                p = [x.strip() for x in line.split(",")]
                key = p[0].upper()
                # Populate meta information that influences visualization
                if key == "START":
                    meta["start"] = p[1]
                elif key == "GOAL":
                    meta["goals"] = p[1:]
                elif key == "ACCIDENT_MULTIPLIER":
                    meta["accident_multiplier"] = float(p[1])

    return nodes, ways, cameras, meta


def load_osm_graph(osm_path):
    """Parse OSM file and build graph structure"""
    tree = ET.parse(osm_path)
    root = tree.getroot()

    # Extract all nodes
    osm_nodes = {}
    for n in root.findall("node"):
        nid = n.attrib["id"]
        lat = float(n.attrib["lat"])
        lon = float(n.attrib["lon"])
        osm_nodes[nid] = (lat, lon)

    # Build adjacency graph
    graph = {nid: [] for nid in osm_nodes}

    for w in root.findall("way"):
        nd_refs = [nd.attrib["ref"] for nd in w.findall("nd")]
        tags = {t.attrib.get("k"): t.attrib.get("v") for t in w.findall("tag")}

        if "highway" not in tags:
            # Only keep ways that represent roads
            continue

        for i in range(len(nd_refs) - 1):
            a, b = nd_refs[i], nd_refs[i+1]
            if a in osm_nodes and b in osm_nodes:
                lat1, lon1 = osm_nodes[a]
                lat2, lon2 = osm_nodes[b]
                # Use haversine distance to approximate segment cost
                dist = haversine_km(lat1, lon1, lat2, lon2)
                graph[a].append((b, dist))
                graph[b].append((a, dist))

    # Remove isolated nodes
    isolated = [nid for nid, nbrs in graph.items() if len(nbrs) == 0]
    for nid in isolated:
        del graph[nid]

    return osm_nodes, graph

# ============================================================================
# GRAPH ALGORITHM FUNCTIONS
# ============================================================================

def k_nearest_graph_nodes(lat, lon, osm_nodes, graph, k=5):
    """Find k nearest nodes in the graph to given coordinates"""
    # Maintain (distance squared, node id) pairs to avoid repetitive sqrt
    candidates = []
    for nid, (nlat, nlon) in osm_nodes.items():
        if nid not in graph:
            continue
        d_lat = lat - nlat
        d_lon = lon - nlon
        d2 = d_lat*d_lat + d_lon*d_lon
        candidates.append((d2, nid))

    candidates.sort(key=lambda x: x[0])
    return [nid for d2, nid in candidates[:k]]


def dijkstra_path(graph, start_id, goal_id):
    """Find shortest path using Dijkstra's algorithm"""
    dist = {start_id: 0.0}
    prev = {}
    pq = [(0.0, start_id)]
    visited = set()

    while pq:
        cur_d, cur = heapq.heappop(pq)
        if cur in visited:
            continue
        visited.add(cur)

        if cur == goal_id:
            break

        for nbr, w in graph.get(cur, []):
            # Relax neighboring nodes when a shorter distance is discovered
            nd = cur_d + w
            if nbr not in dist or nd < dist[nbr]:
                dist[nbr] = nd
                prev[nbr] = cur
                heapq.heappush(pq, (nd, nbr))

    if goal_id not in dist:
        return None

    # Reconstruct path
    path = []
    node = goal_id
    while True:
        path.append(node)
        if node == start_id:
            break
        node = prev.get(node)
        if node is None:
            return None

    path.reverse()
    return path


def path_length_km(path, graph):
    """Calculate total length of a path in kilometers"""
    if not path or len(path) < 2:
        return 0.0
    total = 0.0
    for a, b in zip(path[:-1], path[1:]):
        for nbr, w in graph.get(a, []):
            if nbr == b:
                # Accumulate edge weights that correspond to sequential nodes
                total += w
                break
    return total


def build_edges_map(ways):
    """Build edge dictionary from ways list"""
    # Store travel time for each directed edge for quick lookup during search
    edges = {}
    for way in ways:
        edges[(way["from"], way["to"])] = {
            "time": way["time_min"],
            "accident": way.get("accident", False)
        }

    return edges




# ============================================================================
# VISUALIZATION FUNCTIONS
# ============================================================================

def color_for_highway(hwy_type):
    """Return color code for highway type"""
    h = (hwy_type or "").lower()
    colors = {
        "primary": "deepskyblue",
        "secondary": "purple",
        "tertiary": "darkblue",
        "service": "slategray"
    }
    # Default to white for unknown highway types
    return colors.get(h, "white")


def get_map_center(nodes):
    """Calculate center point of all nodes"""
    lats = [info["lat"] for info in nodes.values()]
    lons = [info["lon"] for info in nodes.values()]
    return sum(lats)/len(lats), sum(lons)/len(lons)


GAP_TO_NODE_TOLERANCE_M = 2.5  # meters of acceptable gap between OSM snap and custom node
ROUTE_NODE_CLEARANCE_M = 4.0   # keep polylines slightly off the start/goal markers
NODE_OVERLAP_PRUNE_M = 0.75    # drop lat/lng points that sit almost exactly on top of a node


def register_arrow_segment(map_obj, coords, color, speed_mps=120):
    """Record a polyline for animated arrow rendering on the client."""
    if not coords or len(coords) < 2:
        return
    if not hasattr(map_obj, "_arrow_segments"):
        map_obj._arrow_segments = []
    map_obj._arrow_segments.append({
        "coords": coords,
        "color": color,
        "speed": speed_mps
    })


def inject_arrow_animation(map_obj, base_speed_mps=120):
    """Inject a client-side script that animates arrows along stored segments."""
    segments = getattr(map_obj, "_arrow_segments", [])
    if not segments:
        return

    payload = {
        "mapName": map_obj.get_name(),
        "segments": segments,
        "baseSpeed": base_speed_mps
    }

    arrow_script = """

    <script>

    (function(){

        const cfg = __ARROW_CONFIG__;

        if (!cfg || !cfg.segments || !cfg.segments.length) return;

        const mapName = cfg.mapName;



        function ready(fn){

            if (document.readyState === 'loading'){

                document.addEventListener('DOMContentLoaded', fn, { once: true });

            } else {

                fn();

            }

        }



        ready(() => {

            const map = window[mapName];

            if (!map) return;

            const baseSpeed = cfg.baseSpeed || 120;



            const styleId = 'arrow-anim-style';

            if (!document.getElementById(styleId)){

                const style = document.createElement('style');

                style.id = styleId;

                style.textContent = `

                .arrow-anim-wrap{width:18px;height:18px;display:flex;align-items:center;justify-content:center;transform:rotate(var(--arrow-rotation,0deg));}

                .arrow-anim-head{width:0;height:0;border-left:6px solid transparent;border-right:6px solid transparent;border-bottom:12px solid var(--arrow-color,#111);filter:drop-shadow(0 0 3px rgba(0,0,0,0.35));opacity:0.95;}

                `;

                document.head.appendChild(style);

            }



            const toRad = deg => deg * Math.PI / 180;

            const bearing = (a, b) => {

                const lat1 = toRad(a[0]);

                const lat2 = toRad(b[0]);

                const dLon = toRad(b[1] - a[1]);

                const y = Math.sin(dLon) * Math.cos(lat2);

                const x = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) * Math.cos(lat2) * Math.cos(dLon);

                return (Math.atan2(y, x) * 180 / Math.PI + 360) % 360;

            };

            const distance = (a, b) => {

                const R = 6371000;

                const dLat = toRad(b[0] - a[0]);

                const dLon = toRad(b[1] - a[1]);

                const lat1 = toRad(a[0]);

                const lat2 = toRad(b[0]);

                const h = Math.sin(dLat / 2) ** 2 + Math.cos(lat1) * Math.cos(lat2) * Math.sin(dLon / 2) ** 2;

                return 2 * R * Math.asin(Math.sqrt(Math.max(h, 0)));

            };



            cfg.segments.forEach((seg) => {

                const coords = Array.isArray(seg.coords) ? seg.coords : [];

                if (coords.length < 2) return;

                const color = seg.color || '#1f6feb';

                const speed = seg.speed || baseSpeed;



                const icon = L.divIcon({

                    className: 'arrow-anim-icon',

                    html: `<div class="arrow-anim-wrap" style="--arrow-color:${color};"><div class="arrow-anim-head"></div></div>`,

                    iconSize: [18, 18],

                    iconAnchor: [9, 9]

                });



                const marker = L.marker(coords[0], { icon, interactive: false, zIndexOffset: 900 }).addTo(map);

                let segIndex = 0;



                function travel(){

                    const start = coords[segIndex];

                    const end = coords[segIndex + 1];

                    if (!end){

                        segIndex = 0;

                        return travel();

                    }

                    const duration = Math.max(420, (distance(start, end) / speed) * 1000);

                    const heading = bearing(start, end);

                    const applyHeading = () => {

                        const el = marker.getElement();

                        if (el){

                            el.style.setProperty('--arrow-rotation', heading + 'deg');

                        }

                    };

                    applyHeading();

                    const startTime = performance.now();



                    function step(now){

                        const t = Math.min(1, (now - startTime) / duration);

                        const lat = start[0] + (end[0] - start[0]) * t;

                        const lon = start[1] + (end[1] - start[1]) * t;

                        marker.setLatLng([lat, lon]);

                        applyHeading();

                        if (t < 1){

                            requestAnimationFrame(step);

                        } else {

                            segIndex = (segIndex + 1) % (coords.length - 1);

                            travel();

                        }

                    }

                    requestAnimationFrame(step);

                }

                travel();

            });

        });

    })();

    </script>

    """
    map_obj.get_root().html.add_child(
        folium.Element(arrow_script.replace("__ARROW_CONFIG__", json.dumps(payload)))
    )

# Route/search playback injection
def inject_route_playback(map_obj, config_payload):
    """Add client-side route/search step playback controls to a Folium map."""
    if not config_payload:
        return

    script_template = """

    <script>

    (function(){

        const cfg = __CONFIG__;

        if (!cfg) return;

        const routeNodes = cfg.routeNodes || [];

        const routeSegments = cfg.routeSegments || [];

        const markerStyles = cfg.markerStyles || {};

        const markerLookup = cfg.nodeMarkerLookup || {};

        const nodeMeta = cfg.nodeMetadata || {};

        const searchSteps = cfg.searchSteps || [];

        const routeDelay = cfg.routeStepDelay || 900;

        const searchDelay = cfg.searchStepDelay || 1100;

        const uniqueMarkers = Array.from(new Set(Object.values(markerLookup)));

        const searchCounts = [];

        let expanded = 0;

        searchSteps.forEach((step, idx) => {

            if (step && step.action === 'expand') { expanded += 1; }

            searchCounts[idx] = expanded;

        });



        const routeState = { index: -1, playing: false, timer: null };

        const searchState = { index: -1, playing: false, timer: null };

        const refs = {

            panel: null,

            status: { search: null, route: null },

            progress: { search: null, route: null },

            buttons: { search: {}, route: {} },

            info: {},

            metrics: {}

        };



        function layer(name){ return name ? window[name] : null; }



        function applyStyle(name, style){

            if (!name || !style) return;

            const marker = layer(name);

            if (marker && typeof marker.setStyle === 'function'){

                marker.setStyle(style);

            }

        }



        function resetNodes(){

            uniqueMarkers.forEach(name => {

                const style = markerStyles[name];

                if (style){

                    applyStyle(name, Object.assign({}, style));

                }

            });

        }



        function fmtNode(id){

            if (id === undefined || id === null) return '-';

            return String(id);

        }



        function fmtPath(path){

            if (!Array.isArray(path) || !path.length) return '-';

            return path.map(fmtNode).join(' -> ');

        }



        function setSegments(){

            routeSegments.forEach((seg, idx) => {

                const poly = layer(seg);

                if (!poly || typeof poly.setStyle !== 'function') return;

                const visible = routeState.index > idx;

                poly.setStyle({ opacity: visible ? 1.0 : 0.0 });

                if (visible && typeof poly.bringToFront === 'function'){

                    poly.bringToFront();

                }

            });

        }



        function routeStyle(node){

            if (!node || !node.name) return {};

            const base = Object.assign({}, markerStyles[node.name] || {});

            if (node.role === 'start' || node.role === 'goal'){

                return base;

            }

            base.color = '#1f6feb';

            base.fillColor = '#1f6feb';

            base.fillOpacity = 1.0;

            base.opacity = 1.0;

            base.weight = 1;

            return base;

        }



        function highlightStyle(node){

            const base = routeStyle(node);

            const fallback = (node && node.name) ? (markerStyles[node.name] || {}) : {};

            const radius = base.radius || fallback.radius || 8;

            const weight = base.weight || fallback.weight || 2;

            base.radius = radius + 3;

            base.weight = weight + 1;

            base.color = '#1f6feb';

            base.fillColor = '#1f6feb';

            base.fillOpacity = 1.0;

            return base;

        }



        function renderRoute(){

            resetNodes();

            setSegments();

            for (let i = 0; i < routeState.index; i++){

                const node = routeNodes[i];

                if (node && node.name){

                    applyStyle(node.name, routeStyle(node));

                }

            }

            if (routeState.index >= 0){

                const node = routeNodes[routeState.index];

                if (node && node.name){

                    applyStyle(node.name, highlightStyle(node));

                }

            }

            if (routeNodes.length && routeState.index >= routeNodes.length - 1){

                const finalNode = routeNodes[routeNodes.length - 1];

                if (finalNode && finalNode.role === 'goal' && finalNode.name){

                    const base = Object.assign({}, markerStyles[finalNode.name] || {});

                    if (!base.fillColor){

                        base.fillColor = '#ffd447';

                    }

                    base.color = base.color || '#b45309';

                    applyStyle(finalNode.name, base);

                }

            }

            if (refs.status.route){

                if (!routeNodes.length){

                    refs.status.route.textContent = 'Route playback unavailable.';

                } else if (routeState.index < 0){

                    refs.status.route.textContent = 'Ready - ' + routeNodes.length + ' stop(s)';

                } else {

                    const node = routeNodes[routeState.index];

                    const label = node && node.label ? node.label : 'Unknown';

                    refs.status.route.textContent = 'Stop ' + (routeState.index + 1) + '/' + routeNodes.length + ': ' + label;

                }

            }

            if (refs.progress.route){

                const pct = routeState.index < 0 || !routeNodes.length ? 0 : ((routeState.index + 1) / routeNodes.length) * 100;

                refs.progress.route.style.width = Math.min(100, pct) + '%';

            }

        }



        function highlightNode(id, opts){

            const markerName = markerLookup[String(id)];

            if (!markerName) return;

            const base = Object.assign({}, markerStyles[markerName] || {});

            Object.assign(base, opts || {});

            applyStyle(markerName, base);

        }



        function applyExploredStyles(limit){

            if (limit === undefined || limit === null || limit < 0) return;

            const visited = new Set();

            for (let i = 0; i <= limit && i < searchSteps.length; i++){

                const step = searchSteps[i];

                if (step && (step.action === 'expand' || step.action === 'goal_found')){

                    visited.add(step.node_id);

                }

            }

            visited.forEach(id => {

                highlightNode(id, {

                    color: '#3730a3',

                    fillColor: '#c7d2fe',

                    fillOpacity: 0.85,

                    opacity: 1,

                    radius: 9,

                    weight: 2

                });

            });

        }



        function paintSearch(step){

            if (!step) return;

            const path = Array.isArray(step.path) ? step.path : [];

            path.forEach(id => highlightNode(id, {

                color: '#818cf8',

                fillColor: '#c7d2fe',

                fillOpacity: 0.95,

                opacity: 1

            }));

            if (step.action === 'expand' || step.action === 'goal_found'){

                highlightNode(step.node_id, {

                    color: step.action === 'goal_found' ? '#16a34a' : '#f97316',

                    fillColor: step.action === 'goal_found' ? '#86efac' : '#fed7aa',

                    radius: 11,

                    weight: 3,

                    fillOpacity: 1

                });

            } else if (step.action === 'add_to_frontier'){

                highlightNode(step.parent_id, {

                    color: '#ec4899',

                    fillColor: '#fdf2f8',

                    radius: 10,

                    weight: 3,

                    fillOpacity: 1

                });

                (step.children_ids || []).forEach(id => {

                    highlightNode(id, {

                        color: '#0ea5e9',

                        fillColor: '#bae6fd',

                        radius: 9,

                        weight: 2,

                        fillOpacity: 1

                    });

                });

            }

        }



        function renderSearch(){

            resetNodes();

            const step = searchState.index >= 0 ? searchSteps[searchState.index] : null;

            if (searchSteps.length){

                applyExploredStyles(searchState.index);

                paintSearch(step);

            }

            if (refs.status.search){

                if (!searchSteps.length){

                    refs.status.search.textContent = 'Search diagnostics unavailable.';

                } else if (searchState.index < 0){

                    refs.status.search.textContent = 'Ready - ' + searchSteps.length + ' recorded step(s)';

                } else {

                    refs.status.search.textContent = 'Step ' + (searchState.index + 1) + '/' + searchSteps.length;

                }

            }

            if (refs.progress.search){

                const pct = searchState.index < 0 || !searchSteps.length ? 0 : ((searchState.index + 1) / searchSteps.length) * 100;

                refs.progress.search.style.width = Math.min(100, pct) + '%';

            }

            const summary = refs.info.summary;

            const fromLine = refs.info.from;

            const pathLine = refs.info.path;

            const frontierLine = refs.info.frontier;

            const exploredMetric = refs.metrics.explored;

            const frontierMetric = refs.metrics.frontier;

            if (!step){

                if (summary) summary.textContent = 'Summary: No step selected';

                if (fromLine) fromLine.textContent = 'From: -';

                if (pathLine) pathLine.textContent = 'Path: -';

                if (frontierLine) frontierLine.textContent = 'Frontier: -';

                if (exploredMetric) exploredMetric.textContent = searchSteps.length ? '0' : '-';

                if (frontierMetric) frontierMetric.textContent = '0';

                return;

            }

            let summaryText = '';

            if (step.action === 'expand'){

                summaryText = 'Expanding ' + fmtNode(step.node_id);

            } else if (step.action === 'add_to_frontier'){

                summaryText = 'Adding to frontier';

            } else if (step.action === 'goal_found'){

                summaryText = 'Goal reached at ' + fmtNode(step.node_id);

            } else {

                summaryText = 'Step: ' + (step.action || 'unknown');

            }

            if (summary) summary.textContent = 'Summary: ' + summaryText;

            let fromText = '-';

            if (step.action === 'add_to_frontier'){

                fromText = fmtNode(step.parent_id);

            } else if (Array.isArray(step.path) && step.path.length > 1){

                fromText = fmtNode(step.path[step.path.length - 2]);

            }

            if (fromLine) fromLine.textContent = 'From: ' + fromText;

            if (pathLine) pathLine.textContent = 'Path: ' + fmtPath(step.path);

            let frontierText = 'Frontier: -';

            let frontierCount = 0;

            if (step.action === 'add_to_frontier'){

                const children = step.children_ids || [];

                frontierCount = children.length;

                frontierText = children.length ? ('Frontier: ' + children.map(fmtNode).join(', ')) : 'Frontier: none';

            }

            if (frontierLine) frontierLine.textContent = frontierText;

            if (exploredMetric) exploredMetric.textContent = String(searchCounts[searchState.index] || 0);

            if (frontierMetric) frontierMetric.textContent = String(frontierCount);



            if (routeNodes.length && searchState.index >= searchSteps.length - 1){

                setRouteIndex(routeNodes.length - 1);

            }

        }



        function setRouteIndex(idx){

            if (!routeNodes.length) return;

            const capped = Math.max(-1, Math.min(idx, routeNodes.length - 1));

            routeState.index = capped;

            renderRoute();

        }



        function setSearchIndex(idx){

            if (!searchSteps.length) return;

            const capped = Math.max(-1, Math.min(idx, searchSteps.length - 1));

            searchState.index = capped;

            renderSearch();

        }



        function stopRouteAutoplay(){

            routeState.playing = false;

            if (routeState.timer){

                clearTimeout(routeState.timer);

                routeState.timer = null;

            }

            if (refs.buttons.route.play){

                refs.buttons.route.play.textContent = routeState.index >= routeNodes.length - 1 ? 'Replay' : 'Play';

            }

        }



        function stopSearchAutoplay(){

            searchState.playing = false;

            if (searchState.timer){

                clearTimeout(searchState.timer);

                searchState.timer = null;

            }

            if (refs.buttons.search.play){

                refs.buttons.search.play.textContent = searchState.index >= searchSteps.length - 1 ? 'Replay' : 'Play';

            }

        }



        function routeTick(){

            if (!routeState.playing) return;

            if (routeState.timer){

                clearTimeout(routeState.timer);

            }

            routeState.timer = setTimeout(() => {

                if (routeState.index >= routeNodes.length - 1){

                    stopRouteAutoplay();

                    return;

                }

                setRouteIndex(routeState.index + 1);

                routeTick();

            }, routeDelay);

        }



        function startRouteAutoplayFromStart(){

            if (!routeNodes.length) return;

            stopRouteAutoplay();

            setRouteIndex(-1);

            routeState.playing = true;

            if (refs.buttons.route.play){

                refs.buttons.route.play.textContent = 'Pause';

            }

            routeTick();

        }



        function searchTick(){

            if (!searchState.playing) return;

            if (searchState.timer){

                clearTimeout(searchState.timer);

            }

            searchState.timer = setTimeout(() => {

                if (searchState.index >= searchSteps.length - 1){

                    stopSearchAutoplay();

                    return;

                }

                setSearchIndex(searchState.index + 1);

                searchTick();

            }, searchDelay);

        }



        function ensureStyles(){

            if (document.getElementById('rpc-styles')) return;

            const style = document.createElement('style');

            style.id = 'rpc-styles';

            style.textContent = `

                .rpc-panel{

                    position:fixed;z-index:10000;

                    background:rgba(255,255,255,0.96);border-radius:12px;

                    padding:12px 14px;box-shadow:0 15px 35px rgba(76,29,149,0.2);

                    min-width:230px;max-width:270px;border:1px solid rgba(79,70,229,0.2);

                    font-family:'Inter',system-ui,-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;

                    color:#0f172a;

                }

                #rpc-search-panel{top:10px;right:10px;max-width:260px;min-width:220px;transform:scale(0.92);transform-origin:top right;}

                #rpc-route-panel{bottom:12px;right:12px;}

                .rpc-panel .rpc-section{margin-bottom:0;}

                .rpc-panel .rpc-title{

                    text-transform:uppercase;font-size:11px;font-weight:700;

                    letter-spacing:0.08em;color:#4338ca;margin-bottom:3px;

                }

                .rpc-panel .rpc-status{

                    font-size:10px;color:#475569;margin-bottom:5px;

                }

                .rpc-panel .rpc-progress{

                    position:relative;height:3px;background:rgba(99,102,241,0.2);

                    border-radius:999px;overflow:hidden;margin-bottom:6px;

                }

                .rpc-panel .rpc-progress span{

                    position:absolute;top:0;left:0;bottom:0;width:0%;

                    background:linear-gradient(90deg,#4f46e5,#a855f7);

                    transition:width 0.25s ease;

                }

                .rpc-panel .rpc-details{

                    font-size:11px;color:#475569;line-height:1.4;margin-bottom:8px;

                }

                .rpc-panel .rpc-metrics{

                    display:flex;gap:8px;margin-bottom:6px;

                }

                .rpc-panel .rpc-metric{

                    flex:1;background:rgba(99,102,241,0.08);border-radius:10px;padding:5px;

                }

                .rpc-panel .rpc-metric span{

                    display:block;font-size:9px;font-weight:600;color:#6366f1;

                }

                .rpc-panel .rpc-metric strong{

                    font-size:13px;color:#312e81;

                }

                .rpc-panel .rpc-buttons{

                    display:flex;gap:6px;margin-bottom:6px;

                }

                .rpc-panel button{

                    flex:1;border:none;border-radius:8px;padding:5px 7px;

                    font-size:11px;font-weight:600;cursor:pointer;

                    background:rgba(129,140,248,0.18);color:#312e81;

                }

                .rpc-panel button.rpc-primary{

                    background:linear-gradient(135deg,#4f46e5,#9333ea);color:#fff;

                    box-shadow:0 8px 20px rgba(59,7,100,0.25);

                }

                .rpc-panel button:disabled{

                    opacity:0.45;cursor:not-allowed;

                }

                .rpc-panel .rpc-footer{

                    display:flex;justify-content:flex-end;

                }

                .rpc-panel .rpc-footer button{

                    flex:0 0 auto;background:transparent;color:#7c3aed;

                    text-decoration:underline;padding:0;

                }

                .rpc-panel .rpc-disabled{

                    opacity:0.55;

                }

            `;

            document.head.appendChild(style);

        }



        function buildPanels(){

            ensureStyles();

            const searchPanel = document.createElement('div');

            searchPanel.id = 'rpc-search-panel';

            searchPanel.className = 'rpc-panel';

            searchPanel.innerHTML = `

                <div class="rpc-section" data-block="search">

                    <div class="rpc-title">Search exploration</div>

                    <div class="rpc-status" data-role="search-status">Preparing...</div>

                    <div class="rpc-progress"><span data-role="search-progress"></span></div>

                    <div class="rpc-details">

                        <div data-role="summary">Summary: -</div>

                        <div data-role="from">From: -</div>

                        <div data-role="path">Path: -</div>

                        <div data-role="frontier">Frontier: -</div>

                    </div>

                    <div class="rpc-metrics">

                        <div class="rpc-metric"><span>Nodes explored</span><strong data-role="explored">0</strong></div>

                        <div class="rpc-metric"><span>Frontier size</span><strong data-role="frontier-count">0</strong></div>

                    </div>

                    <div class="rpc-buttons">

                        <button data-action="search-prev">Prev</button>

                        <button class="rpc-primary" data-action="search-play">Play</button>

                        <button data-action="search-next">Next</button>

                    </div>

                    <div class="rpc-footer"><button data-action="search-reset">Reset</button></div>

                </div>

            `;

            document.body.appendChild(searchPanel);



            const routePanel = document.createElement('div');

            routePanel.id = 'rpc-route-panel';

            routePanel.className = 'rpc-panel';

            routePanel.innerHTML = `

                <div class="rpc-section" data-block="route">

                    <div class="rpc-title">Route playback</div>

                    <div class="rpc-status" data-role="route-status">Preparing...</div>

                    <div class="rpc-progress"><span data-role="route-progress"></span></div>

                    <div class="rpc-buttons">

                        <button data-action="route-prev">Prev</button>

                        <button class="rpc-primary" data-action="route-play">Play</button>

                        <button data-action="route-next">Next</button>

                    </div>

                    <div class="rpc-footer"><button data-action="route-reset">Reset</button></div>

                </div>

            `;

            document.body.appendChild(routePanel);



            refs.status.search = searchPanel.querySelector('[data-role="search-status"]');

            refs.progress.search = searchPanel.querySelector('[data-role="search-progress"]');

            refs.info.summary = searchPanel.querySelector('[data-role="summary"]');

            refs.info.from = searchPanel.querySelector('[data-role="from"]');

            refs.info.path = searchPanel.querySelector('[data-role="path"]');

            refs.info.frontier = searchPanel.querySelector('[data-role="frontier"]');

            refs.metrics.explored = searchPanel.querySelector('[data-role="explored"]');

            refs.metrics.frontier = searchPanel.querySelector('[data-role="frontier-count"]');

            refs.buttons.search.prev = searchPanel.querySelector('[data-action="search-prev"]');

            refs.buttons.search.next = searchPanel.querySelector('[data-action="search-next"]');

            refs.buttons.search.play = searchPanel.querySelector('[data-action="search-play"]');

            refs.buttons.search.reset = searchPanel.querySelector('[data-action="search-reset"]');



            refs.status.route = routePanel.querySelector('[data-role="route-status"]');

            refs.progress.route = routePanel.querySelector('[data-role="route-progress"]');

            refs.buttons.route.prev = routePanel.querySelector('[data-action="route-prev"]');

            refs.buttons.route.next = routePanel.querySelector('[data-action="route-next"]');

            refs.buttons.route.play = routePanel.querySelector('[data-action="route-play"]');

            refs.buttons.route.reset = routePanel.querySelector('[data-action="route-reset"]');



            if (!searchSteps.length){

                const block = searchPanel.querySelector('[data-block="search"]');

                if (block) block.classList.add('rpc-disabled');

            }

            if (!routeNodes.length){

                const block = routePanel.querySelector('[data-block="route"]');

                if (block) block.classList.add('rpc-disabled');

            }



            if (refs.buttons.search.prev){

                refs.buttons.search.prev.addEventListener('click', () => { stopSearchAutoplay(); setSearchIndex(searchState.index - 1); });

            }

            if (refs.buttons.search.next){

                refs.buttons.search.next.addEventListener('click', () => { stopSearchAutoplay(); setSearchIndex(searchState.index + 1); });

            }

            if (refs.buttons.search.play){

                refs.buttons.search.play.addEventListener('click', () => {

                    if (!searchSteps.length) return;

                    if (searchState.playing){

                        stopSearchAutoplay();

                    } else {

                        if (searchState.index >= searchSteps.length - 1){

                            setSearchIndex(-1);

                            if (routeNodes.length) {

                                stopRouteAutoplay();

                                setRouteIndex(-1);

                            }

                        }

                        searchState.playing = true;

                        refs.buttons.search.play.textContent = 'Pause';

                        searchTick();

                    }

                });

            }

            if (refs.buttons.search.reset){

                refs.buttons.search.reset.addEventListener('click', () => {

                    stopSearchAutoplay();

                    setSearchIndex(-1);

                    if (routeNodes.length) {

                        stopRouteAutoplay();

                        setRouteIndex(-1);

                    }

                });

            }



            if (refs.buttons.route.prev){

                refs.buttons.route.prev.addEventListener('click', () => { stopRouteAutoplay(); setRouteIndex(routeState.index - 1); });

            }

            if (refs.buttons.route.next){

                refs.buttons.route.next.addEventListener('click', () => { stopRouteAutoplay(); setRouteIndex(routeState.index + 1); });

            }

            if (refs.buttons.route.play){

                refs.buttons.route.play.addEventListener('click', () => {

                    if (!routeNodes.length) return;

                    if (routeState.playing){

                        stopRouteAutoplay();

                    } else {

                        if (routeState.index >= routeNodes.length - 1){

                            setRouteIndex(-1);

                        }

                        routeState.playing = true;

                        refs.buttons.route.play.textContent = 'Pause';

                        routeTick();

                    }

                });

            }

            if (refs.buttons.route.reset){

                refs.buttons.route.reset.addEventListener('click', () => {

                    stopRouteAutoplay();

                    setRouteIndex(-1);

                });

            }

        }



        buildPanels();

        renderRoute();

        renderSearch();

        startRouteAutoplayFromStart();

    })();

    </script>

    """

    animation_script = script_template.replace("__CONFIG__", json.dumps(config_payload))
    map_obj.get_root().html.add_child(folium.Element(animation_script))

def create_polyline(locations, color, weight, dash_array, opacity, tooltip_text, popup_html, map_obj, add_arrow=True):
    """Helper function to create polylines with consistent styling and optional arrows"""
    # Centralized folium polyline creation ensures consistent style arguments
    line = folium.PolyLine(
        locations=locations,
        color=color,
        weight=weight,
        dash_array=dash_array,
        opacity=opacity,
        tooltip=tooltip_text,
        popup=folium.Popup(popup_html, max_width=250)
    ).add_to(map_obj)
    
    # Capture this segment for client-side arrow animation
    if add_arrow and len(locations) >= 2:
        register_arrow_segment(map_obj, locations, color)
    
    return line


def extend_path_to_custom_nodes(latlngs, start_coord, end_coord, tolerance_m=GAP_TO_NODE_TOLERANCE_M):
    """Ensure rendered polylines reach the custom nodes but stop just outside the markers."""
    if not latlngs:
        return [start_coord, end_coord]

    extended = list(latlngs)

    def needs_connector(coord_a, coord_b):
        if coord_a is None or coord_b is None:
            return False
        # Compare geodesic distance and determine if a short connector is needed
        return haversine_km(coord_a[0], coord_a[1], coord_b[0], coord_b[1]) * 1000 > tolerance_m

    if needs_connector(start_coord, extended[0]):
        extended.insert(0, start_coord)
    if needs_connector(extended[-1], end_coord):
        extended.append(end_coord)

    def prune_endpoint(points, node_coord, from_start=True):
        if not node_coord:
            return
        while points:
            idx = 0 if from_start else -1
            target = points[idx]
            dist_m = haversine_km(node_coord[0], node_coord[1], target[0], target[1]) * 1000
            if dist_m <= NODE_OVERLAP_PRUNE_M:
                points.pop(idx)
            else:
                break

    def offset_from_node(node_coord, anchor_coord):
        if not node_coord or not anchor_coord:
            return None
        dist_m = haversine_km(node_coord[0], node_coord[1], anchor_coord[0], anchor_coord[1]) * 1000
        if dist_m <= 1e-6:
            return None
        ratio = min(ROUTE_NODE_CLEARANCE_M / dist_m, 0.45)
        if ratio <= 0:
            return None
        return (
            node_coord[0] + (anchor_coord[0] - node_coord[0]) * ratio,
            node_coord[1] + (anchor_coord[1] - node_coord[1]) * ratio
        )

    prune_endpoint(extended, start_coord, from_start=True)
    prune_endpoint(extended, end_coord, from_start=False)

    if not extended and start_coord and end_coord:
        start_point = offset_from_node(start_coord, end_coord)
        end_point = offset_from_node(end_coord, start_coord)
        if start_point and end_point:
            extended = [start_point, end_point]

    if not extended:
        if start_coord and end_coord:
            return [start_coord, end_coord]
        return extended

    anchor_start = extended[0] if extended else end_coord
    start_point = offset_from_node(start_coord, anchor_start)
    if start_point:
        extended.insert(0, start_point)

    anchor_end = extended[-1] if extended else start_coord
    end_point = offset_from_node(end_coord, anchor_end)
    if end_point:
        extended.append(end_point)

    return extended

def visualize_simple_graph(nodes, ways, cameras, meta, out_html, solution_path=None, other_paths=None, exploration_steps=None):
    """Generate simplified graph visualization with plain background and arrow-headed paths"""
    center_lat, center_lon = get_map_center(nodes)
    exploration_steps = exploration_steps or []
    
    # Create map with CartoDB Positron (light, minimal background)
    m = folium.Map(
        location=[center_lat, center_lon],
        zoom_start=16,
        tiles='CartoDB positron',
        attr='Simple Graph View'
    )
    
    # Add custom CSS to make background even lighter/whiter
    custom_css = """

    <style>

        .leaflet-container {

            background: #f8f9fa !important;

        }

        .leaflet-tile-pane {

            opacity: 0.15 !important;

        }

    </style>

    """
    m.get_root().html.add_child(folium.Element(custom_css))
    
    # Build solution edges set
    solution_edges = set()
    if solution_path and len(solution_path) > 1:
        for i in range(len(solution_path) - 1):
            solution_edges.add((solution_path[i], solution_path[i+1]))
    solution_nodes_set = set(solution_path or [])
    
    # Build other solution edges
    other_solution_edges = set()
    if other_paths:
        for entry in other_paths:
            path = entry.get("path") if isinstance(entry, dict) else entry
            if not path or len(path) < 2:
                continue
            for i in range(len(path) - 1):
                edge = (path[i], path[i + 1])
                if edge not in solution_edges:
                    other_solution_edges.add(edge)

    # Quick lookup for reverse edges so we can position paired arrows without overlap
    edge_lookup = {(w["from"], w["to"]): w for w in ways}
    solution_segment_layers = []
    
    # Draw all edges as simple lines with arrows
    for w in ways:
        way_id = w["way_id"]
        u, v = w["from"], w["to"]
        rn = w["road_name"]
        time_min = w["time_min"]
        start_coord = (nodes[u]["lat"], nodes[u]["lon"])
        end_coord = (nodes[v]["lat"], nodes[v]["lon"])
        
        # Determine edge type (but don't highlight solution paths)
        is_camera = way_id in cameras
        is_accident = w.get("accident", False)

        # Style based on edge type - accidents get priority coloring
        if is_accident:
            # Get severity to determine color
            severity = w.get("severity", "severe").lower()
            
            # Map severity to colors: yellow=minor, orange=moderate, red=severe
            severity_colors = {
                "minor": "#FFC107",      # Yellow
                "moderate": "#FF9800",  # Orange
                "severe": "#F44336"     # Red
            }
            color = severity_colors.get(severity, "#F44336")  # Default to red
            weight = 5
            opacity = 1.0
        elif is_camera:
            color = '#ef4444'  # Red for camera roads
            weight = 3
            opacity = 0.92
        else:
            color = '#64748b'  # Slate gray for all regular roads
            weight = 2.6
            opacity = 0.78

        # Create simple line
        line = folium.PolyLine(
            locations=[start_coord, end_coord],
            color=color,
            weight=weight,
            opacity=opacity,
            tooltip=f"{rn} ({time_min} min) | {u} -> {v}"
        )
        line.add_to(m)
        register_arrow_segment(m, [start_coord, end_coord], color)
    
    # Add overlay polylines for the selected solution path so we can animate step-by-step playback
    if solution_path and len(solution_path) > 1:
        for idx in range(len(solution_path) - 1):
            u = solution_path[idx]
            v = solution_path[idx + 1]
            w = edge_lookup.get((u, v))
            if w:
                start_coord = (nodes[u]["lat"], nodes[u]["lon"])
                end_coord = (nodes[v]["lat"], nodes[v]["lon"])
            else:
                start_coord = (nodes.get(u, {}).get("lat"), nodes.get(u, {}).get("lon"))
                end_coord = (nodes.get(v, {}).get("lat"), nodes.get(v, {}).get("lon"))
            if None in (*start_coord, *end_coord):
                continue
            seg = folium.PolyLine(
                locations=[start_coord, end_coord],
                color="#2563eb",
                weight=5,
                opacity=0.0,
                tooltip=f"Step {idx + 1}: {u} -> {v}"
            ).add_to(m)
            solution_segment_layers.append(seg.get_name())
    
    # Draw nodes
    start_node = meta.get("start")
    goal_nodes = set(meta.get("goals", []))
    node_marker_names = {}
    node_marker_styles = {}
    node_metadata = {}
    
    for nid, info in nodes.items():
        lat, lon = info["lat"], info["lon"]
        label = info["label"]
        
        # Determine node style - only highlight start and goal
        if nid == start_node:
            color = '#10b981'
            fill_color = '#d1fae5'
            radius = 10
            icon_text = 'S'
        elif nid in goal_nodes:
            color = '#f59e0b'
            fill_color = '#fef3c7'
            radius = 10
            icon_text = 'G'
        else:
            # All other nodes are uniform
            color = '#64748b'
            fill_color = '#f1f5f9'
            radius = 6
            icon_text = ''
        
        if nid in solution_nodes_set and nid not in goal_nodes and nid != start_node:
            color = '#2563eb'
            fill_color = '#e0ecff'
            radius = max(radius, 7)
        
        # Create circle marker for node
        marker = folium.CircleMarker(
            location=(lat, lon),
            radius=radius,
            color=color,
            fill=True,
            fillColor=fill_color,
            fillOpacity=0.9,
            weight=2,
            popup=f"<b>{label}</b><br>ID: {nid}",
            tooltip=label
        ).add_to(m)
        marker_name = marker.get_name()
        node_marker_names[str(nid)] = marker_name
        node_marker_styles[marker_name] = {
            "color": color,
            "fillColor": fill_color,
            "radius": radius,
            "weight": 2,
            "fillOpacity": 0.9,
            "opacity": 1.0
        }
        node_metadata[str(nid)] = {"label": label}
        
        # Add text label for start/goal nodes
        if icon_text:
            folium.Marker(
                location=(lat, lon),
                icon=folium.DivIcon(
                    html=f'<div style="font-size: 10px; font-weight: bold; color: {color}; text-align: center; margin-top: -20px;">{icon_text}</div>'
                )
            ).add_to(m)
    
    # Inject step-by-step playback controls for the simplified map
    ordered_node_markers = []
    if solution_path:
        for nid in solution_path:
            marker_name = node_marker_names.get(str(nid))
            if marker_name:
                if nid == start_node:
                    role = "start"
                elif nid in goal_nodes:
                    role = "goal"
                else:
                    role = "normal"
                ordered_node_markers.append({
                    "id": nid,
                    "name": marker_name,
                    "label": nodes[nid]["label"],
                    "role": role
                })
    if ordered_node_markers:
        config_payload = {
            "routeSegments": solution_segment_layers,
            "routeNodes": ordered_node_markers,
            "markerStyles": node_marker_styles,
            "nodeMarkerLookup": node_marker_names,
            "nodeMetadata": node_metadata,
            "searchSteps": exploration_steps,
            "routeStepDelay": 850,
            "searchStepDelay": 1050
        }
        inject_route_playback(m, config_payload)
    
    # Add legend
    legend_html = """

    <div style="

        position: fixed;

        bottom: 8px;

        left: 20px;

        z-index: 9999;

        background: rgba(255,255,255,0.95);

        padding: 12px 16px;

        border: 2px solid #333;

        border-radius: 8px;

        font-size: 13px;

        line-height: 1.6;

        box-shadow: 0 4px 12px rgba(0,0,0,0.15);

        font-family: system-ui, -apple-system, sans-serif;

    ">

    <b style="font-size: 14px;">Simple Graph View</b><br>

    <div style="display:flex;align-items:center;gap:8px;margin-top:4px;">

        <span style="display:inline-block;width:0;height:0;border-left:7px solid transparent;border-right:7px solid transparent;border-bottom:14px solid #475569;filter:drop-shadow(0 0 3px #fff);transform:rotate(90deg);"></span>

        <span style="color:#475569;font-weight:600;">One-way edge</span>

    </div>

    <div style="display:flex;align-items:center;gap:8px;margin-top:6px;">

        <span style="display:inline-block;width:0;height:0;border-left:7px solid transparent;border-right:7px solid transparent;border-bottom:14px solid #ef4444;filter:drop-shadow(0 0 3px #fff);transform:rotate(90deg);"></span>

        <span style="color:#ef4444;font-weight:600;">Camera road</span>

    </div>

    <div style="display:flex;align-items:center;gap:8px;margin-top:6px;">

        <span style="width:10px;height:10px;border:2px solid #10b981;border-radius:50%;background:#d1fae5;display:inline-block;"></span>

        <span style="color:#0f766e;font-weight:600;">Start node (S)</span>

    </div>

    <div style="display:flex;align-items:center;gap:8px;margin-top:6px;">

        <span style="width:10px;height:10px;border:2px solid #f59e0b;border-radius:50%;background:#fef3c7;display:inline-block;"></span>

        <span style="color:#b45309;font-weight:600;">Goal node (G)</span>

    </div>

    <div style="display:flex;align-items:center;gap:8px;margin-top:6px;">

        <span style="width:8px;height:8px;border:2px solid #64748b;border-radius:50%;background:#f8fafc;display:inline-block;"></span>

        <span style="color:#475569;">Regular nodes</span>

    </div>

    <small style="color:#475569;display:block;margin-top:8px;"><i>Two-way edges show two arrows on the line.</i></small>

    </div>

    """
    m.get_root().html.add_child(folium.Element(legend_html))
    
    inject_arrow_animation(m)
    m.save(out_html)



def visualize_with_roads(nodes, ways, cameras, meta, osm_nodes, graph, 

                        out_html, solution_path=None, other_paths=None, exploration_steps=None, k_snap=8):
    """Generate interactive Folium map with road visualization"""
    center_lat, center_lon = get_map_center(nodes)

    # Base map uses OpenStreetMap tiles around the dataset centroid
    m = folium.Map(
        location=[center_lat, center_lon],
        zoom_start=16,
        tiles="OpenStreetMap"
    )

    # Convenience set for quick membership tests while styling nodes
    solution_nodes_set = set(solution_path or [])
    exploration_steps = exploration_steps or []

    # Pre-compute snap candidates for all nodes
    snap_candidates = {}
    for nid, info in nodes.items():
        # Snap each custom node to multiple nearby OSM nodes for routing
        snap_candidates[nid] = k_nearest_graph_nodes(
            info["lat"], info["lon"], osm_nodes, graph, k=k_snap
        )

    # Build solution edges set
    solution_edges = set()
    if solution_path and len(solution_path) > 1:
        for i in range(len(solution_path) - 1):
            # Store each directed edge belonging to the selected solution
            solution_edges.add((solution_path[i], solution_path[i+1]))

    # Build other solution edges and route mapping
    # Track edges for alternate solutions plus associated Folium layers
    other_solution_edges = set()
    edge_route_map = {}
    solution_edge_layers = {}
    
    if other_paths:
        for entry in other_paths:
            path = entry.get("path") if isinstance(entry, dict) else entry
            route_id = entry.get("id") if isinstance(entry, dict) else None

            if not path or len(path) < 2:
                continue

            for i in range(len(path) - 1):
                edge = (path[i], path[i + 1])
                if edge not in solution_edges:
                    other_solution_edges.add(edge)
                    if route_id is not None:
                        # Track which optional route uses a given edge
                        edge_route_map.setdefault(edge, set()).add(route_id)

    # Keep JS references to dynamic polylines for interactivity hooks
    route_polyline_refs = {}
    solution_line_names = []
    
    # Build a set of reverse edges to detect parallel roads
    reverse_edges = {}
    for w in ways:
        reverse_edges[(w["from"], w["to"])] = w["way_id"]

    # Draw all ways/roads
    for w in ways:
        way_id = w["way_id"]
        u, v = w["from"], w["to"]
        rn = w["road_name"]
        hwy = w["highway_type"]
        time_min = w["time_min"]
        start_coord = (nodes[u]["lat"], nodes[u]["lon"])
        end_coord = (nodes[v]["lat"], nodes[v]["lon"])

        # Find best OSM path between nodes
        best_path = None
        best_len = None

        for u_osm in snap_candidates[u]:
            for v_osm in snap_candidates[v]:
                path = dijkstra_path(graph, u_osm, v_osm)
                if path is None:
                    continue
                plen = path_length_km(path, graph)
                if best_len is None or plen < best_len:
                    best_len = plen
                    best_path = path

        # Build coordinates list
        if best_path is None:
            # Fall back to drawing a straight line if OSM snapping fails
            latlngs = [start_coord, end_coord]
        else:
            latlngs = [(osm_nodes[nid][0], osm_nodes[nid][1]) for nid in best_path]

        # Always append the true node coordinates so the line reaches the endpoints
        latlngs = extend_path_to_custom_nodes(latlngs, start_coord, end_coord)
        
        # Check if there's a reverse edge (parallel road)
        has_reverse = (v, u) in reverse_edges
        
        # Offset parallel roads slightly to make them visually distinct and clickable
        if has_reverse and len(latlngs) >= 2:
            # Apply perpendicular offset to separate parallel roads
            offset_distance = 0.00003  # ~3 meters offset
            offset_latlngs = []
            
            for i, coord in enumerate(latlngs):
                if i == 0 and i + 1 < len(latlngs):
                    # First point - use direction to next point
                    lat1, lon1 = coord
                    lat2, lon2 = latlngs[i + 1]
                elif i > 0:
                    # Other points - use direction from previous point
                    lat2, lon2 = coord
                    lat1, lon1 = latlngs[i - 1]
                else:
                    offset_latlngs.append(coord)
                    continue
                
                # Calculate perpendicular offset (rotate direction by 90 degrees)
                dlat = lat2 - lat1
                dlon = lon2 - lon1
                length = (dlat**2 + dlon**2)**0.5
                
                if length > 0:
                    # Perpendicular vector (rotate 90Β° right)
                    perp_lat = -dlon / length * offset_distance
                    perp_lon = dlat / length * offset_distance
                    offset_latlngs.append((coord[0] + perp_lat, coord[1] + perp_lon))
                else:
                    offset_latlngs.append(coord)
            
            latlngs = offset_latlngs

        # Determine edge type and styling
        is_solution = (u, v) in solution_edges
        route_ids_for_edge = list(edge_route_map.get((u, v), []))
        is_other_solution = (u, v) in other_solution_edges
        is_camera = way_id in cameras
        # These booleans determine styling (color/weight/dashed) for each polyline

        tooltip_text = f"{rn} ({time_min} min)"
        popup_html = (
            f"<b>{rn}</b><br>"
            f"way_id: {way_id}<br>"
            f"type: {hwy}<br>"
            f"time: {time_min} min<br>"
        )
        
        if is_camera:
            popup_html += "<b>CAMERA MONITORED</b><br>Accident x time multiplied<br>"
        if is_solution:
            popup_html += "<b style='color:#1f6feb;'>* SELECTED SOLUTION *</b>"
        elif is_other_solution:
            popup_html += "<b style='color:#cfe8ff;'>* OTHER SOLUTION *</b>"

        # Create appropriate polyline
        # Create appropriate polyline
        polyline_for_events = None
        
        # Check if this road has an accident (draw accident color first if needed)
        has_accident = w.get("accident", False)
        severity = w.get("severity", "none").lower() if has_accident else "none"
        
        # Only draw accident color if severity is not 'none'
        if has_accident and severity != "none":
            severity_colors = {
                "minor": "#FFC107",      # Yellow
                "moderate": "#FF9800",  # Orange
                "severe": "#F44336"     # Red
            }
            accident_color = severity_colors.get(severity, "#F44336")
            
            # Draw accident color as base layer (will be under blue if it's a solution path)
            folium.PolyLine(
                locations=latlngs,
                color=accident_color,
                weight=7,
                opacity=1.0,
                tooltip=tooltip_text + f" (ACCIDENT: {severity.upper()})"
            ).add_to(m)

        # πŸ”΅ 1. SELECTED SOLUTION (blue) - DRAW ON TOP
        if is_solution:
            polyline_for_events = create_polyline(
                latlngs, "#1f6feb", 5, None, 0.85, tooltip_text, popup_html, m
            )
            layer_name = polyline_for_events.get_name()
            solution_line_names.append(layer_name)
            solution_edge_layers[(u, v)] = layer_name

        # πŸ”Ή 2. OTHER SOLUTIONS
        elif is_other_solution:
            folium.PolyLine(
                locations=latlngs, color="#1c4fd8", weight=7,
                dash_array=None, opacity=0.9
            ).add_to(m)
            polyline_for_events = create_polyline(
                latlngs, "#e4f0ff", 5, None, 0.95, tooltip_text, popup_html, m
            )

        # πŸ”₯ 3. ACCIDENT ROADS (only if not already drawn above)
        elif has_accident:
            # Already drawn as base layer above, just create event handler
            polyline_for_events = create_polyline(
                latlngs, "transparent", 1, None, 0,
                tooltip_text + f" (ACCIDENT: {severity.upper()})",
                popup_html,
                m
            )

        # πŸ“Έ 4. CAMERA ROADS
        elif is_camera:
            polyline_for_events = create_polyline(
                latlngs, "crimson", 3, "8,4", 0.8,
                tooltip_text, popup_html, m
            )

        # πŸ›£ 5. NORMAL ROADS
        else:
            weight = 3 if hwy in ["primary", "secondary"] else 2
            polyline_for_events = create_polyline(
                latlngs, color_for_highway(hwy), weight, None, 0.25,
                tooltip_text, popup_html, m
            )

        # Attach click events
        if route_ids_for_edge:
            layer_name = polyline_for_events.get_name()
            for rid in route_ids_for_edge:
                route_polyline_refs.setdefault(rid, []).append(layer_name)


    # Add interactivity scripts for route selection
    if route_polyline_refs or solution_line_names:
        script_lines = ["<script>", "(function(){"]
        
        if route_polyline_refs:
            script_lines.extend([
                "function postSelectRoute(routeId){",
                "    if (window.parent && window.parent !== window) {",
                "        window.parent.postMessage({type: 'selectRoute', routeId: routeId}, '*');",
                "    }",
                "}",
                "function attachRouteClicks(){"
            ])
            for rid, names in route_polyline_refs.items():
                for layer_name in names:
                    script_lines.append(
                        f"    if (typeof {layer_name} !== 'undefined') {{ "
                        f"{layer_name}.on('click', function() {{ postSelectRoute({rid}); }}); }}"
                    )
            script_lines.append("}")

        if solution_line_names:
            script_lines.append("function bringSelectedToFront(){")
            for layer_name in solution_line_names:
                script_lines.append(
                    f"    if (typeof {layer_name} !== 'undefined' && {layer_name}.bringToFront) {{ "
                    f"{layer_name}.bringToFront(); }}"
                )
            script_lines.append("}")

        script_lines.extend([
            "function initControls(){",
            "    if (typeof attachRouteClicks === 'function') { attachRouteClicks(); }",
            "    if (typeof bringSelectedToFront === 'function') { bringSelectedToFront(); }",
            "}",
            "if (document.readyState === 'loading') {",
            "    document.addEventListener('DOMContentLoaded', initControls);",
            "} else {",
            "    initControls();",
            "}",
            "})();",
            "</script>"
        ])
        m.get_root().html.add_child(folium.Element("\n".join(script_lines)))

    # Draw node markers
    start_node = meta.get("start")
    goal_nodes = set(meta.get("goals", []))
    # Store references to folium markers for later animation/click handling
    node_marker_names = {}
    node_marker_styles = {}
    node_metadata = {}

    for nid, info in nodes.items():
        lat, lon, label = info["lat"], info["lon"], info["label"]

        # Determine node styling
        if nid == start_node:
            fill_color = "green"
            role = "START"
        elif nid in goal_nodes:
            fill_color = "#ffd447"
            role = "GOAL"
        else:
            fill_color = "white"
            role = "Node"

        if nid in solution_nodes_set:
            border_color = "#0ea5e9"
            border_weight = 2
        else:
            border_color = "black"
            border_weight = 1

        if nid == start_node or nid in goal_nodes:
            border_weight = 1

        circle_marker = folium.CircleMarker(
            location=(lat, lon),
            radius=8,
            color=border_color,
            weight=border_weight,
            fill=True,
            fill_color=fill_color,
            fill_opacity=0.9,
            opacity=0.9,
            popup=folium.Popup(
                f"<b>Node {nid}: {label}</b><br>"
                f"lat: {lat:.6f}<br>lon: {lon:.6f}<br>{role}",
                max_width=250
            ),
            tooltip=f"{nid}: {label} ({role})"
        ).add_to(m)

        marker_name = circle_marker.get_name()
        node_marker_names[str(nid)] = marker_name
        node_marker_styles[marker_name] = {
            "color": border_color,
            "fillColor": fill_color,
            "radius": 8,
            "weight": border_weight,
            "fillOpacity": 0.9,
            "opacity": 1.0
        }
        node_metadata[str(nid)] = {"label": label}
        # Save styling info so animation can temporarily modify the markers

        # Add label using HTML so node id and label stay visible
        folium.map.Marker(
            [lat, lon],
            icon=folium.DivIcon(
                html=f"""

                <div style="

                    font-size:10px;

                    font-weight:bold;

                    border-radius:3px;

                    padding:2px 3px;

                    white-space:nowrap;

                ">{nid}: {label}</div>

                """,
                icon_size=(0, 0),
                icon_anchor=(-10, 10)
            )
        ).add_to(m)
    # Add path animation for solution
    if solution_path:
        ordered_segment_layers = []
        for i in range(len(solution_path) - 1):
            layer_name = solution_edge_layers.get((solution_path[i], solution_path[i + 1]))
            if layer_name:
                # Preserve the segment order so the animation highlights edges sequentially
                ordered_segment_layers.append(layer_name)

        ordered_node_markers = []
        for nid in solution_path:
            marker_name = node_marker_names.get(str(nid))
            if marker_name:
                if nid == start_node:
                    role = "start"
                elif nid in goal_nodes:
                    role = "goal"
                else:
                    role = "normal"
                ordered_node_markers.append({
                    "id": nid,
                    "name": marker_name,
                    "label": nodes[nid]["label"],
                    "role": role
                })

        if ordered_node_markers:
            config_payload = {
                "routeSegments": ordered_segment_layers,
                "routeNodes": ordered_node_markers,
                "markerStyles": node_marker_styles,
                "nodeMarkerLookup": node_marker_names,
                "nodeMetadata": node_metadata,
                "searchSteps": exploration_steps,
                "routeStepDelay": 900,
                "searchStepDelay": 1100
            }
            script_template = """

            <script>

            (function(){

                const cfg = __CONFIG__;

                if (!cfg) return;

                const routeNodes = cfg.routeNodes || [];

                const routeSegments = cfg.routeSegments || [];

                const markerStyles = cfg.markerStyles || {};

                const markerLookup = cfg.nodeMarkerLookup || {};

                const nodeMeta = cfg.nodeMetadata || {};

                const searchSteps = cfg.searchSteps || [];

                const routeDelay = cfg.routeStepDelay || 900;

                const searchDelay = cfg.searchStepDelay || 1100;

                const uniqueMarkers = Array.from(new Set(Object.values(markerLookup)));

                const searchCounts = [];

                let expanded = 0;

                searchSteps.forEach((step, idx) => {

                    if (step && step.action === 'expand') { expanded += 1; }

                    searchCounts[idx] = expanded;

                });



                const routeState = { index: -1, playing: false, timer: null };

                const searchState = { index: -1, playing: false, timer: null };

                const refs = {

                    panel: null,

                    status: { search: null, route: null },

                    progress: { search: null, route: null },

                    buttons: { search: {}, route: {} },

                    info: {},

                    metrics: {}

                };



                function layer(name){ return name ? window[name] : null; }



                function applyStyle(name, style){

                    if (!name || !style) return;

                    const marker = layer(name);

                    if (marker && typeof marker.setStyle === 'function'){

                        marker.setStyle(style);

                    }

                }



                function resetNodes(){

                    uniqueMarkers.forEach(name => {

                        const style = markerStyles[name];

                        if (style){

                            applyStyle(name, Object.assign({}, style));

                        }

                    });

                }



                function fmtNode(id){

                    if (id === undefined || id === null) return '-';

                    return String(id);

                }



                function fmtPath(path){

                    if (!Array.isArray(path) || !path.length) return '-';

                    return path.map(fmtNode).join(' -> ');

                }



                function setSegments(){

                    routeSegments.forEach((seg, idx) => {

                        const poly = layer(seg);

                        if (!poly || typeof poly.setStyle !== 'function') return;

                        const visible = routeState.index > idx;

                        poly.setStyle({ opacity: visible ? 1.0 : 0.0 });

                        if (visible && typeof poly.bringToFront === 'function'){

                            poly.bringToFront();

                        }

                    });

                }



                function routeStyle(node){

                    if (!node || !node.name) return {};

                    const base = Object.assign({}, markerStyles[node.name] || {});

                    if (node.role === 'start' || node.role === 'goal'){

                        return base;

                    }

                    base.color = '#1f6feb';

                    base.fillColor = '#1f6feb';

                    base.fillOpacity = 1.0;

                    base.opacity = 1.0;

                    base.weight = 1;

                    return base;

                }



                function highlightStyle(node){

                    const base = routeStyle(node);

                    const fallback = (node && node.name) ? (markerStyles[node.name] || {}) : {};

                    const radius = base.radius || fallback.radius || 8;

                    const weight = base.weight || fallback.weight || 2;

                    base.radius = radius + 3;

                    base.weight = weight + 1;

                    base.color = '#1f6feb';

                    base.fillColor = '#1f6feb';

                    base.fillOpacity = 1.0;

                    return base;

                }



                function renderRoute(){

                    resetNodes();

                    setSegments();

                    for (let i = 0; i < routeState.index; i++){

                        const node = routeNodes[i];

                        if (node && node.name){

                            applyStyle(node.name, routeStyle(node));

                        }

                    }

                    if (routeState.index >= 0){

                        const node = routeNodes[routeState.index];

                        if (node && node.name){

                            applyStyle(node.name, highlightStyle(node));

                        }

                    }

                    if (routeNodes.length && routeState.index >= routeNodes.length - 1){

                        const finalNode = routeNodes[routeNodes.length - 1];

                        if (finalNode && finalNode.role === 'goal' && finalNode.name){

                            const base = Object.assign({}, markerStyles[finalNode.name] || {});

                            if (!base.fillColor){

                                base.fillColor = '#ffd447';

                            }

                            base.color = base.color || '#b45309';

                            applyStyle(finalNode.name, base);

                        }

                    }

                    if (refs.status.route){

                        if (!routeNodes.length){

                            refs.status.route.textContent = 'Route playback unavailable.';

                        } else if (routeState.index < 0){

                            refs.status.route.textContent = 'Ready - ' + routeNodes.length + ' stop(s)';

                        } else {

                            const node = routeNodes[routeState.index];

                            const label = node && node.label ? node.label : 'Unknown';

                            refs.status.route.textContent = 'Stop ' + (routeState.index + 1) + '/' + routeNodes.length + ': ' + label;

                        }

                    }

                    if (refs.progress.route){

                        const pct = routeState.index < 0 || !routeNodes.length ? 0 : ((routeState.index + 1) / routeNodes.length) * 100;

                        refs.progress.route.style.width = Math.min(100, pct) + '%';

                    }

                }



                function highlightNode(id, opts){

                    const markerName = markerLookup[String(id)];

                    if (!markerName) return;

                    const base = Object.assign({}, markerStyles[markerName] || {});

                    Object.assign(base, opts || {});

                    applyStyle(markerName, base);

                }



                function applyExploredStyles(limit){

                    if (limit === undefined || limit === null || limit < 0) return;

                    const visited = new Set();

                    for (let i = 0; i <= limit && i < searchSteps.length; i++){

                        const step = searchSteps[i];

                        if (step && (step.action === 'expand' || step.action === 'goal_found')){

                            visited.add(step.node_id);

                        }

                    }

                    visited.forEach(id => {

                        highlightNode(id, {

                            color: '#3730a3',

                            fillColor: '#c7d2fe',

                            fillOpacity: 0.85,

                            opacity: 1,

                            radius: 9,

                            weight: 2

                        });

                    });

                }



                function paintSearch(step){

                    if (!step) return;

                    const path = Array.isArray(step.path) ? step.path : [];

                    path.forEach(id => highlightNode(id, {

                        color: '#818cf8',

                        fillColor: '#c7d2fe',

                        fillOpacity: 0.95,

                        opacity: 1

                    }));

                    if (step.action === 'expand' || step.action === 'goal_found'){

                        highlightNode(step.node_id, {

                            color: step.action === 'goal_found' ? '#16a34a' : '#f97316',

                            fillColor: step.action === 'goal_found' ? '#86efac' : '#fed7aa',

                            radius: 11,

                            weight: 3,

                            fillOpacity: 1

                        });

                    } else if (step.action === 'add_to_frontier'){

                        highlightNode(step.parent_id, {

                            color: '#ec4899',

                            fillColor: '#fdf2f8',

                            radius: 10,

                            weight: 3,

                            fillOpacity: 1

                        });

                        (step.children_ids || []).forEach(id => {

                            highlightNode(id, {

                                color: '#0ea5e9',

                                fillColor: '#bae6fd',

                                radius: 9,

                                weight: 2,

                                fillOpacity: 1

                            });

                        });

                    }

                }



                function renderSearch(){

                    resetNodes();

                    const step = searchState.index >= 0 ? searchSteps[searchState.index] : null;

                    if (searchSteps.length){

                        applyExploredStyles(searchState.index);

                        paintSearch(step);

                    }

                    if (refs.status.search){

                        if (!searchSteps.length){

                            refs.status.search.textContent = 'Search diagnostics unavailable.';

                        } else if (searchState.index < 0){

                            refs.status.search.textContent = 'Ready - ' + searchSteps.length + ' recorded step(s)';

                        } else {

                            refs.status.search.textContent = 'Step ' + (searchState.index + 1) + '/' + searchSteps.length;

                        }

                    }

                    if (refs.progress.search){

                        const pct = searchState.index < 0 || !searchSteps.length ? 0 : ((searchState.index + 1) / searchSteps.length) * 100;

                        refs.progress.search.style.width = Math.min(100, pct) + '%';

                    }

                    const summary = refs.info.summary;

                    const fromLine = refs.info.from;

                    const pathLine = refs.info.path;

                    const frontierLine = refs.info.frontier;

                    const exploredMetric = refs.metrics.explored;

                    const frontierMetric = refs.metrics.frontier;

                    if (!step){

                        if (summary) summary.textContent = 'Summary: No step selected';

                        if (fromLine) fromLine.textContent = 'From: -';

                        if (pathLine) pathLine.textContent = 'Path: -';

                        if (frontierLine) frontierLine.textContent = 'Frontier: -';

                        if (exploredMetric) exploredMetric.textContent = searchSteps.length ? '0' : '-';

                        if (frontierMetric) frontierMetric.textContent = '0';

                        return;

                    }

                    let summaryText = '';

                    if (step.action === 'expand'){

                        summaryText = 'Expanding ' + fmtNode(step.node_id);

                    } else if (step.action === 'add_to_frontier'){

                        summaryText = 'Adding to frontier';

                    } else if (step.action === 'goal_found'){

                        summaryText = 'Goal reached at ' + fmtNode(step.node_id);

                    } else {

                        summaryText = 'Step: ' + (step.action || 'unknown');

                    }

                    if (summary) summary.textContent = 'Summary: ' + summaryText;

                    let fromText = '-';

                    if (step.action === 'add_to_frontier'){

                        fromText = fmtNode(step.parent_id);

                    } else if (Array.isArray(step.path) && step.path.length > 1){

                        fromText = fmtNode(step.path[step.path.length - 2]);

                    }

                    if (fromLine) fromLine.textContent = 'From: ' + fromText;

                    if (pathLine) pathLine.textContent = 'Path: ' + fmtPath(step.path);

                    let frontierText = 'Frontier: -';

                    let frontierCount = 0;

                    if (step.action === 'add_to_frontier'){

                        const children = step.children_ids || [];

                        frontierCount = children.length;

                        frontierText = children.length ? ('Frontier: ' + children.map(fmtNode).join(', ')) : 'Frontier: none';

                    }

                    if (frontierLine) frontierLine.textContent = frontierText;

                    if (exploredMetric) exploredMetric.textContent = String(searchCounts[searchState.index] || 0);

                    if (frontierMetric) frontierMetric.textContent = String(frontierCount);



                    if (routeNodes.length && searchState.index >= searchSteps.length - 1){

                        setRouteIndex(routeNodes.length - 1);

                    }

                }



                function setRouteIndex(idx){

                    if (!routeNodes.length) return;

                    const capped = Math.max(-1, Math.min(idx, routeNodes.length - 1));

                    routeState.index = capped;

                    renderRoute();

                }



                function setSearchIndex(idx){

                    if (!searchSteps.length) return;

                    const capped = Math.max(-1, Math.min(idx, searchSteps.length - 1));

                    searchState.index = capped;

                    renderSearch();

                }



                function stopRouteAutoplay(){

                    routeState.playing = false;

                    if (routeState.timer){

                        clearTimeout(routeState.timer);

                        routeState.timer = null;

                    }

                    if (refs.buttons.route.play){

                        refs.buttons.route.play.textContent = routeState.index >= routeNodes.length - 1 ? 'Replay' : 'Play';

                    }

                }



                function stopSearchAutoplay(){

                    searchState.playing = false;

                    if (searchState.timer){

                        clearTimeout(searchState.timer);

                        searchState.timer = null;

                    }

                    if (refs.buttons.search.play){

                        refs.buttons.search.play.textContent = searchState.index >= searchSteps.length - 1 ? 'Replay' : 'Play';

                    }

                }



                function routeTick(){

                    if (!routeState.playing) return;

                    if (routeState.timer){

                        clearTimeout(routeState.timer);

                    }

                    routeState.timer = setTimeout(() => {

                        if (routeState.index >= routeNodes.length - 1){

                            stopRouteAutoplay();

                            return;

                        }

                        setRouteIndex(routeState.index + 1);

                        routeTick();

                    }, routeDelay);

                }



                function startRouteAutoplayFromStart(){

                    if (!routeNodes.length) return;

                    stopRouteAutoplay();

                    setRouteIndex(-1);

                    routeState.playing = true;

                    if (refs.buttons.route.play){

                        refs.buttons.route.play.textContent = 'Pause';

                    }

                    routeTick();

                }



                function searchTick(){

                    if (!searchState.playing) return;

                    if (searchState.timer){

                        clearTimeout(searchState.timer);

                    }

                    searchState.timer = setTimeout(() => {

                        if (searchState.index >= searchSteps.length - 1){

                            stopSearchAutoplay();

                            return;

                        }

                        setSearchIndex(searchState.index + 1);

                        searchTick();

                    }, searchDelay);

                }



                function ensureStyles(){

                    if (document.getElementById('rpc-styles')) return;

                    const style = document.createElement('style');

                    style.id = 'rpc-styles';

                    style.textContent = `

                        .rpc-panel{

                            position:fixed;z-index:10000;

                            background:rgba(255,255,255,0.96);border-radius:12px;

                            padding:12px 14px;box-shadow:0 15px 35px rgba(76,29,149,0.2);

                            min-width:230px;max-width:270px;border:1px solid rgba(79,70,229,0.2);

                            font-family:'Inter',system-ui,-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;

                            color:#0f172a;

                        }

                        #rpc-search-panel{top:10px;right:10px;max-width:260px;min-width:220px;transform:scale(0.92);transform-origin:top right;}

                        #rpc-route-panel{bottom:12px;right:12px;}

                        .rpc-panel .rpc-section{margin-bottom:0;}

                        .rpc-panel .rpc-title{

                            text-transform:uppercase;font-size:11px;font-weight:700;

                            letter-spacing:0.08em;color:#4338ca;margin-bottom:3px;

                        }

                        .rpc-panel .rpc-status{

                            font-size:10px;color:#475569;margin-bottom:5px;

                        }

                        .rpc-panel .rpc-progress{

                            position:relative;height:3px;background:rgba(99,102,241,0.2);

                            border-radius:999px;overflow:hidden;margin-bottom:6px;

                        }

                        .rpc-panel .rpc-progress span{

                            position:absolute;top:0;left:0;bottom:0;width:0%;

                            background:linear-gradient(90deg,#4f46e5,#a855f7);

                            transition:width 0.25s ease;

                        }

                        .rpc-panel .rpc-details{

                            font-size:11px;color:#475569;line-height:1.4;margin-bottom:8px;

                        }

                        .rpc-panel .rpc-metrics{

                            display:flex;gap:8px;margin-bottom:6px;

                        }

                        .rpc-panel .rpc-metric{

                            flex:1;background:rgba(99,102,241,0.08);border-radius:10px;padding:5px;

                        }

                        .rpc-panel .rpc-metric span{

                            display:block;font-size:9px;font-weight:600;color:#6366f1;

                        }

                        .rpc-panel .rpc-metric strong{

                            font-size:13px;color:#312e81;

                        }

                        .rpc-panel .rpc-buttons{

                            display:flex;gap:6px;margin-bottom:6px;

                        }

                        .rpc-panel button{

                            flex:1;border:none;border-radius:8px;padding:5px 7px;

                            font-size:11px;font-weight:600;cursor:pointer;

                            background:rgba(129,140,248,0.18);color:#312e81;

                        }

                        .rpc-panel button.rpc-primary{

                            background:linear-gradient(135deg,#4f46e5,#9333ea);color:#fff;

                            box-shadow:0 8px 20px rgba(59,7,100,0.25);

                        }

                        .rpc-panel button:disabled{

                            opacity:0.45;cursor:not-allowed;

                        }

                        .rpc-panel .rpc-footer{

                            display:flex;justify-content:flex-end;

                        }

                        .rpc-panel .rpc-footer button{

                            flex:0 0 auto;background:transparent;color:#7c3aed;

                            text-decoration:underline;padding:0;

                        }

                        .rpc-panel .rpc-disabled{

                            opacity:0.55;

                        }

                    `;

                    document.head.appendChild(style);

                }



                function buildPanels(){

                    ensureStyles();

                    const searchPanel = document.createElement('div');

                    searchPanel.id = 'rpc-search-panel';

                    searchPanel.className = 'rpc-panel';

                    searchPanel.innerHTML = `

                        <div class="rpc-section" data-block="search">

                            <div class="rpc-title">Search exploration</div>

                            <div class="rpc-status" data-role="search-status">Preparing...</div>

                            <div class="rpc-progress"><span data-role="search-progress"></span></div>

                            <div class="rpc-details">

                                <div data-role="summary">Summary: -</div>

                                <div data-role="from">From: -</div>

                                <div data-role="path">Path: -</div>

                                <div data-role="frontier">Frontier: -</div>

                            </div>

                            <div class="rpc-metrics">

                                <div class="rpc-metric"><span>Nodes explored</span><strong data-role="explored">0</strong></div>

                                <div class="rpc-metric"><span>Frontier size</span><strong data-role="frontier-count">0</strong></div>

                            </div>

                            <div class="rpc-buttons">

                                <button data-action="search-prev">Prev</button>

                                <button class="rpc-primary" data-action="search-play">Play</button>

                                <button data-action="search-next">Next</button>

                            </div>

                            <div class="rpc-footer"><button data-action="search-reset">Reset</button></div>

                        </div>

                    `;

                    document.body.appendChild(searchPanel);



                    const routePanel = document.createElement('div');

                    routePanel.id = 'rpc-route-panel';

                    routePanel.className = 'rpc-panel';

                    routePanel.innerHTML = `

                        <div class="rpc-section" data-block="route">

                            <div class="rpc-title">Route playback</div>

                            <div class="rpc-status" data-role="route-status">Preparing...</div>

                            <div class="rpc-progress"><span data-role="route-progress"></span></div>

                            <div class="rpc-buttons">

                                <button data-action="route-prev">Prev</button>

                                <button class="rpc-primary" data-action="route-play">Play</button>

                                <button data-action="route-next">Next</button>

                            </div>

                            <div class="rpc-footer"><button data-action="route-reset">Reset</button></div>

                        </div>

                    `;

                    document.body.appendChild(routePanel);



                    refs.status.search = searchPanel.querySelector('[data-role="search-status"]');

                    refs.progress.search = searchPanel.querySelector('[data-role="search-progress"]');

                    refs.info.summary = searchPanel.querySelector('[data-role="summary"]');

                    refs.info.from = searchPanel.querySelector('[data-role="from"]');

                    refs.info.path = searchPanel.querySelector('[data-role="path"]');

                    refs.info.frontier = searchPanel.querySelector('[data-role="frontier"]');

                    refs.metrics.explored = searchPanel.querySelector('[data-role="explored"]');

                    refs.metrics.frontier = searchPanel.querySelector('[data-role="frontier-count"]');

                    refs.buttons.search.prev = searchPanel.querySelector('[data-action="search-prev"]');

                    refs.buttons.search.next = searchPanel.querySelector('[data-action="search-next"]');

                    refs.buttons.search.play = searchPanel.querySelector('[data-action="search-play"]');

                    refs.buttons.search.reset = searchPanel.querySelector('[data-action="search-reset"]');



                    refs.status.route = routePanel.querySelector('[data-role="route-status"]');

                    refs.progress.route = routePanel.querySelector('[data-role="route-progress"]');

                    refs.buttons.route.prev = routePanel.querySelector('[data-action="route-prev"]');

                    refs.buttons.route.next = routePanel.querySelector('[data-action="route-next"]');

                    refs.buttons.route.play = routePanel.querySelector('[data-action="route-play"]');

                    refs.buttons.route.reset = routePanel.querySelector('[data-action="route-reset"]');



                    if (!searchSteps.length){

                        const block = searchPanel.querySelector('[data-block="search"]');

                        if (block) block.classList.add('rpc-disabled');

                    }

                    if (!routeNodes.length){

                        const block = routePanel.querySelector('[data-block="route"]');

                        if (block) block.classList.add('rpc-disabled');

                    }



                    if (refs.buttons.search.prev){

                        refs.buttons.search.prev.addEventListener('click', () => { stopSearchAutoplay(); setSearchIndex(searchState.index - 1); });

                    }

                    if (refs.buttons.search.next){

                        refs.buttons.search.next.addEventListener('click', () => { stopSearchAutoplay(); setSearchIndex(searchState.index + 1); });

                    }

                    if (refs.buttons.search.play){

                        refs.buttons.search.play.addEventListener('click', () => {

                            if (!searchSteps.length) return;

                            if (searchState.playing){

                                stopSearchAutoplay();

                            } else {

                                if (searchState.index >= searchSteps.length - 1){

                                    setSearchIndex(-1);

                                    if (routeNodes.length) {

                                        stopRouteAutoplay();

                                        setRouteIndex(-1);

                                    }

                                }

                                searchState.playing = true;

                                refs.buttons.search.play.textContent = 'Pause';

                                searchTick();

                            }

                        });

                    }

                    if (refs.buttons.search.reset){

                        refs.buttons.search.reset.addEventListener('click', () => {

                            stopSearchAutoplay();

                            setSearchIndex(-1);

                            if (routeNodes.length) {

                                stopRouteAutoplay();

                                setRouteIndex(-1);

                            }

                        });

                    }



                    if (refs.buttons.route.prev){

                        refs.buttons.route.prev.addEventListener('click', () => { stopRouteAutoplay(); setRouteIndex(routeState.index - 1); });

                    }

                    if (refs.buttons.route.next){

                        refs.buttons.route.next.addEventListener('click', () => { stopRouteAutoplay(); setRouteIndex(routeState.index + 1); });

                    }

                    if (refs.buttons.route.play){

                        refs.buttons.route.play.addEventListener('click', () => {

                            if (!routeNodes.length) return;

                            if (routeState.playing){

                                stopRouteAutoplay();

                            } else {

                                if (routeState.index >= routeNodes.length - 1){

                                    setRouteIndex(-1);

                                }

                                routeState.playing = true;

                                refs.buttons.route.play.textContent = 'Pause';

                                routeTick();

                            }

                        });

                    }

                    if (refs.buttons.route.reset){

                        refs.buttons.route.reset.addEventListener('click', () => {

                            stopRouteAutoplay();

                            setRouteIndex(-1);

                        });

                    }

                }



                buildPanels();

                renderRoute();

                renderSearch();

                startRouteAutoplayFromStart();

            })();

            </script>

            """
            animation_script = script_template.replace("__CONFIG__", json.dumps(config_payload))
            m.get_root().html.add_child(folium.Element(animation_script))

    # Add legend
    acc_mult = meta.get("accident_multiplier", 1)
    # Provide a custom legend so the user understands each styling cue
    legend_html = f"""

    <div style="

        position: fixed;

        bottom: 20px;

        left: 20px;

        bottom: 8px;

        left: 8px;

        z-index: 9999;

        background: rgba(255,255,255,0.93);

        padding: 10px 14px;

        border: 1px solid #333;

        border-radius: 6px;

        font-size: 12px;

        line-height: 1.5;

        box-shadow: 0 4px 12px rgba(30,30,30,0.25);

    ">

    <b>Kuching Heritage Graph</b><br>

    <span style="color:#1f6feb;font-weight:bold;">β–¬</span> Selected solution<br>

    <span style="color:#cfe8ff;font-weight:bold;">β–¬</span> Other solution paths<br>

    <span style="color:crimson;font-weight:bold;">β–¬</span> Camera road (accident x time x {acc_mult})<br>

    <span style="color:deepskyblue;font-weight:bold;">β–¬</span> Primary road<br>

    <span style="color:purple;font-weight:bold;">β–¬</span> Secondary road<br>

    <span style="color:darkblue;font-weight:bold;">β–¬</span> Tertiary road<br>

    <span style="color:slategray;font-weight:bold;">β–¬</span> Service / alley

    </div>

    """
    m.get_root().html.add_child(folium.Element(legend_html))

    inject_arrow_animation(m)
    m.save(out_html)

# ============================================================================
# FLASK APP SETUP
# ============================================================================

BASE_DIR = os.path.dirname(__file__)
MAP_DATA_DIR = os.path.join(BASE_DIR, 'algorithms')

# Load all algorithms dynamically
ALGORITHM_CONFIG = {
    'astar': ('aStar.py', 'aStar'),
    'beam': ('beam.py', 'beam_search_lds'),
    'dfs': ('dfs.py', 'dfs'),
    'gbfs': ('gbfs.py', 'gbfs'),
    'iddfs': ('iddfs.py', 'iddfs'),
    'bfs': ('bfs.py', 'bfs')
}

algorithms_impl = {}
for name, (filename, func_name) in ALGORITHM_CONFIG.items():
    try:
        # Attempt to import each algorithm strategy from the algorithms folder
        algorithms_impl[name] = load_func_from_path(
            os.path.join(MAP_DATA_DIR, filename), func_name
        )
    except Exception:
        # Missing/invalid implementations are recorded as None for graceful fallback
        algorithms_impl[name] = None

app = Flask(__name__)
app.secret_key = 'your-secret-key-here-change-in-production'
app.config['UPLOAD_FOLDER'] = 'uploads'
app.config['MAX_CONTENT_LENGTH'] = 50 * 1024 * 1024
app.config['ALLOWED_EXTENSIONS'] = {'txt', 'osm'}
app.config['SESSION_TYPE'] = 'filesystem'
app.config['SESSION_PERMANENT'] = False

os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
os.makedirs('static', exist_ok=True)


def allowed_file(filename):
    """Check if file extension is allowed"""
    # Ensure uploads only include supported text or OSM inputs
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in app.config['ALLOWED_EXTENSIONS']

# ============================================================================
# FLASK ROUTES
# ============================================================================

@app.route('/')
def index():
    return render_template('index.html')


@app.route('/test_accidents')
def test_accidents():
    """Test page for accident system"""
    return render_template('test_accidents.html')


@app.route('/get_default_nodes', methods=['GET'])
def get_default_nodes():
    """Get nodes from default map without uploading files"""
    try:
        if DEFAULT_MAP_DATA['nodes'] is None:
            return jsonify({'error': 'Default map not available'}), 404
        
        nodes = DEFAULT_MAP_DATA['nodes']
        ways = copy.deepcopy(DEFAULT_MAP_DATA['ways'])
        cameras = DEFAULT_MAP_DATA['cameras']
        meta = DEFAULT_MAP_DATA['meta']
        osm_nodes = DEFAULT_MAP_DATA['osm_nodes']
        graph = DEFAULT_MAP_DATA['graph']
        
        # Clear any previous session data and mark as using default
        session.clear()
        session['using_default_map'] = True
        session['has_uploaded_files'] = False
        session.modified = True
        
        # Return list of available nodes
        nodes_list = [{'id': nid, 'label': info['label']} for nid, info in nodes.items()]
        
        # List of ways for accident system
        ways_list = [{
            "way_id": w["way_id"],
            "from": w["from"],
            "to": w["to"],
            "road_name": w["road_name"],
            "highway_type": w["highway_type"]
        } for w in ways]
        
        # Generate base maps
        base_map_path = os.path.join('static', 'heritage_map_base.html')
        base_simple_map_path = os.path.join('static', 'heritage_map_simple_base.html')
        visualize_with_roads(nodes, ways, cameras, meta, osm_nodes, graph, base_map_path, solution_path=None)
        visualize_simple_graph(nodes, ways, cameras, meta, base_simple_map_path, solution_path=None, other_paths=None)
        
        return jsonify({
            'success': True,
            'nodes': nodes_list,
            'ways': ways_list,
            'map_url': "/static/heritage_map_base.html",
            'map_url_simple': "/static/heritage_map_simple_base.html",
            'using_default': True
        })
    except Exception as e:
        print(f"❌ Error in get_default_nodes: {e}")
        import traceback
        traceback.print_exc()
        return jsonify({'error': str(e)}), 500


@app.route('/upload_files', methods=['POST'])
def upload_files():
    """Upload files and return available nodes"""
    try:
        if 'txt_file' not in request.files or 'osm_file' not in request.files:
            return jsonify({'error': 'Both .txt and .osm files are required'}), 400
        
        txt_file = request.files['txt_file']
        osm_file = request.files['osm_file']
        algorithm = request.form.get('algorithm', 'bfs')
        
        if txt_file.filename == '' or osm_file.filename == '':
            return jsonify({'error': 'Please select both files'}), 400
        
        if not (allowed_file(txt_file.filename) and allowed_file(osm_file.filename)):
            return jsonify({'error': 'Invalid file type'}), 400
        
        # Sanitize filenames and save to the upload folder
        txt_filename = secure_filename(txt_file.filename)
        osm_filename = secure_filename(osm_file.filename)
        
        txt_path = os.path.join(app.config['UPLOAD_FOLDER'], txt_filename)
        osm_path = os.path.join(app.config['UPLOAD_FOLDER'], osm_filename)
        
        txt_file.save(txt_path)
        osm_file.save(osm_path)
        
        # Parse files and cache in session
        nodes, ways, cameras, meta = parse_map_data_file(txt_path)
        osm_nodes, graph = load_osm_graph(osm_path)
        
        # Store in global cache (survives across requests)
        import time
        UPLOADED_MAP_CACHE['nodes'] = nodes
        UPLOADED_MAP_CACHE['ways'] = copy.deepcopy(ways)
        UPLOADED_MAP_CACHE['cameras'] = cameras
        UPLOADED_MAP_CACHE['meta'] = meta
        UPLOADED_MAP_CACHE['osm_nodes'] = osm_nodes
        UPLOADED_MAP_CACHE['graph'] = graph
        UPLOADED_MAP_CACHE['txt_path'] = txt_path
        UPLOADED_MAP_CACHE['osm_path'] = osm_path
        UPLOADED_MAP_CACHE['timestamp'] = time.time()
        
        # Store paths in session for later use
        session['txt_path'] = txt_path
        session['osm_path'] = osm_path
        session['algorithm'] = algorithm
        session['using_default_map'] = False
        session['has_uploaded_files'] = True
        session['nodes_count'] = len(nodes)
        session['ways_count'] = len(ways)
        
        # Clear all previous state when new files are uploaded
        session.pop("modified_ways", None)   # RESET modified accident data
        session.pop("edge_accidents", None)  # RESET accident records
        session.pop("origin", None)          # RESET origin
        session.pop("destination", None)     # RESET destination
        session.modified = True

        # Return list of available nodes
       # Return list of available nodes
        nodes_list = [{'id': nid, 'label': info['label']} for nid, info in nodes.items()]

        # NEW: list of ways for accident system
        ways_list = [{
            "way_id": w["way_id"],
            "from": w["from"],
            "to": w["to"],
            "road_name": w["road_name"],
            "highway_type": w["highway_type"]
        } for w in ways]

        # Generate base maps (without highlighted paths) so users see the area right after upload
        base_map_path = os.path.join('static', 'heritage_map_base.html')
        base_simple_map_path = os.path.join('static', 'heritage_map_simple_base.html')
        visualize_with_roads(nodes, ways, cameras, meta, osm_nodes, graph, base_map_path, solution_path=None)
        visualize_simple_graph(nodes, ways, cameras, meta, base_simple_map_path, solution_path=None, other_paths=None)

        return jsonify({
            'success': True,
            'nodes': nodes_list,
            'ways': ways_list,  # IMPORTANT
            'map_url': "/static/heritage_map_base.html",
            'map_url_simple': "/static/heritage_map_simple_base.html"
        })

    
    except Exception as e:
        return jsonify({'error': str(e)}), 500


@app.route('/find_routes', methods=['POST'])
def find_routes():
    """Find routes with user-specified origin and destination"""
    try:
        data = request.get_json()
        # Pull the requested origin/destination and allow client to override algorithm
        origin = data.get('origin')
        destination = data.get('destination')

        algorithm = data.get('algorithm', session.get('algorithm', 'bfs'))
        
        if not origin or not destination:
            # Input validation before expensive parsing work
            return jsonify({'error': 'Origin and destination are required'}), 400
        
        # Save for later (used by accident system + ALL algorithms comparison)
        session['origin'] = origin
        session['destination'] = destination

        # Get current map data (uploaded or default)
        nodes, ways, cameras, meta, osm_nodes, graph, txt_path, osm_path = get_current_map_data()
        
        if nodes is None:
            return jsonify({'error': 'Please upload files first'}), 400
        
        # Check if accidents are applied (use global store)
        edge_accidents = GLOBAL_ACCIDENTS
        if edge_accidents:
            print(f"βœ… Route finding with {len(edge_accidents)} active accident(s)")
            for way_id, info in edge_accidents.items():
                print(f"   🚨 {info['road_name']}: {info['severity']} ({info['multiplier']}x)")
        else:
            print(f"ℹ️  Route finding with no accidents")
        
        # Build edges map for pathfinding
        edges_map = build_edges_map(ways)
        # Algorithms expect nodes mapped to coordinate tuples, not metadata dicts
        algo_nodes = {nid: (info["lat"], info["lon"]) for nid, info in nodes.items()}

        # Get the selected algorithm function
        algo_func = algorithms_impl.get(algorithm.lower())
        
        if algo_func is None:
            return jsonify({'error': f'Algorithm "{algorithm}" is not available or failed to load'}), 400
        
        # Run the selected algorithm with step tracking
        result = algo_func(algo_nodes, edges_map, origin, [destination], track=False, visualise=True)
        
        if result[0] is None or not result[2]:  # Check if goal was found and path exists
            return jsonify({'error': f'No path found using {algorithm} algorithm'}), 404
        
        exploration_steps = []
        if len(result) >= 4:
            goal_node, nodes_created, path, exploration_steps = result[0], result[1], result[2], result[3]
        else:
            goal_node, nodes_created, path = result[0], result[1], result[2]
        
        # Calculate the actual cost of the path
        def calculate_path_cost(p):
            total = 0
            for i in range(len(p) - 1):
                edge_key = (p[i], p[i + 1])
                if edge_key in edges_map:
                    total += edges_map[edge_key]["time"]
            return total
        
        total_cost = calculate_path_cost(path)
        
        # Prepare route data
        route_definitions = []
        routes = []
        found_paths = set()
        
        # Add the primary path from the selected algorithm as route 0
        route_definitions.append({'id': 0, 'path': path})
        path_str_parts = [str(nid) for nid in path]
        routes.append({
            'id': 0,
            'path': path,
            'cost': round(total_cost, 2),
            'length': len(path),
            'path_str': ' β†’ '.join(path_str_parts),
            'primary': True
        })
        found_paths.add(tuple(path))
        
        # Find alternative paths by temporarily removing edges and re-running algorithm
        alt_id = 1
        max_alternatives = 4
        edges_to_remove = []
        
        # Try to find alternatives by blocking edges from the primary path
        for i in range(len(path) - 1):
            if alt_id > max_alternatives:
                break
            
            # Create a modified edge map excluding one edge from the original path
            modified_edges = edges_map.copy()
            edge_to_block = (path[i], path[i + 1])
            
            if edge_to_block in modified_edges:
                del modified_edges[edge_to_block]
                edges_to_remove.append(edge_to_block)
                
                # Run algorithm with modified edges
                try:
                    alt_result = algo_func(algo_nodes, modified_edges, origin, [destination], track=False, visualise=False)
                    
                    if alt_result[0] is not None and alt_result[2]:
                        alt_path = alt_result[2]
                        
                        # Only add if it's a different path
                        if tuple(alt_path) not in found_paths:
                            alt_cost = calculate_path_cost(alt_path)
                            
                            route_definitions.append({'id': alt_id, 'path': alt_path})
                            path_str_parts = [str(nid) for nid in alt_path]
                            routes.append({
                                'id': alt_id,
                                'path': alt_path,
                                'cost': round(alt_cost, 2),
                                'length': len(alt_path),
                                'path_str': ' β†’ '.join(path_str_parts),
                                'primary': False
                            })
                            found_paths.add(tuple(alt_path))
                            alt_id += 1
                except Exception:
                    # If algorithm fails with modified edges, continue to next attempt
                    pass
        
        # Generate individual maps for each route
         # Generate individual maps for each route (both OSM and simplified views)
        for route_def in route_definitions:
            # Each result gets its own HTML map with the chosen path highlighted
            map_output = os.path.join('static', f'heritage_map_{route_def["id"]}.html')
            simple_output = os.path.join('static', f'heritage_map_simple_{route_def["id"]}.html')
            display_meta = {
                "start": origin,
                "goals": [destination],
                "accident_multiplier": meta.get("accident_multiplier", 1)
            }
            try:
                # Generate OSM view
                visualize_with_roads(
                    nodes, ways, cameras, display_meta, osm_nodes, graph,
                    map_output, route_def['path'], other_paths=None,
                    exploration_steps=exploration_steps
                )

                            
                # Generate simplified graph view
                visualize_simple_graph(
                    nodes, ways, cameras, display_meta,
                    simple_output, route_def['path'], other_paths=None,
                    exploration_steps=exploration_steps
                )
            except Exception as e:
                print(f"Error generating maps for route {route_def['id']}: {str(e)}")
                # Continue with other routes even if one fails

        # Sort routes by cost but keep primary route first
        # Separate primary from alternatives, sort alternatives, then recombine
        primary_route = [r for r in routes if r.get('primary', False)]
        alternative_routes = [r for r in routes if not r.get('primary', False)]
        alternative_routes.sort(key=lambda r: r['cost'])
        
        # Final route list: primary first, then sorted alternatives
        sorted_routes = primary_route + alternative_routes

        return jsonify({
            'success': True,
            'routes': sorted_routes,
            'algorithm': algorithm.upper(),
            'stats': {
                'nodes': len(nodes),
                'ways': len(ways),
                'routes_found': len(sorted_routes),
                'nodes_created': nodes_created
            }
        })
    
    except Exception as e:
        return jsonify({'error': str(e)}), 500

# ========================================================================
# ACCIDENT IMAGE CLASSIFICATION API
# ========================================================================
@app.route('/predict_accident', methods=['POST'])
def predict_accident():
    """Classify accident image severity using AI model"""
    model_name = request.form.get("model", "resnet")

    # Select model
    if model_name == "mobilenet":
        model = mobilenet_model
    elif model_name == "resnet":
        model = resnet_model
    elif model_name == "efficientnet":
        if efficientnet_model is None:
            return jsonify({"success": False, "error": "EfficientNet model not available"})
        model = efficientnet_model
    else:
        return jsonify({"success": False, "error": "Invalid model"}), 400

    # Load image
    if "image" not in request.files:
        return jsonify({"success": False, "error": "No image uploaded"}), 400
        
    img_file = request.files["image"]
    img = Image.open(img_file).convert("RGB")

    # Preprocess
    x = accident_transform(img).unsqueeze(0)

    # Predict
    with torch.no_grad():
        logits = model(x)
        probs = torch.softmax(logits, dim=1)

    confidence, label_idx = torch.max(probs, dim=1)
    CLASS_NAMES = ["none", "minor", "moderate", "severe"]
    predicted_severity = CLASS_NAMES[int(label_idx.item())]
    confidence_val = float(confidence.item())
    
    # Get all probabilities for each class
    all_probs = {
        CLASS_NAMES[i]: float(probs[0][i].item())
        for i in range(len(CLASS_NAMES))
    }

    return jsonify({
        "success": True,
        "label": predicted_severity,
        "confidence": confidence_val,
        "all_probabilities": all_probs
    })


@app.route('/reset_accident', methods=['POST'])
def reset_accident():
    """Remove accident impact and revert to original travel times"""
    try:
        # Clear global accidents
        GLOBAL_ACCIDENTS.clear()
        print("βœ… Cleared all accidents from GLOBAL_ACCIDENTS")
        
        # Clear session
        session.pop("edge_accidents", None)
        session.pop("modified_ways", None)
        session.pop("default_map_modified_ways", None)
        session.modified = True
        
        # Reset UPLOADED cache ways to original
        if UPLOADED_MAP_CACHE['txt_path'] and os.path.exists(UPLOADED_MAP_CACHE['txt_path']):
            _, original_ways, _, _ = parse_map_data_file(UPLOADED_MAP_CACHE['txt_path'])
            UPLOADED_MAP_CACHE['ways'] = original_ways
            print("βœ… Reset UPLOADED_MAP_CACHE ways to original")
        
        # Reset DEFAULT map ways to original
        if DEFAULT_MAP_DATA['txt_path'] and os.path.exists(DEFAULT_MAP_DATA['txt_path']):
            _, original_ways, _, _ = parse_map_data_file(DEFAULT_MAP_DATA['txt_path'])
            DEFAULT_MAP_DATA['ways'] = original_ways
            print("βœ… Reset DEFAULT_MAP_DATA ways to original")
        
        return jsonify({"success": True})
    except Exception as e:
        return jsonify({"success": False, "error": str(e)}), 500


@app.route('/clear_cache', methods=['POST'])
def clear_cache():
    """Clear uploaded map cache and reset session"""
    try:
        # Clear uploaded cache
        for key in UPLOADED_MAP_CACHE:
            UPLOADED_MAP_CACHE[key] = None
        
        # Clear global accidents
        GLOBAL_ACCIDENTS.clear()
        
        # Clear session
        session.clear()
        
        return jsonify({"success": True})
    except Exception as e:
        return jsonify({"success": False, "error": str(e)}), 500


@app.route('/debug_session', methods=['GET'])
def debug_session():
    """Debug endpoint to check session and cache state"""
    global_accidents_list = []
    for road_id, info in GLOBAL_ACCIDENTS.items():
        global_accidents_list.append({
            "road_id": road_id,
            "road_name": info.get("road_name", "Unknown"),
            "severity": info.get("severity", "unknown"),
            "multiplier": info.get("multiplier", 1.0)
        })
    
    return jsonify({
        "session": dict(session),
        "global_accidents": dict(GLOBAL_ACCIDENTS),
        "global_accidents_count": len(GLOBAL_ACCIDENTS),
        "global_accidents_list": global_accidents_list,
        "has_uploaded_cache": UPLOADED_MAP_CACHE['nodes'] is not None,
        "has_default_map": DEFAULT_MAP_DATA['nodes'] is not None,
        "uploaded_cache_timestamp": UPLOADED_MAP_CACHE.get('timestamp'),
        "uploaded_cache_txt_path": UPLOADED_MAP_CACHE.get('txt_path'),
        "default_map_txt_path": DEFAULT_MAP_DATA.get('txt_path')
    })


@app.route('/remove_accident', methods=['POST'])
def remove_accident():
    """Remove a specific accident from a road"""
    try:
        data = request.get_json()
        road_id = data.get("road_id")
        
        if not road_id:
            return jsonify({"success": False, "error": "Missing road_id"}), 400
        
        # Use string key for consistency
        road_id_str = str(road_id)
        
        # Check global accidents store
        if road_id_str not in GLOBAL_ACCIDENTS:
            return jsonify({"success": False, "error": f"No accident found for road {road_id_str}"}), 400
        
        # Remove the accident from global store
        removed_info = GLOBAL_ACCIDENTS.pop(road_id_str)
        print(f"πŸ—‘οΈ  Removing accident from road {road_id_str}: {removed_info['road_name']}")
        print(f"   Remaining accidents in GLOBAL_ACCIDENTS: {len(GLOBAL_ACCIDENTS)}")
        
        # Update session
        session["edge_accidents"] = dict(GLOBAL_ACCIDENTS)
        session.modified = True
        
        # Get fresh copy of original ways by re-parsing the file
        import copy
        using_uploaded = False
        using_default = False
        
        if UPLOADED_MAP_CACHE['nodes'] is not None:
            # Get original ways from file (not cache)
            original_txt = UPLOADED_MAP_CACHE['txt_path']
            nodes, ways, cameras, meta = parse_map_data_file(original_txt)
            osm_nodes = UPLOADED_MAP_CACHE['osm_nodes']
            graph = UPLOADED_MAP_CACHE['graph']
            txt_path = UPLOADED_MAP_CACHE['txt_path']
            osm_path = UPLOADED_MAP_CACHE['osm_path']
            using_uploaded = True
        elif DEFAULT_MAP_DATA['nodes'] is not None:
            # Get original ways from file (not cache)
            original_txt = DEFAULT_MAP_DATA['txt_path']
            nodes, ways, cameras, meta = parse_map_data_file(original_txt)
            osm_nodes = DEFAULT_MAP_DATA['osm_nodes']
            graph = DEFAULT_MAP_DATA['graph']
            txt_path = DEFAULT_MAP_DATA['txt_path']
            osm_path = DEFAULT_MAP_DATA['osm_path']
            using_default = True
        else:
            return jsonify({"success": False, "error": "No map data available"}), 400
        
        print(f"πŸ”„ Rebuilding ways after removing accident from road {road_id}")
        
        # Initialize original times
        for w in ways:
            if "original_time" not in w:
                w["original_time"] = w["time_min"]
        
        # Reapply remaining accidents from GLOBAL_ACCIDENTS
        print(f"\nπŸ”§ Reapplying {len(GLOBAL_ACCIDENTS)} remaining accident(s)...")
        for way_id, accident_info in GLOBAL_ACCIDENTS.items():
            multiplier = accident_info["multiplier"]
            found = False
            for w in ways:
                if str(w["way_id"]) == str(way_id):
                    w["time_min"] = w["original_time"] * multiplier
                    w["accident"] = True
                    w["severity"] = accident_info["severity"]
                    found = True
                    print(f"βœ… Reapplied {accident_info['severity']} ({multiplier}x) to way {way_id}: {w.get('road_name', 'Unknown')}")
                    break
            if not found:
                print(f"⚠️  Way {way_id} not found during reapplication")
        
        # Update cache and session
        if GLOBAL_ACCIDENTS:
            session["modified_ways"] = ways
            if using_uploaded:
                UPLOADED_MAP_CACHE['ways'] = copy.deepcopy(ways)
                print("βœ… Updated UPLOADED_MAP_CACHE with remaining accidents")
            elif using_default:
                DEFAULT_MAP_DATA['ways'] = copy.deepcopy(ways)
                print("βœ… Updated DEFAULT_MAP_DATA with remaining accidents")
        else:
            # No accidents left - clear everything and restore original ways
            session.pop("modified_ways", None)
            session.pop("default_map_modified_ways", None)
            if using_uploaded:
                # Reload original ways
                _, original_ways, _, _ = parse_map_data_file(UPLOADED_MAP_CACHE['txt_path'])
                UPLOADED_MAP_CACHE['ways'] = original_ways
                print("βœ… Reset UPLOADED_MAP_CACHE to original (no accidents)")
            elif using_default:
                # Reload original ways
                _, original_ways, _, _ = parse_map_data_file(DEFAULT_MAP_DATA['txt_path'])
                DEFAULT_MAP_DATA['ways'] = original_ways
                print("βœ… Reset DEFAULT_MAP_DATA to original (no accidents)")
        session.modified = True
        
        # Always regenerate map to show current state (with or without remaining accidents)
        accident_map_output = os.path.join('static', 'heritage_map_accidents.html')
        accident_map_simple = os.path.join('static', 'heritage_map_simple_accidents.html')
        
        try:
            # Use the ways we just rebuilt (with accidents cleared)
            visualize_with_roads(
                nodes, ways, cameras,
                {"start": None, "goals": []},
                osm_nodes, graph,
                accident_map_output,
                solution_path=None,
                exploration_steps=[]
            )
            
            visualize_simple_graph(
                nodes, ways, cameras,
                {"start": None, "goals": []},
                accident_map_simple,
                solution_path=None,
                other_paths=None,
                exploration_steps=[]
            )
            print(f"βœ… Regenerated map with {len(GLOBAL_ACCIDENTS)} remaining accident(s)")
        except Exception as e:
            print(f"⚠️ Error regenerating accident map: {str(e)}")
        
        # Return updated accident list from global store
        all_accidents = {}
        for way_id, accident_info in GLOBAL_ACCIDENTS.items():
            all_accidents[way_id] = {
                "road_name": accident_info["road_name"],
                "severity": accident_info["severity"],
                "from_node": accident_info.get("from_node", "?"),
                "to_node": accident_info.get("to_node", "?")
            }
        
        import time
        timestamp = int(time.time())
        
        return jsonify({
            "success": True,
            "removed_road": removed_info["road_name"],
            "accidents": all_accidents,
            "map_url": f"/static/heritage_map_accidents.html?t={timestamp}",
            "has_accidents": len(GLOBAL_ACCIDENTS) > 0
        })
        
    except Exception as e:
        print(f"❌ Error removing accident: {str(e)}")
        import traceback
        traceback.print_exc()
        return jsonify({"success": False, "error": str(e)}), 500

# ========================================================================
# APPLY ACCIDENT IMPACT TO SPECIFIC EDGES IN ROUTES
# ========================================================================
@app.route('/apply_accident', methods=['POST'])
def apply_accident():
    """

    Apply accident severity multiplier to a specific way (road).

    Stores accidents in session for later route calculation.

    Supports multiple accidents on different roads.

    """
    try:
        print("\nπŸ”₯ APPLY ACCIDENT TO WAY")
        
        # Get road_id and severity from request
        data = request.get_json()
        road_id = data.get("road_id")
        severity = data.get("severity")
        
        if not road_id or not severity:
            return jsonify({"success": False, "error": "Missing road_id or severity"}), 400

        # --- LOAD DATA ---
        nodes, ways, cameras, meta, osm_nodes_data, graph_data, txt_path, osm_path = get_current_map_data()
        
        if nodes is None:
            print("❌ No map data available!")
            return jsonify({"success": False, "error": "No map data available. Please upload map files or refresh the page."}), 400
        
        # Use global accident store (persists across all requests)
        edge_accidents = GLOBAL_ACCIDENTS
        
        # Check if this road already has an accident
        is_override = str(road_id) in edge_accidents
        
        # Get road name and nodes for response
        road_name = "Unknown"
        from_node = "?"
        to_node = "?"
        for w in ways:
            if str(w["way_id"]) == str(road_id):
                road_name = w.get("road_name", "Unknown")
                from_node = w.get("from", "?")
                to_node = w.get("to", "?")
                break
        
        # Store this accident for the road (way_id) - use string key for consistency
        GLOBAL_ACCIDENTS[str(road_id)] = {
            "severity": severity,
            "multiplier": SEVERITY_MULTIPLIERS.get(severity.lower(), 1.0),
            "road_name": road_name,
            "from_node": from_node,
            "to_node": to_node
        }
        
        # Also update session for backwards compatibility
        session["edge_accidents"] = dict(GLOBAL_ACCIDENTS)
        session.modified = True
        
        print(f"βœ… {'Overridden' if is_override else 'Applied'} accident: {road_id} ({road_name}) = {severity}")
        print(f"   Total accidents in GLOBAL_ACCIDENTS: {len(GLOBAL_ACCIDENTS)}")
        print(f"   All accidents: {list(GLOBAL_ACCIDENTS.keys())}")
        
        print(f"βœ… {'Overridden' if is_override else 'Applied'} accident: {road_id} ({road_name}) = {severity} (multiplier: {edge_accidents[road_id]['multiplier']})")
        
        # ==========================================================
        # Apply accidents to ways for later route calculation
        # ==========================================================
        for w in ways:
            # Store original time if not already stored
            if "original_time" not in w:
                w["original_time"] = w["time_min"]
            
            # Reset to original
            w["time_min"] = w["original_time"]
            w["accident"] = False
        
        # Apply accidents to specific ways (roads)
        affected_ways = []
        print(f"\nπŸ”§ Applying {len(edge_accidents)} accident(s) to ways...")
        for way_id, accident_info in edge_accidents.items():
            multiplier = accident_info["multiplier"]
            found = False
            
            for w in ways:
                # Check if this is the affected way (compare as strings)
                if str(w["way_id"]) == str(way_id):
                    original_time = w["original_time"]
                    new_time = original_time * multiplier
                    w["time_min"] = new_time
                    w["accident"] = True
                    w["severity"] = accident_info["severity"]
                    affected_ways.append(way_id)
                    found = True
                    print(f"🚨 Applied {accident_info['severity']} ({multiplier}x) to way {way_id}: {w.get('road_name', 'Unknown')}")
                    print(f"   ⏱️  {original_time:.2f} min β†’ {new_time:.2f} min")
                    break
            
            if not found:
                print(f"⚠️  Way {way_id} not found in ways list!")
        
        # Store modified ways in BOTH session AND cache
        session["modified_ways"] = ways
        session.modified = True
        
        # Update the cache with modified ways so all routes see the accidents
        if UPLOADED_MAP_CACHE['nodes'] is not None:
            import copy
            UPLOADED_MAP_CACHE['ways'] = copy.deepcopy(ways)
            print(f"βœ… Updated UPLOADED_MAP_CACHE with accidents")
        elif DEFAULT_MAP_DATA['nodes'] is not None:
            # For default map, update the DEFAULT_MAP_DATA directly
            import copy
            DEFAULT_MAP_DATA['ways'] = copy.deepcopy(ways)
            print(f"βœ… Updated DEFAULT_MAP_DATA with accidents")
        
        print(f"πŸ“¦ Total accidents stored: {len(edge_accidents)}")
        
        # ==========================================================
        # Generate accident visualization map immediately
        # ==========================================================
        osm_nodes = osm_nodes_data
        graph = graph_data
        accident_map_output = os.path.join('static', 'heritage_map_accidents.html')
        accident_map_simple = os.path.join('static', 'heritage_map_simple_accidents.html')
        
        try:
            # Create detailed map with accident roads highlighted
            visualize_with_roads(
                nodes, ways, cameras,
                {"start": None, "goals": []},
                osm_nodes, graph,
                accident_map_output,
                solution_path=None,
                exploration_steps=[]
            )
            
            # Create simple map with accident roads highlighted
            visualize_simple_graph(
                nodes, ways, cameras,
                {"start": None, "goals": []},
                accident_map_simple,
                solution_path=None,
                other_paths=None,
                exploration_steps=[]
            )
            print(f"βœ… Generated accident visualization maps")
        except Exception as e:
            print(f"⚠️ Error generating accident maps: {str(e)}")
            import traceback
            traceback.print_exc()
        
        # ==========================================================
        # Return all accidents for frontend to display
        # ==========================================================
        all_accidents = {}
        for way_id, accident_info in GLOBAL_ACCIDENTS.items():
            all_accidents[way_id] = {
                "road_name": accident_info["road_name"],
                "severity": accident_info["severity"],
                "from_node": accident_info.get("from_node", "?"),
                "to_node": accident_info.get("to_node", "?")
            }
        
        return jsonify({
            "success": True,
            "road_id": road_id,
            "road_name": road_name,
            "severity": severity,
            "is_override": is_override,
            "accidents": all_accidents,
            "map_url": "/static/heritage_map_accidents.html",
            "map_simple_url": "/static/heritage_map_simple_accidents.html"
        })
    
    except Exception as e:
        print(f"❌ Error in apply_accident: {str(e)}")
        import traceback
        traceback.print_exc()
        return jsonify({
            "success": False,
            "error": f"Server error: {str(e)}"
        }), 500


# ========================================================================
# ALL ALGORITHMS COMPARISON (WITH EDGE ACCIDENT SUPPORT)
# ========================================================================
@app.route('/find_all_algorithms', methods=['POST'])
def find_all_algorithms():
    """Compare all algorithms with current edge accident conditions"""
    
    # Try to get from request body first, fallback to session
    data = request.get_json() or {}
    origin = data.get("origin") or session.get("origin")
    destination = data.get("destination") or session.get("destination")

    print("STEP 4 ORIGIN =", origin)
    print("STEP 4 DESTINATION =", destination)

    if not origin or not destination:
        return jsonify({"success": True, "routes": []})

    nodes, ways, cameras, meta, osm_nodes, graph, txt_path, osm_path = get_current_map_data()
    
    if nodes is None:
        return jsonify({"success": False, "error": "No map data available"}), 400
    
    # If modified ways exist (accident applied), use them
    if "modified_ways" in session:
        ways = session["modified_ways"]
        print(f"βœ… Using modified ways with {len(GLOBAL_ACCIDENTS)} accidents applied")
    edges_map = build_edges_map(ways)

    algo_nodes = {nid: (info["lat"], info["lon"]) for nid, info in nodes.items()}

    results = []

    for algo_name, func in algorithms_impl.items():

        if func is None:
            continue
        
        try:
            # Run algorithm with tracking so the exploration panel can be used
            result = func(algo_nodes, edges_map, origin, [destination],
                          track=True, visualise=True)

            if result is None or len(result) < 3:
                continue

            path = result[2]
            exploration_steps = result[3] if len(result) >= 4 else []
            if not path:
                continue

            total_cost = 0
            for i in range(len(path) - 1):
                key = (path[i], path[i + 1])
                if key in edges_map:
                    total_cost += edges_map[key]["time"]

            # Save each algorithm map
            out_html = f"static/algomap_{algo_name}.html"
            simple_out_html = f"static/algomap_simple_{algo_name}.html"

            visualize_with_roads(
                nodes, ways, cameras,
                {"start": origin, "goals": [destination],
                 "accident_multiplier": meta.get("accident_multiplier", 1)},
                osm_nodes, graph,
                out_html,
                solution_path=path,
                exploration_steps=exploration_steps
            )

            visualize_simple_graph(
                nodes, ways, cameras,
                {"start": origin, "goals": [destination],
                 "accident_multiplier": meta.get("accident_multiplier", 1)},
                simple_out_html,
                solution_path=path,
                other_paths=None,
                exploration_steps=exploration_steps
            )

            results.append({
                "algorithm": algo_name.upper(),
                "path": path,
                "cost": round(total_cost, 2),
                "length": len(path),
                "path_str": " β†’ ".join(path),
                "map_url": f"/static/algomap_{algo_name}.html",
                "map_url_simple": f"/static/algomap_simple_{algo_name}.html"
            })

        except Exception as e:
            print("ERROR in algo", algo_name, ":", e)
            continue

    return jsonify({"success": True, "routes": results})



# ========================================================================
# CLEAR ACCIDENT STATE (FOR NEW ROUTE SELECTION)
# ========================================================================
@app.route('/clear_route_state', methods=['POST'])
def clear_route_state():
    """Clear accidents and modified ways when selecting new origin/destination"""
    try:
        session.pop("edge_accidents", None)
        session.pop("modified_ways", None)
        session.modified = True
        return jsonify({"success": True})
    except Exception as e:
        return jsonify({"success": False, "error": str(e)}), 500


if __name__ == '__main__':
    # Load default map data on startup (for Hugging Face deployment)
    load_default_map_data()
    
    # Get port from environment variable (Hugging Face uses 7860)
    port = int(os.environ.get('PORT', 7860))
    
    # Check if running in production (Hugging Face Spaces)
    is_production = os.environ.get('SPACE_ID') is not None
    
    if not is_production:
        # Only open browser in local development
        import threading
        import webbrowser
        import time

        def _open_browser_after_delay(url, delay=1.0):
            try:
                time.sleep(delay)
                webbrowser.open_new(url)
            except Exception:
                pass

        url = f'http://127.0.0.1:{port}/'
        threading.Thread(target=_open_browser_after_delay, args=(url, 1.0), daemon=True).start()

    # Run Flask - debug mode off in production
    app.run(debug=not is_production, host='0.0.0.0', port=port, use_reloader=False)