Spaces:
Runtime error

File size: 89,094 Bytes
557e1cc
 
 
 
 
 
 
 
 
 
 
 
 
 
62d94ac
557e1cc
 
75ba483
affc7df
557e1cc
 
798714d
 
 
 
 
 
557e1cc
798714d
557e1cc
 
798714d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
557e1cc
 
798714d
 
557e1cc
798714d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
557e1cc
 
75ba483
801771f
557e1cc
 
affc7df
 
557e1cc
affc7df
557e1cc
75ba483
801771f
 
 
 
75ba483
801771f
 
75ba483
801771f
 
 
 
d4a7cc9
801771f
 
 
 
 
 
d4a7cc9
801771f
 
 
 
d4a7cc9
801771f
 
 
75ba483
557e1cc
 
801771f
 
75ba483
801771f
75ba483
801771f
557e1cc
801771f
62d94ac
557e1cc
affc7df
 
557e1cc
 
 
 
 
62d94ac
801771f
 
75ba483
 
801771f
 
 
 
 
 
 
557e1cc
801771f
557e1cc
75ba483
801771f
 
 
 
 
 
75ba483
801771f
8be8b8a
62d94ac
8be8b8a
 
 
62d94ac
 
75ba483
801771f
 
62d94ac
 
affc7df
 
 
 
62d94ac
 
affc7df
fe3ba6b
d1d9e27
62d94ac
affc7df
fe3ba6b
 
 
 
 
 
 
 
 
62d94ac
fe3ba6b
 
 
62d94ac
 
 
75ba483
801771f
75ba483
801771f
 
62d94ac
 
 
75ba483
801771f
 
affc7df
62d94ac
 
75ba483
801771f
 
fe3ba6b
 
 
 
 
 
75ba483
801771f
affc7df
 
 
75ba483
801771f
d1d9e27
affc7df
 
02716b8
 
 
 
affc7df
 
75ba483
801771f
affc7df
557e1cc
 
 
 
801771f
557e1cc
801771f
557e1cc
75ba483
801771f
 
c9ca664
affc7df
 
557e1cc
affc7df
fe3ba6b
affc7df
557e1cc
affc7df
801771f
affc7df
 
801771f
affc7df
75ba483
801771f
557e1cc
 
affc7df
801771f
 
557e1cc
fe3ba6b
557e1cc
801771f
affc7df
557e1cc
affc7df
 
62d94ac
801771f
affc7df
 
801771f
 
affc7df
fe3ba6b
 
 
 
02716b8
8be8b8a
affc7df
 
 
801771f
 
 
fe3ba6b
affc7df
 
fe3ba6b
 
 
affc7df
 
 
 
801771f
affc7df
 
 
801771f
affc7df
75ba483
801771f
557e1cc
 
affc7df
 
801771f
 
557e1cc
fe3ba6b
557e1cc
801771f
affc7df
557e1cc
affc7df
557e1cc
affc7df
 
 
801771f
affc7df
801771f
557e1cc
 
affc7df
 
801771f
 
 
affc7df
d1d9e27
affc7df
d1d9e27
affc7df
 
801771f
 
557e1cc
8be8b8a
d1d9e27
092e74d
dfca50b
 
 
 
 
 
fe3ba6b
 
affc7df
fe3ba6b
 
 
 
d1d9e27
affc7df
 
 
 
801771f
affc7df
 
 
801771f
affc7df
75ba483
8be8b8a
 
 
75ba483
801771f
affc7df
 
 
fe3ba6b
75ba483
8be8b8a
 
 
 
 
 
 
 
 
75ba483
801771f
fe3ba6b
 
 
801771f
8be8b8a
fe3ba6b
 
 
 
 
 
8be8b8a
 
 
 
 
fe3ba6b
 
 
8be8b8a
fe3ba6b
 
 
 
 
 
 
 
 
801771f
fe3ba6b
 
801771f
 
fe3ba6b
 
8be8b8a
fe3ba6b
 
 
 
 
8be8b8a
 
 
 
 
 
 
fe3ba6b
 
 
 
 
 
 
801771f
fe3ba6b
8be8b8a
 
 
 
 
fe3ba6b
 
 
8be8b8a
 
 
 
 
 
fe3ba6b
 
75ba483
801771f
fe3ba6b
 
 
 
 
 
 
 
 
 
d1d9e27
 
 
 
fe3ba6b
 
 
 
 
75ba483
801771f
fe3ba6b
 
 
 
 
 
 
 
 
 
801771f
fe3ba6b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
801771f
fe3ba6b
 
 
 
 
 
 
 
801771f
75ba483
8be8b8a
 
 
 
 
 
 
 
 
75ba483
801771f
affc7df
8be8b8a
 
affc7df
8be8b8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
affc7df
75ba483
801771f
affc7df
 
 
 
 
 
75ba483
f8922d7
75ba483
f8922d7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75ba483
f8922d7
 
 
 
 
 
 
 
 
 
 
 
75ba483
affc7df
801771f
75ba483
801771f
 
 
 
 
75ba483
801771f
 
557e1cc
801771f
02716b8
 
 
 
 
affc7df
75ba483
affc7df
 
 
 
801771f
affc7df
 
 
 
 
fe3ba6b
affc7df
fe3ba6b
affc7df
 
 
02716b8
fe3ba6b
801771f
fe3ba6b
 
 
 
801771f
fe3ba6b
801771f
fe3ba6b
affc7df
 
 
fe3ba6b
dfca50b
2f115f4
801771f
2f115f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dfca50b
2f115f4
 
dfca50b
 
2f115f4
 
 
801771f
dfca50b
801771f
dfca50b
 
 
 
 
801771f
2f115f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
801771f
dfca50b
 
 
2f115f4
 
fe3ba6b
801771f
fe3ba6b
 
 
 
affc7df
75ba483
fe3ba6b
 
 
 
 
 
801771f
fe3ba6b
 
 
 
 
 
801771f
fe3ba6b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75ba483
affc7df
 
fe3ba6b
affc7df
801771f
affc7df
 
 
 
 
 
 
 
fe3ba6b
affc7df
 
2994e74
801771f
fe3ba6b
 
 
 
 
 
 
 
 
801771f
affc7df
 
fe3ba6b
7cb12fd
fe3ba6b
 
 
 
 
 
 
801771f
fe3ba6b
affc7df
fe3ba6b
affc7df
d1d9e27
2994e74
50ed0f2
 
2994e74
801771f
 
2994e74
 
 
02716b8
fe3ba6b
 
2994e74
02716b8
affc7df
801771f
affc7df
fe3ba6b
 
 
affc7df
fe3ba6b
affc7df
801771f
affc7df
fe3ba6b
801771f
 
 
affc7df
 
02716b8
fe3ba6b
801771f
9e35c8d
fe3ba6b
affc7df
801771f
 
fe3ba6b
801771f
fe3ba6b
801771f
fe3ba6b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
801771f
fe3ba6b
 
 
 
 
 
 
 
 
 
 
 
 
801771f
affc7df
801771f
fe3ba6b
9e35c8d
801771f
 
 
 
fe3ba6b
8588058
d4a7cc9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75ba483
d4a7cc9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
801771f
2994e74
801771f
fe3ba6b
2994e74
801771f
fe3ba6b
 
 
801771f
affc7df
 
801771f
 
fe3ba6b
801771f
fe3ba6b
 
 
 
affc7df
 
 
801771f
affc7df
801771f
affc7df
 
 
801771f
fe3ba6b
801771f
fe3ba6b
801771f
fe3ba6b
801771f
 
fe3ba6b
801771f
fe3ba6b
801771f
fe3ba6b
 
affc7df
 
801771f
affc7df
801771f
 
fe3ba6b
 
801771f
d1d9e27
801771f
 
fe3ba6b
d1d9e27
f59276b
801771f
fe3ba6b
801771f
fe3ba6b
 
801771f
dfca50b
fe3ba6b
 
f59276b
801771f
affc7df
 
fe3ba6b
affc7df
801771f
 
fe3ba6b
 
 
801771f
d4a7cc9
 
 
 
 
 
 
 
 
 
 
 
 
801771f
 
 
 
 
affc7df
d1d9e27
798714d
 
 
 
 
06a7f31
798714d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d4a7cc9
 
798714d
 
 
 
 
 
 
 
 
d4a7cc9
 
 
 
 
 
 
798714d
 
 
 
 
 
 
 
 
 
 
d4a7cc9
 
798714d
75ba483
798714d
 
 
 
 
 
 
 
 
 
 
 
affc7df
 
798714d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d4a7cc9
798714d
 
 
 
 
 
d4a7cc9
798714d
 
d4a7cc9
 
 
 
 
 
 
 
 
798714d
 
 
 
 
 
 
d4a7cc9
798714d
 
 
 
d4a7cc9
798714d
d4a7cc9
798714d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d4a7cc9
798714d
 
 
 
d4a7cc9
798714d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d4a7cc9
798714d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d4a7cc9
798714d
 
 
 
 
 
 
 
 
 
 
 
 
affc7df
798714d
affc7df
 
02716b8
affc7df
 
 
 
 
 
 
801771f
fe3ba6b
 
 
affc7df
02716b8
801771f
affc7df
fe3ba6b
 
affc7df
801771f
fe3ba6b
 
 
 
 
 
 
 
affc7df
fe3ba6b
affc7df
75ba483
d4a7cc9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f8922d7
 
 
 
 
 
 
 
 
 
75ba483
 
f8922d7
 
75ba483
d4a7cc9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
01e14ab
d4a7cc9
 
 
 
 
 
 
0cae729
 
d4a7cc9
0cae729
 
 
d4a7cc9
 
 
 
 
 
 
 
 
 
0cae729
 
 
 
 
d4a7cc9
0cae729
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d4a7cc9
0cae729
 
d4a7cc9
0cae729
 
 
 
 
 
 
d4a7cc9
0cae729
75ba483
 
 
 
 
 
 
 
 
 
 
0cae729
d4a7cc9
0cae729
 
 
 
 
d4a7cc9
 
0cae729
 
 
 
 
d4a7cc9
0cae729
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d4a7cc9
0cae729
 
 
 
 
 
 
 
 
 
d4a7cc9
0cae729
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d4a7cc9
0cae729
 
 
 
 
 
 
d4a7cc9
0cae729
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d4a7cc9
0cae729
75ba483
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
import streamlit as st
import pandas as pd
import numpy as np
import io
import re
import math
import time
import json
import os
import requests
import pydeck as pdk
import openpyxl
import difflib
import datetime
import sqlite3
from ortools.constraint_solver import routing_enums_pb2
from ortools.constraint_solver import pywrapcp

st.set_page_config(page_title="Repsly Enterprise Command Center", page_icon="⚑", layout="wide")
st.markdown("""
    <style>
    @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');
    .stApp { background-color: #F8F9FC; font-family: 'Inter', sans-serif; }
    h1 { color: #1A1F36 !important; font-weight: 700 !important; letter-spacing: -0.5px; }
    h2 { color: #2D3748 !important; font-weight: 600 !important; }
    h3 { color: #4A5568 !important; font-weight: 600 !important; }
    /* Primary buttons */
    div.stButton > button:first-child {
        background: linear-gradient(135deg, #3B82F6 0%, #2563EB 100%) !important;
        color: white !important;
        border: none !important;
        border-radius: 10px;
        font-weight: 600;
        font-size: 0.9rem;
        padding: 0.5rem 1.2rem;
        box-shadow: 0 4px 12px rgba(37, 99, 235, 0.25);
        transition: all 0.2s ease;
    }
    div.stButton > button:first-child:hover {
        background: linear-gradient(135deg, #2563EB 0%, #1D4ED8 100%) !important;
        box-shadow: 0 6px 16px rgba(37, 99, 235, 0.35);
        transform: translateY(-1px);
    }
    button[kind="primary"] {
        background: linear-gradient(135deg, #F59E0B 0%, #D97706 100%) !important;
        box-shadow: 0 4px 12px rgba(217, 119, 6, 0.25);
    }
    button[kind="primary"]:hover {
        background: linear-gradient(135deg, #D97706 0%, #B45309 100%) !important;
    }
    /* Metric cards */
    [data-testid="stMetric"] {
        background: white;
        border-radius: 12px;
        padding: 1rem;
        box-shadow: 0 1px 3px rgba(0,0,0,0.08);
        border: 1px solid #E2E8F0;
    }
    [data-testid="stMetricLabel"] { font-weight: 600 !important; color: #64748B !important; font-size: 0.8rem !important; }
    [data-testid="stMetricValue"] { font-weight: 700 !important; color: #1E293B !important; }
    /* Tabs */
    .stTabs [data-baseweb="tab-list"] {
        gap: 4px;
        background: #EDF2F7;
        border-radius: 10px;
        padding: 4px;
    }
    .stTabs [data-baseweb="tab"] {
        border-radius: 8px;
        font-weight: 600;
        font-size: 0.85rem;
        padding: 8px 16px;
    }
    .stTabs [aria-selected="true"] {
        background: white !important;
        box-shadow: 0 1px 3px rgba(0,0,0,0.1);
    }
    /* Data tables */
    .stDataFrame { border-radius: 10px; overflow: hidden; border: 1px solid #E2E8F0; }
    /* Sidebar */
    section[data-testid="stSidebar"] { background: #1E293B !important; }
    section[data-testid="stSidebar"] * { color: #E2E8F0 !important; }
    section[data-testid="stSidebar"] .stSelectbox label,
    section[data-testid="stSidebar"] .stMultiSelect label,
    section[data-testid="stSidebar"] .stSlider label { color: #94A3B8 !important; font-weight: 500; }
    /* Expanders */
    .streamlit-expanderHeader { font-weight: 600 !important; font-size: 0.95rem; }
    /* Success/warning/info boxes */
    .stAlert { border-radius: 10px !important; }
    </style>
    """, unsafe_allow_html=True)

def _fxaji0y6d(key, default=None):
    try:
        val = st.secrets[key]
        if val is not None and str(val).strip(): return str(val).strip()
    except Exception: pass
    val = os.environ.get(key, "").strip()
    if val: return val
    return default

_vn9j2qp89 = {
    "rh_2625":  {"pass_key": "PASS_RH",      "role": "owner",    "display": "Owner"},
    "michael":  {"pass_key": "PASS_MICHAEL",  "role": "admin",    "display": "Michael A."},
    "yousef":   {"pass_key": "PASS_YOUSEF",   "role": "admin",    "display": "Yousef A."},
    "wade":     {"pass_key": "PASS_WADE",     "role": "admin",    "display": "Wade", "fallback_pass": "Enc_7089"},
    "larry":    {"pass_key": "PASS_LARRY",    "role": "dispatch", "display": "Larry J."},
}

_vuzfk8ut0 = {
    "owner": [
        "πŸ”„ Data Sync Dashboard",
        "πŸ€– Predictive Sales Router (Field)",
        "πŸ“¦ Delivery Route Builder",
        "πŸ“Š Route Compliance",
        "🚚 Driver Dispatch (Warehouse)",
    ],
    "admin": [
        "πŸ”„ Data Sync Dashboard",
        "πŸ€– Predictive Sales Router (Field)",
        "πŸ“¦ Delivery Route Builder",
        "πŸ“Š Route Compliance",
        "🚚 Driver Dispatch (Warehouse)",
    ],
    "dispatch": [
        "πŸ“¦ Delivery Route Builder",
        "🚚 Driver Dispatch (Warehouse)",
    ],
}

if "authenticated" not in st.session_state:
    st.session_state.authenticated = False
    st.session_state.user_role = None
    st.session_state.user_display = None

api_ok = bool(_fxaji0y6d("REPSLY_API_USER")) and bool(_fxaji0y6d("REPSLY_API_KEY"))

if not api_ok:
    st.title("πŸ”’ Repsly Command Center β€” Setup Required")
    st.error("⚠️ **Cannot start:** Repsly API secrets are missing.")
    st.stop()
elif not st.session_state.authenticated:
    st.title("πŸ”’ Repsly Enterprise Routing")
    st.write("Authorized personnel only. Please log in.")
    col1, col2, col3 = st.columns([1, 2, 1])
    with col2:
        with st.form("login_form"):
            user_input = st.text_input("Username")
            pass_input = st.text_input("Password", type="password")
            if st.form_submit_button("Log In", use_container_width=True):
                user_key = user_input.strip().lower()
                if user_key in _vn9j2qp89:
                    # Dynamically pull the fallback password if they don't have it in HF secrets
                    stored_pass = _fxaji0y6d(_vn9j2qp89[user_key]["pass_key"], _vn9j2qp89[user_key].get("fallback_pass", ""))
                    if stored_pass and pass_input == stored_pass:
                        st.session_state.authenticated = True
                        st.session_state.user_role = _vn9j2qp89[user_key]["role"]
                        st.session_state.user_display = _vn9j2qp89[user_key]["display"]
                        st.rerun()
                    else:
                        st.error("❌ Invalid password.")
                else:
                    st.error("❌ User not found.")
    st.stop()

_vpht0hl9x = _fxaji0y6d("REPSLY_API_USER", "")
_vpseimvih = _fxaji0y6d("REPSLY_API_KEY", "")
_vcwi64ciy = "repsly_enterprise.db"
_vhe7ur23g = 5000
_vdppq0y9d = 5
_vom5igqpk = [2, 4, 8, 15, 30]

def _fpbhsahxt():
    conn = sqlite3.connect(_vcwi64ciy, check_same_thread=False)
    conn.execute("PRAGMA journal_mode=WAL")
    conn.execute("PRAGMA synchronous=NORMAL")
    conn.execute("PRAGMA cache_size=-8000")
    conn.execute("PRAGMA temp_store=MEMORY")
    conn.row_factory = sqlite3.Row
    return conn

def _fhv3a3zmf():
    conn = _fpbhsahxt()
    conn.executescript("""
        CREATE TABLE IF NOT EXISTS clients (
            client_code TEXT PRIMARY KEY, customer_id TEXT, name TEXT, rep_name TEXT,
            active INTEGER DEFAULT 1, lat REAL DEFAULT 0.0, lon REAL DEFAULT 0.0,
            street_address TEXT, city TEXT, state TEXT, zip TEXT, tag TEXT,
            territory TEXT, updated_at TEXT
        );
        CREATE TABLE IF NOT EXISTS forms (
            form_id TEXT PRIMARY KEY, rep_name TEXT, client_code TEXT, form_name TEXT,
            cases INTEGER DEFAULT 0, dollar_value REAL DEFAULT 0.0, record_timestamp INTEGER,
            visit_date TEXT, is_order INTEGER DEFAULT 0
        );
        CREATE TABLE IF NOT EXISTS sync_meta (key TEXT PRIMARY KEY, value TEXT);
        CREATE TABLE IF NOT EXISTS generated_routes (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            rep_name TEXT,
            route_date TEXT,
            day_label TEXT,
            generated_at TEXT,
            total_stops INTEGER,
            stops_json TEXT
        );
        CREATE INDEX IF NOT EXISTS idx_forms_client ON forms(client_code);
        CREATE INDEX IF NOT EXISTS idx_forms_visit ON forms(client_code, visit_date);
        CREATE INDEX IF NOT EXISTS idx_forms_rep ON forms(rep_name);
        CREATE INDEX IF NOT EXISTS idx_routes_rep ON generated_routes(rep_name, route_date);
    """)
    conn.commit()
    conn.close()

_fhv3a3zmf()

def _f8mdd4v30(key, default=None):
    conn = _fpbhsahxt()
    row = conn.execute("SELECT value FROM sync_meta WHERE key = ?", (key,)).fetchone()
    conn.close()
    return row["value"] if row else default

def _ft9nt3w5u(key, value):
    conn = _fpbhsahxt()
    conn.execute("INSERT OR REPLACE INTO sync_meta (key, value) VALUES (?, ?)", (key, str(value)))
    conn.commit()
    conn.close()

def _fzbikcidk(rep_name, route_date, day_label, stops_data):
    conn = _fpbhsahxt()
    conn.execute("""
        INSERT INTO generated_routes (rep_name, route_date, day_label, generated_at, total_stops, stops_json)
        VALUES (?, ?, ?, ?, ?, ?)
    """, (rep_name, route_date, day_label, str(datetime.datetime.now()), len(stops_data), json.dumps(stops_data)))
    conn.commit()
    conn.close()

def _fwnnhj7xv(val):
    if val is None: return ""
    s = str(val).strip()
    return "" if s.lower() in ("none", "null", "", "unk") else s

def _fg0fn9xuy(form):
    for key in ("DateAndTime", "dateAndTime", "VisitStart", "visitStart", "Timestamp", "timestamp"):
        raw = form.get(key)
        if raw:
            raw_str = str(raw).strip()
            m = re.search(r'/Date\((\d+)', raw_str)
            if m: return int(m.group(1)) // 1000
            try: return int(pd.to_datetime(raw_str, utc=True).timestamp())
            except Exception: pass
    return None

def _f41ibljh7(data_dict, target_key):
    if not isinstance(data_dict, dict): return ""
    target_lower = target_key.lower()
    meta_raw = data_dict.get("MetaCollectionResult") or data_dict.get("metaCollectionResult")
    if isinstance(meta_raw, dict):
        for k, v in meta_raw.items():
            if str(k).lower() == target_lower: return _fwnnhj7xv(v)
    for k, v in data_dict.items():
        if str(k).lower() == target_lower: return _fwnnhj7xv(v)
    return ""

def _f5lxo6qji(url, auth, status_placeholder, context_label):
    for attempt in range(_vdppq0y9d):
        try:
            res = requests.get(url, auth=auth, timeout=30)
            if res.status_code == 200: return res.json()
            if res.status_code == 429:
                wait = max(int(res.headers.get("Retry-After", 60)), 10)
                status_placeholder.warning(f"⏳ Rate limited. Waiting {wait}s…")
                time.sleep(wait)
                continue
            status_placeholder.warning(f"⚠️ HTTP {res.status_code} on {context_label}. Retrying…")
            time.sleep(_vom5igqpk[attempt])
        except Exception as e:
            status_placeholder.warning(f"⚠️ Network error: {e}. Retrying…")
            time.sleep(_vom5igqpk[attempt])
    return None

def _fujv6oh9s(api_user, api_pass, status_placeholder):
    last_id = "0"
    page_count = 0
    total_inserted = 0
    conn = _fpbhsahxt()
    while page_count < _vhe7ur23g:
        page_count += 1
        status_placeholder.info(f"πŸ“‘ **Downloading Accounts… (Page {page_count})**")
        url = f"https://api.repsly.com/v3/export/clients/{last_id}?count=200"
        data = _f5lxo6qji(url, (api_user, api_pass), status_placeholder, "clients")
        if not data: break
        batch = data.get("Clients", [])
        if not batch: break
        sql_batch = []
        for c in batch:
            code = _fwnnhj7xv(c.get("ClientCode") or c.get("ClientID"))
            if not code: continue
            rep_obj = c.get("Representative")
            rep_name = _fwnnhj7xv(rep_obj.get("Name")) if isinstance(rep_obj, dict) else _fwnnhj7xv(c.get("RepresentativeName"))
            acct_name = _fwnnhj7xv(c.get("Name"))
            active = 0 if str(c.get("Active")).lower() in ("false", "0", "no") else 1
            try:
                lat = float(c.get("GPSLatitude") or c.get("Latitude") or 0)
                lon = float(c.get("GPSLongitude") or c.get("Longitude") or 0)
            except:
                lat, lon = 0.0, 0.0
            match = _p1.search(acct_name)
            cust_id = match.group(0).upper() if match else ""
            sql_batch.append((
                code, cust_id, acct_name, rep_name, active, lat, lon,
                _fwnnhj7xv(c.get("StreetAddress")), _fwnnhj7xv(c.get("City")),
                _fwnnhj7xv(c.get("State")), _fwnnhj7xv(c.get("ZIP")),
                _fwnnhj7xv(c.get("Tag")), _fwnnhj7xv(c.get("Territory")),
                str(datetime.datetime.now())
            ))
        conn.executemany("""
            INSERT OR REPLACE INTO clients
            (client_code, customer_id, name, rep_name, active, lat, lon,
             street_address, city, state, zip, tag, territory, updated_at)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        """, sql_batch)
        conn.commit()
        total_inserted += len(sql_batch)
        new_id = _f41ibljh7(data, "lasttimestamp") or _f41ibljh7(data, "lastid")
        if not new_id or new_id == last_id: break
        last_id = new_id
    conn.close()
    _ft9nt3w5u("last_client_sync", str(datetime.datetime.now()))
    return total_inserted

def _fdbdw2pcn(api_user, api_pass, start_date, end_date, fast_forward_id, status_placeholder):
    start_ts = int(datetime.datetime.combine(start_date, datetime.datetime.min.time()).timestamp())
    end_ts = int(datetime.datetime.combine(end_date, datetime.datetime.max.time()).timestamp())
    last_id = str(fast_forward_id).strip() if fast_forward_id else "0"
    page_count, total_scanned, total_inserted = 0, 0, 0
    conn = _fpbhsahxt()
    while page_count < _vhe7ur23g:
        page_count += 1
        status_placeholder.info(f"πŸ“‘ **Scanning Forms… ({total_scanned:,} scanned | {total_inserted:,} new | Page {page_count})**")
        url = f"https://api.repsly.com/v3/export/forms/{last_id}?count=200"
        data = _f5lxo6qji(url, (api_user, api_pass), status_placeholder, "forms")
        if not data: break
        batch = data.get("Forms", data.get("FormResults", []))
        if not batch: break
        total_scanned += len(batch)
        sql_batch = []
        count_parseable, count_future = 0, 0
        for f in batch:
            form_id = _fwnnhj7xv(f.get("FormID") or f.get("ID"))
            if not form_id: continue
            record_ts = _fg0fn9xuy(f)
            if record_ts is not None:
                count_parseable += 1
                if record_ts > end_ts: count_future += 1
                if record_ts < start_ts or record_ts > end_ts: continue
            rep_name = _fwnnhj7xv(f.get("RepresentativeName"))
            client_code = _fwnnhj7xv(f.get("ClientCode"))
            form_name = _fwnnhj7xv(f.get("FormName")).lower()
            visit_date = datetime.datetime.utcfromtimestamp(record_ts).strftime("%Y-%m-%d") if record_ts else None
            is_order = 1 if "order confirmation" in form_name else 0
            case_count = 0
            dollar_value = 0.0
            if is_order:
                for item in f.get("Items", []):
                    title = _fwnnhj7xv(item.get("Field") or item.get("Title") or item.get("Name") or "").lower()
                    val_str = _fwnnhj7xv(item.get("Value") or item.get("value") or "")
                    if "case" in title:
                        try: case_count += int(_p2.search(val_str).group())
                        except: pass
                    if "estimated dollar" in title or "dollar amount" in title:
                        cleaned = re.sub(r'[^\d.]', '', val_str)
                        if cleaned:
                            try: dollar_value += float(cleaned)
                            except: pass
                if dollar_value == 0 and case_count > 0:
                    dollar_value = case_count * 22.0
            sql_batch.append((form_id, rep_name, client_code, form_name,
                              case_count, dollar_value, record_ts, visit_date, is_order))
        if sql_batch:
            conn.executemany("""
                INSERT OR IGNORE INTO forms
                (form_id, rep_name, client_code, form_name, cases, dollar_value,
                 record_timestamp, visit_date, is_order)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
            """, sql_batch)
            conn.commit()
            total_inserted += conn.execute("SELECT changes()").fetchone()[0]
        if count_parseable > 0 and count_future == count_parseable: break
        new_id = _f41ibljh7(data, "lastid")
        if not new_id or new_id == last_id: break
        last_id = new_id
    conn.close()
    _ft9nt3w5u("last_form_sync", str(datetime.datetime.now()))
    return total_inserted

_p1 = re.compile(r'[A-Za-z]{2}\d{4}')
_p2 = re.compile(r'\d+')
_p3 = re.compile(r'[^\d.]')

def _f9t84azyt(lat1, lon1, lat2, lon2):
    R = 3958.8
    lat1, lon1, lat2, lon2 = map(math.radians, [lat1, lon1, lat2, lon2])
    a = math.sin((lat2 - lat1) / 2) ** 2 + math.cos(lat1) * math.cos(lat2) * math.sin((lon2 - lon1) / 2) ** 2
    return (R * 2 * math.asin(math.sqrt(a))) * 1.45

def _h8kq2m4np(lats, lons):
    R = 3958.8
    lat = np.radians(np.array(lats))
    lon = np.radians(np.array(lons))
    dlat = lat[:, None] - lat[None, :]
    dlon = lon[:, None] - lon[None, :]
    a = np.sin(dlat / 2) ** 2 + np.cos(lat[:, None]) * np.cos(lat[None, :]) * np.sin(dlon / 2) ** 2
    miles = R * 2 * np.arcsin(np.sqrt(a)) * 1.45
    return miles

def _fjxepq85j(conn, client_codes, rolling_days=90):
    if not client_codes:
        return {}
    ph = ",".join(["?"] * len(client_codes))
    _rc = str(datetime.date.today() - datetime.timedelta(days=rolling_days))
    combined = conn.execute(f"""
        SELECT client_code,
               COUNT(*) as total_visits,
               SUM(is_order) as total_orders,
               SUM(cases) as total_cases,
               SUM(dollar_value) as total_dollars,
               MAX(visit_date) as last_visit,
               MIN(visit_date) as first_visit,
               SUM(CASE WHEN visit_date >= ? THEN 1 ELSE 0 END) as recent_visits,
               SUM(CASE WHEN visit_date >= ? AND is_order = 1 THEN 1 ELSE 0 END) as recent_orders,
               SUM(CASE WHEN visit_date >= ? THEN cases ELSE 0 END) as recent_cases,
               SUM(CASE WHEN visit_date >= ? THEN dollar_value ELSE 0 END) as recent_dollars
        FROM forms
        WHERE client_code IN ({ph}) AND visit_date IS NOT NULL
        GROUP BY client_code
    """, [_rc]*4 + client_codes).fetchall()
    cadence = conn.execute(f"""
        SELECT client_code,
               CAST(strftime('%w', visit_date) AS INTEGER) as visit_dow,
               COUNT(*) as cnt
        FROM forms
        WHERE client_code IN ({ph}) AND visit_date IS NOT NULL
        GROUP BY client_code, visit_dow
        ORDER BY client_code, cnt DESC
    """, client_codes).fetchall()
    _cm = {}
    for r in cadence:
        cc = r["client_code"]
        if cc not in _cm:
            _cm[cc] = r["visit_dow"]
    dow_names = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
    result = {}
    for r in combined:
        cc = r["client_code"]
        tv = r["total_visits"] or 0
        to = r["total_orders"] or 0
        tc = r["total_cases"] or 0
        td = r["total_dollars"] or 0.0
        rv = r["recent_visits"] or 0
        ro = r["recent_orders"] or 0
        rc = r["recent_cases"] or 0
        rd = r["recent_dollars"] or 0.0
        if ro > 0:
            avg_cases = math.ceil(rc / ro)
            avg_dollars = round(rd / ro, 2)
        elif to > 0:
            avg_cases = math.ceil(tc / to)
            avg_dollars = round(td / to, 2)
        else:
            avg_cases = 0
            avg_dollars = 0.0
        rov = round(td / tv, 2) if tv > 0 else 0.0
        preferred_dow = _cm.get(cc)
        preferred_day = dow_names[preferred_dow] if preferred_dow is not None else "None"
        if to > 0 and ro > 0:
            at_avg = tc / to
            if avg_cases > at_avg * 1.2: trend = "πŸ“ˆ Up"
            elif avg_cases < at_avg * 0.8: trend = "πŸ“‰ Down"
            else: trend = "➑️ Stable"
        else:
            trend = "β€”"
        result[cc] = {
            "total_visits": tv, "total_orders": to, "total_cases": tc,
            "total_dollars": td, "last_visit": r["last_visit"],
            "first_visit": r["first_visit"], "avg_cases": avg_cases,
            "avg_dollars": avg_dollars, "rov": rov,
            "preferred_day": preferred_day, "preferred_dow": preferred_dow,
            "trend": trend, "recent_visits": rv, "recent_orders": ro,
        }
    return result

def _fsg65kxvf(metrics, days_since_last, projection_days=0):
    tv = metrics.get("total_visits", 0)
    to = metrics.get("total_orders", 0)
    avg_cases = metrics.get("avg_cases", 10)
    avg_dollars = metrics.get("avg_dollars", 100)
    if tv == 0:
        return 1.0, 10.0, 10.0, 100.0, 100.0
    divisor = to if to > 0 else tv
    avg_cycle = max(365.0 / divisor, 7.0)
    future_days = days_since_last + (projection_days / 2.0)
    urgency_ratio = future_days / avg_cycle
    if urgency_ratio < 0.6:
        probability = 0.0
    else:
        probability = min(1.0, urgency_ratio)
    expected_cases = probability * avg_cases
    expected_dollars = probability * avg_dollars
    return (round(probability, 2), round(float(avg_cases), 1),
            round(expected_cases, 2), round(float(avg_dollars), 2),
            round(expected_dollars, 2))

def _f1t2tala7(conn, rep_name, lookback_days=30):
    cutoff = str(datetime.date.today() - datetime.timedelta(days=lookback_days))
    routes = conn.execute("""
        SELECT id, route_date, day_label, total_stops, stops_json, generated_at
        FROM generated_routes
        WHERE rep_name = ? AND route_date >= ?
        ORDER BY route_date DESC
    """, (rep_name, cutoff)).fetchall()
    if not routes:
        return []
    rep_lower = rep_name.lower().strip()
    _cd = []
    for route in routes:
        route_date = route["route_date"]
        try:
            planned_stops = json.loads(route["stops_json"])
        except:
            continue
        planned_codes = set()
        for stop in planned_stops:
            store_name = stop.get("Store", "")
            if "Home" in store_name or "🏠" in store_name:
                continue
            code = stop.get("id", stop.get("code", ""))
            if code:
                planned_codes.add(code)
            else:
                planned_codes.add(store_name)
        if not planned_codes:
            continue
        actual_visits = conn.execute("""
            SELECT DISTINCT client_code
            FROM forms
            WHERE LOWER(rep_name) LIKE ? AND visit_date = ?
        """, (f"%{rep_lower}%", route_date)).fetchall()
        actual_codes = set(r["client_code"] for r in actual_visits)
        visited = planned_codes & actual_codes
        missed = planned_codes - actual_codes
        unplanned = actual_codes - planned_codes
        total_planned = len(planned_codes)
        compliance_pct = round((len(visited) / total_planned) * 100) if total_planned > 0 else 0
        _cd.append({
            "Date": route_date,
            "Day": route["day_label"],
            "Planned": total_planned,
            "Visited": len(visited),
            "Missed": len(missed),
            "Unplanned": len(unplanned),
            "Compliance %": f"{compliance_pct}%",
        })
    return _cd

@st.cache_data(ttl=300, show_spinner=False)
def _o3rx7kwm(coords_str):
    try:
        url = f"http://router.project-osrm.org/table/v1/driving/{coords_str}?annotations=duration"
        resp = requests.get(url, timeout=15)
        if resp.status_code == 200:
            return resp.json().get('durations')
    except: pass
    return None

def _f53lc58dr(nodes, use_osrm=False):
    size = len(nodes)
    lats = [n['lat'] for n in nodes]
    lons = [n['lon'] for n in nodes]
    if use_osrm and size <= 100:
        coords_str = ";".join([f"{n['lon']},{n['lat']}" for n in nodes])
        durations = _o3rx7kwm(coords_str)
        if durations:
            matrix = [[0]*size for _ in range(size)]
            fallback = _h8kq2m4np(lats, lons)
            for i in range(size):
                for j in range(size):
                    if durations[i][j] is not None:
                        matrix[i][j] = int(durations[i][j] / 60.0)
                    else:
                        matrix[i][j] = int((fallback[i][j] / 45.0) * 60)
            return matrix, True
        else:
            st.warning("⚠️ OSRM unavailable. Using geometric engine.")
    miles = _h8kq2m4np(lats, lons)
    matrix = ((miles / 45.0) * 60).astype(int).tolist()
    return matrix, False

def _fc11ertj5(minutes):
    h = (int(minutes) // 60) % 24
    m = int(minutes) % 60
    ap = "AM" if h < 12 else "PM"
    ch = h if h <= 12 else h - 12
    if ch == 0: ch = 12
    return f"{ch:02d}:{m:02d} {ap}"

_tk9 = _fxaji0y6d("_tk9", "")

@st.cache_data(ttl=600, show_spinner=False)
def _t4mk9x2z(lats, lons, truck_height, truck_weight, truck_length, truck_width):
    if not _tk9:
        return None
    size = len(lats)
    if size > 50:
        return None
    origins = [{"point": {"latitude": float(lats[i]), "longitude": float(lons[i])}} for i in range(size)]
    destinations = origins.copy()
    payload = {
        "origins": origins,
        "destinations": destinations,
        "options": {
            "travelMode": "truck",
            "vehicleLoadType": "otherHazmatGeneral",
            "vehicleHeight": truck_height,
            "vehicleWeight": truck_weight,
            "vehicleLength": truck_length,
            "vehicleWidth": truck_width,
            "traffic": "live",
            "departAt": "now",
        }
    }
    try:
        url = f"https://api.tomtom.com/routing/matrix/2?key={_tk9}"
        headers = {"Content-Type": "application/json"}
        resp = requests.post(url, json=payload, headers=headers, timeout=30)
        if resp.status_code == 200:
            data = resp.json()
            matrix = data.get("data", [])
            _tm = [[0] * size for _ in range(size)]
            for entry in matrix:
                oi = entry.get("originIndex", 0)
                di = entry.get("destinationIndex", 0)
                route_summary = entry.get("routeSummary", {})
                travel_secs = route_summary.get("travelTimeInSeconds", 0)
                _tm[oi][di] = max(1, int(travel_secs / 60))
            return _tm
        elif resp.status_code == 403:
            st.warning("⚠️ TomTom API key invalid or expired. Using geometric fallback.")
            return None
        else:
            st.warning(f"⚠️ TomTom API returned HTTP {resp.status_code}. Using geometric fallback.")
            return None
    except requests.exceptions.Timeout:
        st.warning("⚠️ TomTom API timeout. Using geometric fallback.")
        return None
    except Exception as e:
        st.warning(f"⚠️ TomTom error: {e}. Using geometric fallback.")
        return None

def _btm7q3(nodes, truck_height=4.0, truck_weight=11800, truck_length=10.0, truck_width=2.6):
    size = len(nodes)
    lats = tuple(n['lat'] for n in nodes)
    lons = tuple(n['lon'] for n in nodes)
    if _tk9 and size <= 50:
        tomtom_matrix = _t4mk9x2z(lats, lons, truck_height, truck_weight, truck_length, truck_width)
        if tomtom_matrix:
            return tomtom_matrix, True, "TomTom Truck"
    miles = _h8kq2m4np(list(lats), list(lons))
    matrix = ((miles / 35.0) * 60).astype(int).tolist()
    engine_used = "Geometric (truck-adjusted, 35mph avg)"
    return matrix, False, engine_used

st.title("⚑ Repsly Enterprise Operations")
st.sidebar.markdown(f"**πŸ‘€ {st.session_state.user_display}** ({st.session_state.user_role.title()})")

if st.sidebar.button("πŸ”“ Log Out", use_container_width=True):
    st.session_state.authenticated = False
    st.session_state.user_role = None
    st.session_state.user_display = None
    st.rerun()

allowed_modules = _vuzfk8ut0.get(st.session_state.user_role, [])
app_mode = st.sidebar.radio("βš™οΈ Select Module", allowed_modules)
st.sidebar.divider()
conn = _fpbhsahxt()
try:
    client_count = conn.execute("SELECT COUNT(*) as c FROM clients").fetchone()["c"]
    form_count = conn.execute("SELECT COUNT(*) as c FROM forms").fetchone()["c"]
except sqlite3.OperationalError:
    client_count, form_count = 0, 0
conn.close()

if app_mode == "πŸ”„ Data Sync Dashboard":
    st.subheader("πŸ—„οΈ Database Management")
    if client_count > 0:
        st.success(f"**Database Active:** {client_count:,} accounts | {form_count:,} forms.")
        st.caption(f"Last client sync: {_f8mdd4v30('last_client_sync', 'Never')} | Last form sync: {_f8mdd4v30('last_form_sync', 'Never')}")
    else:
        st.warning("Database is empty. Run a sync below.")
    st.divider()
    col1, col2, col3 = st.columns(3)
    today = datetime.date.today()
    with col1: start_date = st.date_input("Start Date", datetime.date(2024, 1, 1))
    with col2: end_date = st.date_input("End Date", today)
    with col3: fast_forward_id = st.text_input("⏩ Fast-Forward ID", value="0")
    if st.button("πŸš€ RUN ENTERPRISE API SYNC", type="primary", use_container_width=True):
        status = st.empty()
        try:
            if fast_forward_id in ["0", "", None]:
                status.info("πŸ—‘οΈ Clearing old form data for clean re-import...")
                c = _fpbhsahxt()
                c.execute("DELETE FROM forms")
                c.commit()
                c.close()
            status.info("πŸ“‘ Syncing Accounts...")
            _fujv6oh9s(_vpht0hl9x, _vpseimvih, status)
            status.info("πŸ“‘ Syncing Forms...")
            _fdbdw2pcn(_vpht0hl9x, _vpseimvih, start_date, end_date, fast_forward_id, status)
            status.success("βœ… **Sync Complete!**")
            time.sleep(2)
            st.rerun()
        except Exception as e:
            status.error(f"❌ {e}")
    st.divider()
    st.markdown("**πŸ”Ž Form Name Inspector** β€” See what forms exist in your database")
    conn_diag = _fpbhsahxt()
    form_names = conn_diag.execute("""
        SELECT form_name, COUNT(*) as cnt, SUM(cases) as total_cases, SUM(dollar_value) as total_dollars
        FROM forms
        GROUP BY form_name
        ORDER BY cnt DESC
        LIMIT 20
    """).fetchall()
    conn_diag.close()
    if form_names:
        st.write(f"**Top {len(form_names)} form types in your database:**")
        for fn in form_names:
            name = fn["form_name"] or "(blank)"
            is_flagged = "βœ… Flagged as order" if "order confirmation" in name.lower() else "❌ Not flagged"
            st.text(f"  {is_flagged} | {fn['cnt']:,}x | \"{name}\" | Cases: {fn['total_cases'] or 0} | ${fn['total_dollars'] or 0:.0f}")
        st.info("The system only counts forms as orders if the name contains 'order confirmation'. If your order form has a different name, tell me and I'll fix it.")
    else:
        st.warning("No forms in database. Run a sync first.")
    st.markdown("**πŸ”Ž Order Form Field Inspector** β€” See what field names your Order Confirmation forms use")
    if st.button("πŸ“‘ Fetch Sample Forms from API (with Items)", key="fetch_order_sample"):
        with st.spinner("Scanning for forms with item data..."):
            status_tmp = st.empty()
            last_id = "0"
            found_count = 0
            seen_names = set()
            for page in range(20):
                data = _f5lxo6qji(
                    f"https://api.repsly.com/v3/export/forms/{last_id}?count=200",
                    (_vpht0hl9x, _vpseimvih), status_tmp, "form sample"
                )
                if not data: break
                batch = data.get("Forms", data.get("FormResults", []))
                if not batch: break
                for form in batch:
                    fn = _fwnnhj7xv(form.get("FormName"))
                    items = form.get("Items", [])
                    if items and fn.lower() not in seen_names:
                        seen_names.add(fn.lower())
                        st.success(f"**Form: \"{fn}\"** β€” {len(items)} fields")
                        for item in items[:10]:
                            field = item.get("Field") or item.get("Title") or item.get("Name") or "(no label)"
                            val = str(item.get("Value", ""))[:100]
                            fl = str(field).lower()
                            if "case" in fl:
                                st.markdown(f"  πŸ“¦ **{field}**: `{val}`")
                            elif any(k in fl for k in ["dollar", "price", "total", "cost", "$", "amount", "value", "est", "sale"]):
                                st.markdown(f"  πŸ’° **{field}**: `{val}`")
                            else:
                                st.text(f"  {field}: {val}")
                        st.divider()
                        found_count += 1
                        if found_count >= 5: break
                if found_count >= 5: break
                new_id = _f41ibljh7(data, "lastid")
                if not new_id or new_id == last_id: break
                last_id = new_id
            status_tmp.empty()
            if found_count == 0:
                st.warning("No forms with item data found.")
    if st.button("πŸ—‘οΈ Factory Reset Database"):
        c = _fpbhsahxt()
        for t in ["clients", "forms", "sync_meta", "generated_routes"]:
            c.execute(f"DELETE FROM {t}")
        c.commit()
        c.close()
        st.rerun()

elif app_mode == "πŸ“Š Route Compliance":
    st.subheader("πŸ“Š Route Compliance Tracker")
    st.write("Compare planned routes vs actual store visits to measure rep execution.")
    if client_count == 0:
        st.warning("Database empty. Sync first.")
        st.stop()
    conn = _fpbhsahxt()
    reps = sorted([r["rep_name"] for r in conn.execute(
        "SELECT DISTINCT rep_name FROM clients WHERE rep_name != '' AND rep_name IS NOT NULL"
    ).fetchall()])
    selected_rep = st.selectbox("Select Rep", reps) if reps else st.text_input("Rep Name")
    lookback = st.slider("Lookback Period (days)", 7, 90, 30)
    if selected_rep:
        compliance = _f1t2tala7(conn, selected_rep, lookback)
        if compliance:
            df_comp = pd.DataFrame(compliance)
            avg_compliance = df_comp["Compliance %"].str.replace("%", "").astype(int).mean()
            c1, c2, c3, c4 = st.columns(4)
            with c1:
                color = "🟒" if avg_compliance >= 80 else "🟑" if avg_compliance >= 60 else "πŸ”΄"
                st.metric("Avg Compliance", f"{color} {avg_compliance:.0f}%")
            with c2:
                st.metric("Routes Tracked", len(compliance))
            with c3:
                total_planned = df_comp["Planned"].sum()
                total_visited = df_comp["Visited"].sum()
                st.metric("Stores Visited", f"{total_visited} / {total_planned}")
            with c4:
                total_missed = df_comp["Missed"].sum()
                st.metric("Total Missed", total_missed)
            st.divider()
            st.dataframe(df_comp, use_container_width=True, hide_index=True)
            if len(df_comp) > 1:
                chart_df = df_comp.copy()
                chart_df["Pct"] = chart_df["Compliance %"].str.replace("%", "").astype(int)
                st.line_chart(chart_df.set_index("Date")["Pct"], use_container_width=True)
        else:
            st.info(f"No route history found for {selected_rep} in the last {lookback} days. Generate routes first, then check back.")
    conn.close()

elif app_mode == "πŸ€– Predictive Sales Router (Field)":
    if client_count == 0:
        st.warning("Database empty. Run Data Sync first.")
        st.stop()
    _v874frhoc = {
        "Brian Milam": {"lat": 36.0152, "lon": -80.2641},
        "Julia Cameron": {"lat": 35.3942, "lon": -77.9248},
        "Aaron Manning": {"lat": 35.9184, "lon": -78.8051},
        "David Williams": {"lat": 34.6181, "lon": -79.0086},
        "David Christian": {"lat": 35.6325, "lon": -77.3996},
        "Charles White": {"lat": 35.0975, "lon": -81.0114},
        "Dorrian Hickman": {"lat": 34.0531, "lon": -79.7995},
        "Shameek Huggins": {"lat": 33.8643, "lon": -79.0881},
        "Tiara Gordon": {"lat": 36.0354, "lon": -79.8662},
    }
    with st.sidebar:
        st.header("πŸ‘€ Territory Optimizer")
        conn = _fpbhsahxt()
        reps = sorted([r["rep_name"] for r in conn.execute(
            "SELECT DISTINCT rep_name FROM clients WHERE rep_name != '' AND rep_name IS NOT NULL"
        ).fetchall()])
        territories = sorted(list(set([r["territory"] for r in conn.execute(
            "SELECT DISTINCT territory FROM clients WHERE territory != '' AND territory IS NOT NULL"
        ).fetchall()])))
        st.markdown("**1. Assign Driver(s)**")
        selected_reps = st.multiselect("Select Sales Reps", reps)
        st.markdown("**2. Pull Territories (Optional)**")
        _sterr = st.multiselect("Additional Territories", territories)
        st.divider()
        st.markdown("**Routing Constraints**")
        route_days = st.slider("Days in Cycle", 1, 14, 10)
        max_hours = st.slider("Max Hours/Shift", 6.0, 14.0, 10.0, step=0.5, help="Default: 10 hours (depart 6 AM β†’ last stop by 4 PM)")
        max_stops = st.slider("Max Stops/Day", 10, 30, 25)
        st.divider()
        st.markdown("**Enterprise Filters**")
        hide_ghosts = st.toggle("πŸ‘» Hide Zero-Visit Accounts", value=False)
        use_osrm = st.toggle("🚦 Use OSRM Traffic", value=True)
        lock_cadence = st.toggle("πŸ”’ Lock Weekly Stores to Same Day", value=True,
                                 help="Weekly accounts always visit on their historically most common weekday")
        _cdy = st.number_input("🧊 Cooldown (min days between visits)", min_value=0, max_value=14, value=5,
                                        help="Stores visited within this many days are excluded. 0 = no cooldown.")
    if not selected_reps:
        st.info("Select at least one Sales Rep in the sidebar.")
        st.stop()
    st.subheader("🧠 Revenue-Maximizing Fleet Optimization")
    conditions = []
    safe_reps = [r.lower().strip().replace("'", "''") for r in selected_reps]
    rep_conditions = " OR ".join([f"LOWER(rep_name) LIKE '%{r}%'" for r in safe_reps])
    conditions.append(f"({rep_conditions})")
    if _sterr:
        safe_terrs = [t.lower().strip().replace("'", "''") for t in _sterr]
        terr_conditions = " OR ".join([f"LOWER(territory) LIKE '%{t}%'" for t in safe_terrs])
        conditions.append(f"({terr_conditions})")
    where_clause = " OR ".join(conditions)
    accounts = conn.execute(f"""
        SELECT client_code, customer_id, name, lat, lon, street_address, city, rep_name, territory
        FROM clients
        WHERE ({where_clause}) AND active = 1 AND lat != 0 AND lon != 0
    """).fetchall()
    account_names = [a["name"] for a in accounts]
    _vip = st.multiselect("πŸ“Œ VIP Accounts (Force Visit)", account_names)
    if st.button("πŸš€ GENERATE FLEET ROUTE", type="primary", use_container_width=True):
        with st.spinner("Running predictive revenue models..."):
            codes = list(set([a["client_code"] for a in accounts]
                           + [a["customer_id"] for a in accounts if a["customer_id"]]))
            if not codes:
                st.error("No active GPS accounts found.")
                st.stop()
            metrics = _fjxepq85j(conn, codes, rolling_days=90)
            today = datetime.date.today()
            weekday_map = {0: "Mon", 1: "Tue", 2: "Wed", 3: "Thu", 4: "Fri"}
            solver_dow = {1: 0, 2: 1, 3: 2, 4: 3, 5: 4}
            _cn = []
            _cs = 0
            for acct in accounts:
                cc = acct["client_code"]
                cust_id = acct["customer_id"]
                m = metrics.get(cust_id) or metrics.get(cc) or {}
                if hide_ghosts and m.get("total_visits", 0) == 0 and acct["name"] not in _vip:
                    continue
                lv = m.get("last_visit")
                days_since = (today - datetime.datetime.strptime(lv, "%Y-%m-%d").date()).days if lv else 999
                if _cdy > 0 and days_since < _cdy and acct["name"] not in _vip:
                    _cs += 1
                    continue
                prob, avg_cases, exp_cases, avg_dollars, exp_dollars = _fsg65kxvf(m, days_since, route_days)
                svc_time = int(15 + (exp_cases * 1.5)) if exp_cases > 0 else 10
                if acct["name"] in _vip:
                    exp_dollars += 10000
                tv = m.get("total_visits", 0)
                if tv > 0:
                    first = m.get("first_visit")
                    last = m.get("last_visit")
                    if first and last:
                        try:
                            span = (datetime.datetime.strptime(last, "%Y-%m-%d").date() -
                                    datetime.datetime.strptime(first, "%Y-%m-%d").date()).days
                            cycle = max(span / tv, 7)
                        except:
                            cycle = 30
                    else:
                        cycle = 30
                else:
                    cycle = 90
                if cycle <= 9: freq_label = "Weekly"
                elif cycle <= 18: freq_label = "Bi-Weekly"
                elif cycle <= 40: freq_label = "Monthly"
                else: freq_label = "Infrequent"
                _cn.append({
                    "id": cc, "cust_id": cust_id, "name": acct["name"],
                    "lat": acct["lat"], "lon": acct["lon"],
                    "budget_mins": svc_time,
                    "ev": exp_cases, "expected_dollars": exp_dollars,
                    "prob": prob, "avg_cases": avg_cases,
                    "avg_dollars": m.get("avg_dollars", 0),
                    "days_since": days_since,
                    "rov": m.get("rov", 0),
                    "trend": m.get("trend", "β€”"),
                    "preferred_day": m.get("preferred_day", "None"),
                    "preferred_dow": m.get("preferred_dow"),
                    "freq": freq_label,
                    "desc": f"{acct['street_address']}, {acct['city']}",
                    "is_vip": acct["name"] in _vip,
                })
            if not _cn:
                st.warning("⚠️ No accounts matched. Try toggling the Ghost filter or reducing the cooldown period.")
                st.stop()
            if _cs > 0:
                st.caption(f"🧊 Cooldown filter: {_cs} stores visited within the last {_cdy} days were excluded.")
            _cn.sort(key=lambda x: x["expected_dollars"], reverse=True)
            if use_osrm and len(_cn) > 90:
                st.warning("Territory exceeds 100 stops. Falling back to internal engine.")
                use_osrm = False
            MAX_GAP_MILES = 10.0
            _dw8k = {
                "Greensboro": {"lat": 36.046, "lon": -79.773},
                "Wilmington": {"lat": 34.269, "lon": -77.935},
                "Sumter":     {"lat": 33.918, "lon": -80.328},
            }
            if len(_cn) > route_days:
                from sklearn.cluster import KMeans
                coords = np.array([[n["lat"], n["lon"]] for n in _cn])
                n_clusters = min(route_days, len(_cn))
                km = KMeans(n_clusters=n_clusters, random_state=42, n_init=10)
                zone_labels = km.fit_predict(coords)
                for i, node in enumerate(_cn):
                    node["zone"] = int(zone_labels[i])
                zone_warehouse = {}
                for z_id in range(n_clusters):
                    centroid = km.cluster_centers_[z_id]
                    zone_stores = [n for n in _cn if n["zone"] == z_id]
                    best_wh, best_dist = "Unknown", 999
                    for wh_name, wh_loc in _dw8k.items():
                        d = _f9t84azyt(centroid[0], centroid[1], wh_loc["lat"], wh_loc["lon"])
                        if d < best_dist:
                            best_wh, best_dist = wh_name, d
                    if zone_stores:
                        sorted_stores = sorted(zone_stores, key=lambda s: (s["lat"], s["lon"]))
                        intra = sum(
                            _f9t84azyt(sorted_stores[i]["lat"], sorted_stores[i]["lon"],
                                       sorted_stores[i+1]["lat"], sorted_stores[i+1]["lon"])
                            for i in range(len(sorted_stores) - 1)
                        ) if len(sorted_stores) > 1 else 0
                        est_loop = round(best_dist * 2 + intra * 1.3, 1)
                    else:
                        est_loop = 0
                    zone_warehouse[z_id] = {
                        "name": best_wh,
                        "dist": round(best_dist, 1),
                        "est_loop": est_loop,
                        "store_count": len(zone_stores),
                    }
                for node in _cn:
                    zw = zone_warehouse.get(node["zone"], {})
                    node["delivery_wh"] = zw.get("name", "β€”")
                    node["delivery_loop"] = zw.get("est_loop", 0)
                outlier_count = 0
                for node in _cn:
                    zone_mates = [n for n in _cn if n["zone"] == node["zone"] and n["id"] != node["id"]]
                    if zone_mates:
                        min_dist = min(_f9t84azyt(node["lat"], node["lon"], m["lat"], m["lon"]) for m in zone_mates)
                        node["nearest_neighbor_miles"] = round(min_dist, 1)
                        if min_dist > MAX_GAP_MILES:
                            node["is_outlier"] = True
                            outlier_count += 1
                            dists_to_centers = [_f9t84azyt(node["lat"], node["lon"], c[0], c[1]) for c in km.cluster_centers_]
                            sorted_centers = sorted(range(len(dists_to_centers)), key=lambda x: dists_to_centers[x])
                            for alt_zone in sorted_centers:
                                alt_mates = [n for n in _cn if n["zone"] == alt_zone and n["id"] != node["id"]]
                                if alt_mates:
                                    alt_min = min(_f9t84azyt(node["lat"], node["lon"], m["lat"], m["lon"]) for m in alt_mates)
                                    if alt_min <= MAX_GAP_MILES:
                                        node["zone"] = alt_zone
                                        node["is_outlier"] = False
                                        zw = zone_warehouse.get(alt_zone, {})
                                        node["delivery_wh"] = zw.get("name", "β€”")
                                        node["delivery_loop"] = zw.get("est_loop", 0)
                                        outlier_count -= 1
                                        break
                    else:
                        node["nearest_neighbor_miles"] = 0
                        node["is_outlier"] = False
                if outlier_count > 0:
                    st.warning(f"⚠️ {outlier_count} stores are more than {MAX_GAP_MILES} miles from any neighbor.")
            else:
                zone_warehouse = {}
                for i, node in enumerate(_cn):
                    node["zone"] = i % max(1, route_days)
                    node["is_outlier"] = False
                    node["delivery_wh"] = "β€”"
                    node["delivery_loop"] = 0
            _dync = {}
            for rep in selected_reps:
                if rep not in _v874frhoc:
                    rep_accts = [a for a in accounts if rep.lower() in str(a.get("rep_name", "")).lower()]
                    if rep_accts:
                        _dync[rep] = {
                            "lat": sum(a["lat"] for a in rep_accts) / len(rep_accts),
                            "lon": sum(a["lon"] for a in rep_accts) / len(rep_accts)
                        }
            _dn, starts, ends, _vl = [], [], [], []
            node_idx = 0
            for rep in selected_reps:
                if rep in _v874frhoc: d_lat, d_lon = _v874frhoc[rep]["lat"], _v874frhoc[rep]["lon"]
                elif rep in _dync: d_lat, d_lon = _dync[rep]["lat"], _dync[rep]["lon"]
                else: d_lat, d_lon = 36.0726, -79.7919
                _dn.append({
                    "id": f"DEPOT_{rep}", "name": f"🏠 {rep} Home",
                    "lat": d_lat, "lon": d_lon, "budget_mins": 0,
                    "ev": 0, "expected_dollars": 0, "prob": 0
                })
                for day in range(route_days):
                    starts.append(node_idx)
                    ends.append(node_idx)
                    _vl.append({"rep": rep, "day": day + 1})
                node_idx += 1
            nodes = _dn + _cn
            size = len(nodes)
            num_vehicles = len(starts)
            max_time_per_day = int(max_hours * 60)
            _cl = {}
            if lock_cadence:
                for ci, cn in enumerate(_cn):
                    if cn["freq"] == "Weekly" and cn["preferred_dow"] is not None:
                        target_weekday = cn["preferred_dow"] - 1
                        if 0 <= target_weekday <= 4:
                            node_global_idx = len(_dn) + ci
                            for vi, vl in enumerate(_vl):
                                if vl["rep"] in selected_reps and ((vl["day"] - 1) % 5) == target_weekday:
                                    _cl[node_global_idx] = vi
                                    break
            _tm, used_osrm = _f53lc58dr(nodes, use_osrm)
            if used_osrm:
                st.success("🚦 OSRM Traffic Data loaded!")
            manager = pywrapcp.RoutingIndexManager(size, num_vehicles, starts, ends)
            routing = pywrapcp.RoutingModel(manager)
            def _tcb(from_index, to_index):
                fn, tn = manager.IndexToNode(from_index), manager.IndexToNode(to_index)
                return _tm[fn][tn] + nodes[tn]["budget_mins"]
            transit_cb = routing.RegisterTransitCallback(_tcb)
            routing.SetArcCostEvaluatorOfAllVehicles(transit_cb)
            routing.AddDimension(transit_cb, 30, max_time_per_day, False, 'Time')
            def _dmc(from_index):
                node = manager.IndexToNode(from_index)
                return 0 if node < len(_dn) else 1
            demand_cb = routing.RegisterUnaryTransitCallback(_dmc)
            routing.AddDimension(demand_cb, 0, max_stops, True, 'Stops')
            stops_dim = routing.GetDimensionOrDie('Stops')
            stops_dim.SetGlobalSpanCostCoefficient(50)
            def _smc(from_index):
                node = manager.IndexToNode(from_index)
                if node < len(_dn):
                    return 0
                return nodes[node].get("budget_mins", 10)
            svc_cb = routing.RegisterUnaryTransitCallback(_smc)
            max_svc_per_day = int(max_hours * 60)
            routing.AddDimension(svc_cb, 0, max_svc_per_day, True, 'ServiceLoad')
            svc_dim = routing.GetDimensionOrDie('ServiceLoad')
            svc_dim.SetGlobalSpanCostCoefficient(25)
            num_depots = len(_dn)
            for i in range(num_depots, size):
                n = nodes[i]
                penalty = 10000000 if n.get("is_vip") else int(5000 + (n["expected_dollars"] * 10) + (n["ev"] * 500) + (n.get("rov", 0) * 20))
                routing.AddDisjunction([manager.NodeToIndex(i)], penalty)
            if _cl:
                for node_idx, vehicle_id in _cl.items():
                    try:
                        routing.SetAllowedVehiclesForIndex([vehicle_id], manager.NodeToIndex(node_idx))
                    except:
                        pass
            for ci, cn in enumerate(_cn):
                node_global_idx = num_depots + ci
                if node_global_idx in _cl:
                    continue
                zone = cn.get("zone", -1)
                if zone >= 0:
                    target_day = (zone % route_days) + 1
                    allowed = [v for v, vl in enumerate(_vl) if vl["day"] == target_day]
                    if allowed:
                        try:
                            routing.SetAllowedVehiclesForIndex(allowed, manager.NodeToIndex(node_global_idx))
                        except:
                            pass
            _sp2 = pywrapcp.DefaultRoutingSearchParameters()
            _sp2.first_solution_strategy = routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC
            _sp2.local_search_metaheuristic = routing_enums_pb2.LocalSearchMetaheuristic.GUIDED_LOCAL_SEARCH
            _sp2.time_limit.seconds = 5
            solution = routing.SolveWithParameters(_sp2)
            if solution:
                time_dim = routing.GetDimensionOrDie('Time')
                day_colors = {
                    "Monday": [231, 76, 60],    "Tuesday": [52, 152, 219],
                    "Wednesday": [46, 204, 113], "Thursday": [241, 196, 15],
                    "Friday": [155, 89, 182],
                }
                weekdays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
                all_rep_routes = {}
                for rep_idx, rep in enumerate(selected_reps):
                    rep_vehicles = [v for v, label in enumerate(_vl) if label["rep"] == rep]
                    rep_routes = []
                    human_day_counter = 1
                    for v_id in rep_vehicles:
                        index = routing.Start(v_id)
                        prev_idx = routing.Start(v_id)
                        _ro = []
                        day_ev = 0
                        day_dollars = 0.0
                        stop_num = 0
                        while not routing.IsEnd(index):
                            node_index = manager.IndexToNode(index)
                            arr_time = solution.Value(time_dim.CumulVar(index)) + 360
                            if node_index >= num_depots:
                                n = nodes[node_index]
                                stop_num += 1
                                day_ev += n['ev']
                                day_dollars += n['expected_dollars']
                                drive_mins = _tm[manager.IndexToNode(prev_idx)][node_index]
                                _ro.append({
                                    "#": stop_num,
                                    "Time": _fc11ertj5(arr_time),
                                    "Store": ("πŸ“Œ " + n["name"]) if n.get("is_vip") else n["name"],
                                    "Prob": f"{int(n['prob']*100)}%",
                                    "Exp.$": f"${round(n['expected_dollars'],2):,}",
                                    "ROV": f"${n.get('rov', 0):,.0f}",
                                    "Trend": n.get("trend", "β€”"),
                                    "Freq": n.get("freq", "β€”"),
                                    "Pref Day": n.get("preferred_day", "β€”"),
                                    "Days Since": n["days_since"],
                                    "Drive": f"{drive_mins}m",
                                    "Service": f"{n['budget_mins']}m",
                                    "lat": n["lat"], "lon": n["lon"],
                                    "id": n.get("cust_id") or n["id"],
                                    "stop_label": f"#{stop_num}",
                                    "delivery_wh": n.get("delivery_wh", "β€”"),
                                    "delivery_loop": n.get("delivery_loop", 0),
                                })
                            prev_idx = index
                            index = solution.Value(routing.NextVar(index))
                        if _ro:
                            week_num = ((human_day_counter - 1) // 5) + 1
                            day_name = weekdays[(human_day_counter - 1) % 5]
                            days_ahead = human_day_counter - 1
                            route_date = str(today + datetime.timedelta(days=days_ahead + (days_ahead // 5) * 2))
                            _fzbikcidk(rep, route_date, f"Week {week_num} - {day_name}", _ro)
                            day_wh_names = [r.get("delivery_wh", "β€”") for r in _ro if r.get("delivery_wh")]
                            if day_wh_names:
                                from collections import Counter
                                day_warehouse = Counter(day_wh_names).most_common(1)[0][0]
                            else:
                                day_warehouse = "β€”"
                            day_loop = max((r.get("delivery_loop", 0) for r in _ro), default=0)
                            rep_routes.append({
                                "week": week_num,
                                "day": day_name,
                                "label": f"Week {week_num} - {day_name}",
                                "rows": _ro,
                                "ev": day_ev,
                                "dollars": day_dollars,
                                "stops": len(_ro),
                                "color": day_colors.get(day_name, [100, 100, 100]),
                                "depot_lat": _dn[rep_idx]["lat"],
                                "depot_lon": _dn[rep_idx]["lon"],
                                "delivery_wh": day_warehouse,
                                "delivery_loop": round(day_loop, 1),
                            })
                        human_day_counter += 1
                    all_rep_routes[rep] = rep_routes
                total_stops_all = sum(r["stops"] for rep_routes in all_rep_routes.values() for r in rep_routes)
                total_days_all = sum(len(routes) for routes in all_rep_routes.values())
                total_dollars_all = sum(r["dollars"] for rep_routes in all_rep_routes.values() for r in rep_routes)
                total_cases_all = sum(r["ev"] for rep_routes in all_rep_routes.values() for r in rep_routes)
                st.markdown("---")
                m1, m2, m3, m4 = st.columns(4)
                m1.metric("Total Stops", f"{total_stops_all}")
                m2.metric("Route Days", f"{total_days_all}")
                m3.metric("Projected Cases", f"{round(total_cases_all):,}")
                m4.metric("Projected Revenue", f"${round(total_dollars_all):,}")
                rep_tabs = st.tabs(selected_reps) if len(selected_reps) > 1 else [st.container()]
                for rep_idx, rep in enumerate(selected_reps):
                    with rep_tabs[rep_idx]:
                        rep_routes = all_rep_routes.get(rep, [])
                        if not rep_routes:
                            st.info(f"No routes generated for {rep}.")
                            continue
                        weeks = {}
                        for r in rep_routes:
                            weeks.setdefault(r["week"], []).append(r)
                        num_weeks = len(weeks)
                        week_tab_labels = [f"πŸ“… Week {wk}" for wk in sorted(weeks.keys())]
                        week_tabs_inner = st.tabs(week_tab_labels)
                        for wk_tab_idx, wk_num in enumerate(sorted(weeks.keys())):
                            with week_tabs_inner[wk_tab_idx]:
                                wk_routes = weeks[wk_num]
                                wk_stops = sum(r["stops"] for r in wk_routes)
                                wk_cases = sum(r["ev"] for r in wk_routes)
                                wk_dollars = sum(r["dollars"] for r in wk_routes)
                                wc1, wc2, wc3 = st.columns(3)
                                wc1.metric(f"Week {wk_num} Stops", wk_stops)
                                wc2.metric("Exp. Cases", f"{round(wk_cases):,}")
                                wc3.metric("Exp. Revenue", f"${round(wk_dollars):,}")
                                day_tab_labels = [f"{r['day']} ({r['stops']})" for r in wk_routes]
                                day_tabs_inner = st.tabs(day_tab_labels)
                                for d_tab_idx, day_route in enumerate(wk_routes):
                                    with day_tabs_inner[d_tab_idx]:
                                        r_data = day_route["rows"]
                                        rgb = day_route["color"]
                                        dc1, dc2, dc3, dc4, dc5 = st.columns(5)
                                        dc1.metric("Stops", day_route["stops"])
                                        dc2.metric("Exp. Cases", round(day_route["ev"], 1))
                                        dc3.metric("Exp. Revenue", f"${round(day_route['dollars']):,}")
                                        first_eta = r_data[0]["Time"] if r_data else "β€”"
                                        last_eta = r_data[-1]["Time"] if r_data else "β€”"
                                        dc4.metric("Window", f"{first_eta} β†’ {last_eta}")
                                        dc5.metric("🏭 Delivery From", f"{day_route.get('delivery_wh', 'β€”')} (~{day_route.get('delivery_loop', 0)} mi)")
                                        display_cols = ["#", "Time", "Store", "Prob", "Exp.$", "ROV", "Trend", "Freq", "Days Since", "Drive", "Service"]
                                        st.dataframe(pd.DataFrame(r_data)[display_cols], use_container_width=True, hide_index=True)
                                        long_gaps = []
                                        prev_pt = {"lat": day_route["depot_lat"], "lon": day_route["depot_lon"], "Store": "Home"}
                                        for p in r_data:
                                            gap = _f9t84azyt(prev_pt["lat"], prev_pt["lon"], p["lat"], p["lon"])
                                            if gap > MAX_GAP_MILES:
                                                long_gaps.append(f"{prev_pt['Store']} β†’ {p['Store']} ({gap:.1f} mi)")
                                            prev_pt = p
                                        if long_gaps:
                                            st.warning(f"⚠️ {len(long_gaps)} gap(s) exceed {MAX_GAP_MILES} mi: {', '.join(long_gaps[:3])}")
                                        if len(r_data) >= 1:
                                            map_pts = []
                                            for p in r_data:
                                                map_pts.append({
                                                    "lat": p["lat"], "lon": p["lon"],
                                                    "name": p["Store"],
                                                    "stop": p["stop_label"],
                                                    "info": f"Stop {p['stop_label']} | {p['Store']} | ETA: {p['Time']} | Exp: {p['Exp.$']}",
                                                })
                                            home_pt = {
                                                "lat": day_route["depot_lat"],
                                                "lon": day_route["depot_lon"],
                                                "name": f"{rep} Home",
                                                "stop": "H",
                                                "info": f"Home Base - {rep}",
                                            }
                                            path_coords = [[home_pt["lon"], home_pt["lat"]]] + [[p["lon"], p["lat"]] for p in map_pts]
                                            all_pts = [home_pt] + map_pts
                                            avg_lat = sum(p["lat"] for p in all_pts) / len(all_pts)
                                            avg_lon = sum(p["lon"] for p in all_pts) / len(all_pts)
                                            st.pydeck_chart(pdk.Deck(
                                                layers=[
                                                    pdk.Layer("PathLayer",
                                                              data=[{"path": path_coords}],
                                                              get_path="path",
                                                              get_color=rgb + [180],
                                                              width_scale=20, get_width=4),
                                                    pdk.Layer("ScatterplotLayer",
                                                              data=all_pts,
                                                              get_position="[lon, lat]",
                                                              get_color=rgb + [240],
                                                              get_radius=350,
                                                              radius_min_pixels=10,
                                                              pickable=True),
                                                    pdk.Layer("TextLayer",
                                                              data=all_pts,
                                                              get_position="[lon, lat]",
                                                              get_text="stop",
                                                              get_color=[255, 255, 255, 255],
                                                              get_size=14),
                                                ],
                                                initial_view_state=pdk.ViewState(
                                                    latitude=avg_lat, longitude=avg_lon,
                                                    zoom=9.5, pitch=0),
                                                tooltip={"text": "{info}"},
                                                map_style="light",
                                            ), use_container_width=True)
                                st.markdown("---")
                                st.markdown(f"#### πŸ—ΊοΈ Week {wk_num} β€” Full Territory Overview")
                                week_layers = []
                                week_all_pts = []
                                for day_route in wk_routes:
                                    rgb = day_route["color"]
                                    r_data = day_route["rows"]
                                    path_coords = [[day_route["depot_lon"], day_route["depot_lat"]]] + [[p["lon"], p["lat"]] for p in r_data]
                                    week_layers.append(pdk.Layer("PathLayer",
                                                                 data=[{"path": path_coords}],
                                                                 get_path="path",
                                                                 get_color=rgb + [120],
                                                                 width_scale=20, get_width=3))
                                    day_pts = [{
                                        "lat": p["lat"], "lon": p["lon"],
                                        "name": p["Store"], "stop": p["stop_label"],
                                        "info": f"{day_route['day']}: {p['Store']} | {p['Time']}",
                                    } for p in r_data]
                                    week_layers.append(pdk.Layer("ScatterplotLayer",
                                                                 data=day_pts,
                                                                 get_position="[lon, lat]",
                                                                 get_color=rgb + [220],
                                                                 get_radius=280,
                                                                 radius_min_pixels=6,
                                                                 pickable=True))
                                    week_all_pts.extend(day_pts)
                                if week_all_pts:
                                    avg_lat = sum(p["lat"] for p in week_all_pts) / len(week_all_pts)
                                    avg_lon = sum(p["lon"] for p in week_all_pts) / len(week_all_pts)
                                    st.pydeck_chart(pdk.Deck(
                                        layers=week_layers,
                                        initial_view_state=pdk.ViewState(
                                            latitude=avg_lat, longitude=avg_lon,
                                            zoom=8.5, pitch=0),
                                        tooltip={"text": "{info}"},
                                        map_style="light",
                                    ), use_container_width=True)
                                    legend_items = []
                                    for dr in wk_routes:
                                        c = dr["color"]
                                        legend_items.append(
                                            f'<span style="display:inline-block;width:12px;height:12px;'
                                            f'border-radius:50%;background:rgb({c[0]},{c[1]},{c[2]});'
                                            f'margin-right:6px;vertical-align:middle;"></span>'
                                            f'<span style="font-weight:600;margin-right:16px;">'
                                            f'{dr["day"]} ({dr["stops"]})</span>'
                                        )
                                    st.markdown(" ".join(legend_items), unsafe_allow_html=True)
            else:
                st.error("❌ Solver could not find a viable solution. Try adjusting constraints.")
    st.divider()
    st.subheader("🚨 The 'One-More-Stop' Hustle Finder")
    all_stores = conn.execute("SELECT name, lat, lon, client_code, customer_id FROM clients WHERE active = 1 AND lat != 0").fetchall()
    store_names = [s["name"] for s in all_stores]
    current_location = st.selectbox("Where are you right now?", ["Select a store..."] + store_names)
    if current_location != "Select a store...":
        ref_store = next(s for s in all_stores if s["name"] == current_location)
        nearby = []
        for s in all_stores:
            if s["name"] != current_location:
                miles = _f9t84azyt(ref_store["lat"], ref_store["lon"], s["lat"], s["lon"])
                if miles <= 10.0:
                    nearby.append({"name": s["name"], "miles": round(miles, 1),
                                   "code": s["client_code"], "customer_id": s["customer_id"]})
        if nearby:
            codes = list(set([n["code"] for n in nearby] + [n["customer_id"] for n in nearby if n["customer_id"]]))
            metrics = _fjxepq85j(conn, codes, rolling_days=90)
            for n in nearby:
                m = metrics.get(n["customer_id"]) or metrics.get(n["code"]) or {}
                lv = m.get("last_visit")
                days_since = (today - datetime.datetime.strptime(lv, "%Y-%m-%d").date()).days if lv else 999
                prob, _, exp_cases, _, exp_dollars = _fsg65kxvf(m, days_since)
                n["Exp Cases"] = exp_cases
                n["Exp $"] = f"${round(exp_dollars, 2):,}"
                n["ROV"] = f"${m.get('rov', 0):,.0f}"
                n["Prob"] = f"{int(prob*100)}%"
                n["Trend"] = m.get("trend", "β€”")
            nearby.sort(key=lambda x: x["Exp Cases"], reverse=True)
            st.success("🎯 **Top targets within 10 miles:**")
            st.dataframe(pd.DataFrame(nearby[:5]).drop(columns=['code', 'customer_id']), use_container_width=True)
        else:
            st.info("No active accounts within 10 miles.")
    conn.close()

elif app_mode == "πŸ“¦ Delivery Route Builder":
    st.subheader("πŸ“¦ Delivery Route Builder")
    st.write("Automatically builds warehouse delivery routes from recent sales orders. Select a date range to pull orders, then generate optimized truck routes per warehouse.")
    if client_count == 0:
        st.warning("Database empty. Run Data Sync first.")
        st.stop()
    _dw7k = {
        "Greensboro (GSO)": {"lat": 36.046, "lon": -79.773, "address": "156 Industrial Ave, Greensboro, NC 27406"},
        "Wilmington (WILM)": {"lat": 34.269, "lon": -77.935, "address": "1536 Castle Hayne Rd, Wilmington, NC 28401"},
        "Sumter (SUMT)": {"lat": 33.918, "lon": -80.328, "address": "50 Commerce St, Sumter, SC 29150"},
    }
    conn = _fpbhsahxt()
    today = datetime.date.today()
    with st.sidebar:
        st.header("πŸ“¦ Delivery Settings")
        st.markdown("**Order Window**")
        del_start = st.date_input("Orders From", today - datetime.timedelta(days=3), key="del_start")
        del_end = st.date_input("Orders To", today, key="del_end")
        st.divider()
        st.markdown("**Truck Constraints**")
        truck_capacity = st.slider("Max Cases Per Truck", 100, 2000, 800, step=50,
                                   help="Total case capacity of delivery vehicle")
        truck_max_stops = st.slider("Max Stops Per Truck", 5, 40, 20)
        truck_max_hours = st.slider("Max Delivery Hours", 4.0, 14.0, 10.0, step=0.5)
        mins_per_case = st.slider("Service Minutes Per Case", 0.5, 3.0, 1.5, step=0.25,
                                  help="Unloading + check-in time per case at each stop")
        base_stop_mins = st.slider("Base Minutes Per Stop", 5, 30, 15,
                                   help="Fixed overhead per stop (parking, paperwork, check-in)")
        st.divider()
        st.markdown("**πŸš› Truck Profile** (26ft Box Truck)")
        truck_height = st.number_input("Height (meters)", 2.0, 5.0, 4.0, step=0.1,
                                        help="26ft box truck = 4.0m (13'2\"). Avoids low bridges.")
        truck_weight = st.number_input("Gross Weight (kg)", 3500, 40000, 11800, step=500,
                                        help="26ft box truck GVWR = 11,800 kg (26,000 lbs). Avoids weight-restricted roads.")
        truck_length = st.number_input("Length (meters)", 5.0, 20.0, 10.0, step=0.5,
                                        help="26ft box + cab = 10.0m (33 ft). Avoids tight turns.")
        truck_width = st.number_input("Width (meters)", 2.0, 3.5, 2.6, step=0.05,
                                       help="26ft box truck = 2.6m (8'6\"). Avoids narrow roads.")
        
        if TOMTOM_API_KEY:
            st.success("πŸš› TomTom Truck API: Connected")
        else:
            st.warning("⚠️ No TomTom key. Using estimated truck times. Add TOMTOM_API_KEY to secrets for real bridge/weight/traffic data.")
    orders = conn.execute("""
        SELECT f.client_code, f.visit_date, SUM(f.cases) as total_cases,
               SUM(f.dollar_value) as total_dollars, COUNT(*) as order_count,
               c.customer_id, c.name, c.lat, c.lon,
               c.street_address, c.city, c.tag, c.territory
        FROM forms f
        JOIN clients c ON (f.client_code = c.customer_id OR f.client_code = c.client_code)
        WHERE f.is_order = 1
          AND f.visit_date >= ? AND f.visit_date <= ?
          AND c.lat != 0 AND c.lon != 0
          AND f.cases > 0
        GROUP BY f.client_code
        ORDER BY total_cases DESC
    """, (str(del_start), str(del_end))).fetchall()
    if not orders:
        st.info(f"No orders found between {del_start} and {del_end}. Try expanding the date range or running a Data Sync.")
        conn.close()
        st.stop()
    delivery_stops = []
    for o in orders:
        best_wh, best_dist = list(_dw7k.keys())[0], 999
        for wh_name, wh_loc in _dw7k.items():
            d = _f9t84azyt(o["lat"], o["lon"], wh_loc["lat"], wh_loc["lon"])
            if d < best_dist:
                best_wh, best_dist = wh_name, d
        cases = o["total_cases"] or 0
        svc_time = base_stop_mins + int(cases * mins_per_case)
        delivery_stops.append({
            "code": o["client_code"], "cust_id": o["customer_id"] or o["client_code"],
            "name": o["name"], "lat": o["lat"], "lon": o["lon"],
            "address": f"{o['street_address']}, {o['city']}",
            "cases": cases, "dollars": o["total_dollars"] or 0,
            "svc_time": svc_time, "warehouse": best_wh,
            "wh_dist": round(best_dist, 1), "order_date": o["visit_date"],
        })
    total_orders = len(delivery_stops)
    total_cases = sum(s["cases"] for s in delivery_stops)
    total_dollars = sum(s["dollars"] for s in delivery_stops)
    st.markdown("---")
    s1, s2, s3, s4 = st.columns(4)
    s1.metric("Orders to Deliver", total_orders)
    s2.metric("Total Cases", f"{total_cases:,}")
    s3.metric("Total Revenue", f"${total_dollars:,.0f}")
    s4.metric("Date Range", f"{del_start} β†’ {del_end}")
    st.markdown("### πŸ“‹ Assign Stores to Routes")
    st.write("Edit the **Route** column to group stores. Each route becomes a separate truck run.")
    auto_route = 1
    running_cases = 0
    running_stops = 0
    for s in delivery_stops:
        if running_cases + s["cases"] > truck_capacity or running_stops >= truck_max_stops:
            auto_route += 1
            running_cases = 0
            running_stops = 0
        s["auto_route"] = auto_route
        running_cases += s["cases"]
        running_stops += 1
    editor_df = pd.DataFrame({
        "Include": [True] * len(delivery_stops),
        "Route": [s["auto_route"] for s in delivery_stops],
        "Store": [s["name"] for s in delivery_stops],
        "Address": [s["address"] for s in delivery_stops],
        "Cases": [s["cases"] for s in delivery_stops],
        "Est. $": [f"${s['dollars']:,.0f}" for s in delivery_stops],
        "Service": [f"{s['svc_time']}m" for s in delivery_stops],
        "Nearest WH": [s["warehouse"] for s in delivery_stops],
    })
    edited = st.data_editor(
        editor_df, hide_index=True, use_container_width=True,
        disabled=["Store", "Address", "Cases", "Est. $", "Service", "Nearest WH"],
        column_config={
            "Include": st.column_config.CheckboxColumn("βœ…", default=True),
            "Route": st.column_config.NumberColumn("Route #", min_value=1, max_value=20, step=1),
        },
    )
    for i, s in enumerate(delivery_stops):
        s["include"] = edited.iloc[i]["Include"]
        s["route_num"] = int(edited.iloc[i]["Route"])
    active_stops = [s for s in delivery_stops if s.get("include", True)]
    if not active_stops:
        st.warning("No stores selected.")
        conn.close()
        st.stop()
    route_groups = {}
    for s in active_stops:
        route_groups.setdefault(s["route_num"], []).append(s)
    st.markdown("**Route Summary:**")
    summary_cols = st.columns(min(len(route_groups), 5))
    for idx, (rnum, stops) in enumerate(sorted(route_groups.items())):
        rc = sum(s["cases"] for s in stops)
        pct = int(rc / truck_capacity * 100) if truck_capacity > 0 else 0
        color = "🟒" if pct <= 85 else "🟑" if pct <= 100 else "πŸ”΄"
        with summary_cols[idx % len(summary_cols)]:
            st.markdown(f"**Route {rnum}**: {len(stops)} stops | {rc:,} cases | {color} {pct}%")
    selected_wh = st.selectbox("🏭 Departing Warehouse", list(_dw7k.keys()))
    if st.button("πŸš› BUILD DELIVERY ROUTES", type="primary", use_container_width=True):
        with st.spinner("Optimizing each route..."):
            wh_loc = _dw7k[selected_wh]
            all_delivery_routes = {}
            for route_num, route_stops in sorted(route_groups.items()):
                route_label = f"Route {route_num}"
                nodes = [{"name": f"🏭 {selected_wh}", "lat": wh_loc["lat"], "lon": wh_loc["lon"], "svc_time": 0, "cases": 0}]
                for s in route_stops:
                    nodes.append({"name": s["name"], "lat": s["lat"], "lon": s["lon"],
                                  "svc_time": s["svc_time"], "cases": s["cases"],
                                  "address": s["address"], "dollars": s["dollars"], "code": s["cust_id"]})
                size = len(nodes)
                if size < 2: continue
                
                # 🚨 CALLING THE UNIFIED TOMTOM ENGINE
                truck_params = {
                    "vehicleHeight": float(truck_height),
                    "vehicleWeight": int(truck_weight),
                    "vehicleLength": float(truck_length),
                    "vehicleWidth": float(truck_width),
                    "vehicleLoadType": "otherHazmatGeneral"
                }
                _tm, used_truck_api, engine_name = _build_unified_matrix(nodes, use_api=True, engine_type="truck", truck_params=truck_params)
                
                manager = pywrapcp.RoutingIndexManager(size, 1, [0], [0])
                routing = pywrapcp.RoutingModel(manager)
                def del_time_cb(fi, ti, tm=_tm, nd=nodes, mgr=manager):
                    return tm[mgr.IndexToNode(fi)][mgr.IndexToNode(ti)] + nd[mgr.IndexToNode(ti)]["svc_time"]
                tcb = routing.RegisterTransitCallback(del_time_cb)
                routing.SetArcCostEvaluatorOfAllVehicles(tcb)
                routing.AddDimension(tcb, 30, int(truck_max_hours * 60), False, 'DT')
                for i in range(1, size):
                    routing.AddDisjunction([manager.NodeToIndex(i)], 100000)
                sp = pywrapcp.DefaultRoutingSearchParameters()
                sp.first_solution_strategy = routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC
                sp.local_search_metaheuristic = routing_enums_pb2.LocalSearchMetaheuristic.GUIDED_LOCAL_SEARCH
                sp.time_limit.seconds = 3
                solution = routing.SolveWithParameters(sp)
                if solution:
                    td = routing.GetDimensionOrDie('DT')
                    _ro = []
                    index = routing.Start(0)
                    t_drive, t_cases, t_dollars, prev_ni, stop_num = 0, 0, 0.0, 0, 0
                    while not routing.IsEnd(index):
                        ni = manager.IndexToNode(index)
                        arr = solution.Value(td.CumulVar(index))
                        if ni > 0:
                            stop_num += 1
                            n = nodes[ni]
                            t_cases += n["cases"]
                            t_dollars += n.get("dollars", 0)
                            drv = _tm[prev_ni][ni]
                            t_drive += drv
                            _ro.append({
                                "#": stop_num, "Time": _fc11ertj5(arr + 360),
                                "Store": n["name"], "Address": n.get("address", ""),
                                "Cases": n["cases"], "Service": f"{n['svc_time']}m",
                                "Drive": f"{drv}m", "lat": n["lat"], "lon": n["lon"],
                                "stop_label": f"#{stop_num}", "code": n.get("code", ""),
                                "info": f"Stop #{stop_num} | {n['name']} | {n['cases']} cases | ETA: {_fc11ertj5(arr + 360)}",
                            })
                        prev_ni = ni
                        index = solution.Value(routing.NextVar(index))
                    if _ro:
                        end_t = solution.Value(td.CumulVar(routing.End(0)))
                        all_delivery_routes[route_label] = {
                            "stops": _ro, "total_cases": t_cases,
                            "total_dollars": t_dollars, "total_drive": t_drive,
                            "end_time": _fc11ertj5(end_t + 360),
                            "stop_count": len(_ro), "engine": engine_name,
                        }
            if all_delivery_routes:
                tot_stops = sum(r["stop_count"] for r in all_delivery_routes.values())
                tot_cases = sum(r["total_cases"] for r in all_delivery_routes.values())
                st.success(f"βœ… {len(all_delivery_routes)} route(s) optimized! {tot_stops} stops | {tot_cases:,} cases")
                if used_truck_api:
                    st.info(f"πŸš› {engine_name} β€” bridge heights, weight limits, live traffic applied.")
                route_tabs = st.tabs(list(all_delivery_routes.keys()))
                dcolors = [[231,76,60], [52,152,219], [46,204,113], [241,196,15], [155,89,182], [26,188,156]]
                all_ov_pts = []
                for rt_idx, (rl, rd) in enumerate(all_delivery_routes.items()):
                    with route_tabs[rt_idx]:
                        rgb = dcolors[rt_idx % len(dcolors)]
                        sd = rd["stops"]
                        mc1, mc2, mc3, mc4, mc5 = st.columns(5)
                        mc1.metric("Stops", rd["stop_count"])
                        mc2.metric("Cases", f"{rd['total_cases']:,}")
                        mc3.metric("Capacity", f"{int(rd['total_cases']/truck_capacity*100)}%")
                        mc4.metric("Revenue", f"${rd['total_dollars']:,.0f}")
                        mc5.metric("Return", rd["end_time"])
                        dcols = ["#", "Time", "Store", "Address", "Cases", "Drive", "Service"]
                        st.dataframe(pd.DataFrame(sd)[dcols], use_container_width=True, hide_index=True)
                        if sd:
                            whp = {"lat": wh_loc["lat"], "lon": wh_loc["lon"], "name": selected_wh, "stop": "WH", "info": f"Warehouse: {selected_wh}"}
                            mpts = [{"lat": s["lat"], "lon": s["lon"], "name": s["Store"], "stop": s["stop_label"], "info": s["info"]} for s in sd]
                            apts = [whp] + mpts
                            pth = [[whp["lon"], whp["lat"]]] + [[p["lon"], p["lat"]] for p in mpts] + [[whp["lon"], whp["lat"]]]
                            alat = sum(p["lat"] for p in apts) / len(apts)
                            alon = sum(p["lon"] for p in apts) / len(apts)
                            st.pydeck_chart(pdk.Deck(
                                layers=[
                                    pdk.Layer("PathLayer", data=[{"path": pth}], get_path="path", get_color=rgb+[180], width_scale=20, get_width=4),
                                    pdk.Layer("ScatterplotLayer", data=apts, get_position="[lon, lat]", get_color=rgb+[240], get_radius=350, radius_min_pixels=10, pickable=True),
                                    pdk.Layer("TextLayer", data=apts, get_position="[lon, lat]", get_text="stop", get_color=[255,255,255,255], get_size=14),
                                ],
                                initial_view_state=pdk.ViewState(latitude=alat, longitude=alon, zoom=9.5),
                                tooltip={"text": "{info}"}, map_style="light",
                            ), use_container_width=True)
                            all_ov_pts.extend([{"lat": s["lat"], "lon": s["lon"], "name": s["Store"],
                                                "info": f"{rl}: {s['Store']} | {s['Cases']} cases"} for s in sd])
                if all_ov_pts:
                    st.markdown("---")
                    st.markdown(f"#### πŸ—ΊοΈ All Routes β€” {selected_wh}")
                    ovl = []
                    for ri, (rl, rd) in enumerate(all_delivery_routes.items()):
                        rgb = dcolors[ri % len(dcolors)]
                        sd = rd["stops"]
                        pth = [[wh_loc["lon"], wh_loc["lat"]]] + [[s["lon"], s["lat"]] for s in sd] + [[wh_loc["lon"], wh_loc["lat"]]]
                        ovl.append(pdk.Layer("PathLayer", data=[{"path": pth}], get_path="path", get_color=rgb+[120], width_scale=20, get_width=3))
                        pts = [{"lat": s["lat"], "lon": s["lon"], "name": s["Store"], "info": f"{rl}: {s['Store']} | {s['Cases']} cases"} for s in sd]
                        ovl.append(pdk.Layer("ScatterplotLayer", data=pts, get_position="[lon, lat]", get_color=rgb+[220], get_radius=280, radius_min_pixels=6, pickable=True))
                    alat = sum(p["lat"] for p in all_ov_pts) / len(all_ov_pts)
                    alon = sum(p["lon"] for p in all_ov_pts) / len(all_ov_pts)
                    st.pydeck_chart(pdk.Deck(layers=ovl, initial_view_state=pdk.ViewState(latitude=alat, longitude=alon, zoom=8.5), tooltip={"text": "{info}"}, map_style="light"), use_container_width=True)
                    legend = " ".join([f'<span style="display:inline-block;width:12px;height:12px;border-radius:50%;background:rgb({dcolors[i%len(dcolors)][0]},{dcolors[i%len(dcolors)][1]},{dcolors[i%len(dcolors)][2]});margin-right:6px;vertical-align:middle;"></span><span style="font-weight:600;margin-right:16px;">{rl} ({rd["stop_count"]} stops, {rd["total_cases"]} cases)</span>' for i, (rl, rd) in enumerate(all_delivery_routes.items())])
                    st.markdown(legend, unsafe_allow_html=True)
            else:
                st.error("❌ Solver failed. Try relaxing constraints or reassigning routes.")
    conn.close()