File size: 70,095 Bytes
34be7eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
from __future__ import annotations

import hashlib
import html
import json
import os
import re
import secrets
from datetime import date
from pathlib import Path
from typing import Any
from urllib.parse import parse_qs, urlparse

from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse, Response
from starlette.staticfiles import StaticFiles

from backend.business import read_draft, save_draft, utc_now
from websitebench.site_backend import SiteBackend, load_runtime


ROOT = Path(__file__).resolve().parent
STATIC_DIR = ROOT / "static"
SITE_ROOT = ROOT.parent
SITE_ID = "autoslash"
COOKIE_FALLBACK = "__Host-websitebench-autoslash"
REFERENCE_PAGE_FILES = {
    "story": STATIC_DIR / "site" / "reference-pages" / "story.html",
    "how": STATIC_DIR / "site" / "reference-pages" / "how.html",
    "help": STATIC_DIR / "site" / "reference-pages" / "help.html",
    "coupons": STATIC_DIR / "site" / "reference-pages" / "coupons.html",
    "quote-home": STATIC_DIR / "site" / "reference-pages" / "quote-home.html",
    "quote-vehicle": STATIC_DIR / "site" / "reference-pages" / "quote-vehicle.html",
    "quote-memberships": STATIC_DIR / "site" / "reference-pages" / "quote-memberships.html",
    "quote-contact": STATIC_DIR / "site" / "reference-pages" / "quote-contact.html",
}
CONTENT_SECURITY_POLICY = (
    "default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; "
    "script-src 'self'; connect-src 'self'; font-src 'self' data:; "
    "frame-ancestors 'none'; base-uri 'self'; form-action 'self'"
)
EMAIL_RE = re.compile(r"^[^@\s]{1,128}@[^@\s]{1,190}$")
COMPANIES = (
    "Abbycar", "Ace", "ACTIVE Car Rental", "ADA", "addCar", "Adobe",
    "Advantage", "AirCar", "Alamo", "Alquicoche Rent a Car",
    "America Car Rental", "AmiGo Rent a Car", "Autatlantis", "Autocandia",
    "AUTOMARKET Rent a Car", "AutoRent", "Autos Menorca", "AutoUnion",
    "AutoVia", "Avec Car Rentals", "Avis", "Avro Rent a Car", "Bargain",
    "BLUU Car Rental", "Bravacar", "Bravo Rent a Car", "B-Rent",
    "Buchbinder", "Budget", "CarGini", "CarQ", "Carwiz", "Centauro", "Cicar",
    "City Car Rental", "Click and Rent", "DIRENT", "Dollar", "Drivalia",
    "Drive Car Rental", "Drive On Holidays", "Drive Rent a Car",
    "Driving Force", "Easirent", "East Coast Car Rentals",
    "EasyCar Costa Rica", "Economy Rent-a-Car", "Ecovia", "Enterprise",
    "Essence Car Rental", "Europcar", "EveryCar", "EXER", "FairCar Rental",
    "Felirent", "Firefly", "First Car Mauritius", "Flexways", "Flizzr Cyprus",
    "Foco", "Fox", "GetYourCar", "Global Rent a Car", "Go By Car",
    "Goldcar rental", "GoRentalsNZ", "Green Motion", "GRS Car Rental",
    "Guadeloupe Rental", "Guerin", "Hawk Rent a Car", "Hemingways Travel",
    "Hertz", "Hiper Rent a Car", "Ilha Verde Rent a car", "InterRent",
    "Island car rentals", "Italy Car Rent", "Jumbo Car", "keddy by Europcar",
    "Kenings", "Key'n Go", "KK Rent-A-Car", "Lagorent", "Leasys", "LetsDrive",
    "Localiza", "Locationauto", "Maggiore", "Mas by Mex Rent-A-Car",
    "Megadrive", "Mex Rent-a-Car", "Midway", "Movida Rent A Car",
    "Naniko Rent a Car", "National", "NextCar", "Nico Nico Rent a Car",
    "Nippon Rent a Car", "Nokta Rent A Car", "Noleggiare", "Nordic Car Rental",
    "Nova Rent a Car", "NU", "Offer Car Hire", "OK Mobility", "OPORent",
    "Orlando Rent A Car", "Oryx Rent a Car", "Other (Not Listed)",
    "OtoQ Car Rental", "Otorento", "Owners Cars", "Pandora", "Panek",
    "Payless", "Pricecarz", "Priceless", "RecordGo", "RenMartinique Rental",
    "Rentacar", "RentByCar", "RENTMOTORS", "Rentscape", "RightCars", "Routes",
    "S S TRAVELS", "Scandia Rent", "Schiller Rent a Car", "Sicily By Car",
    "Sixt", "SR Rent a Car", "StarCar", "State Van Rental",
    "Street Rent a Car", "Stride", "SurPrice", "Tangerine Rent a Car",
    "Thai Rent A Car", "Thrifty", "Top Rent a Car", "TopCar", "Travelcar",
    "Turisprime", "Unidas", "United International Car Rentals",
    "United Rent A Car", "U-Save", "Viaggiare", "WheeGo", "Yours Rent A Car",
    "Zezgo",
)
VEHICLE_LABELS = {
    "ACAR": "Least expensive option",
    "ECAR": "Economy car",
    "CCAR": "Compact car",
    "ICAR": "Midsize car",
    "SCAR": "Standard car",
    "FCAR": "Full-size car",
    "PCAR": "Premium car",
    "LCAR": "Luxury car",
    "CFAR": "Compact SUV",
    "IFAR": "Midsize SUV",
    "SFAR": "Standard SUV",
    "PGAR": "Premium SUV",
    "FFAR": "Full-size SUV",
    "PFAR": "Luxury SUV",
    "MVAR": "Minivan",
    "RVAR": "Passenger van",
    "IPAR": "Pickup truck",
}
COUNTRY_LABELS = {"US": "United States"}
AFFILIATION_LABELS = {
    "3": "American Express",
    "25": "Amex Platinum",
    "6": "Discover",
    "9": "Mastercard",
    "23": "Mastercard World Elite",
    "11": "Visa",
    "24": "Visa Infinite/Signature",
}

_BACKEND: SiteBackend | None = None
_BACKEND_KEY: tuple[str, str] | None = None


def _backend() -> SiteBackend:
    global _BACKEND, _BACKEND_KEY
    runtime_path = Path(
        os.environ.get(
            "WEBSITEBENCH_SITE_BACKEND_RUNTIME",
            str(SITE_ROOT / "backend" / "runtime.json"),
        )
    ).resolve()
    database_override = os.environ.get("WEBSITEBENCH_SITE_BACKEND_DATABASE", "")
    key = (str(runtime_path), database_override)
    if _BACKEND is not None and _BACKEND_KEY == key:
        return _BACKEND
    runtime = load_runtime(runtime_path)
    if database_override:
        database_path = Path(database_override).resolve()
        if database_path.name != runtime.database_filename:
            raise RuntimeError("deployed database filename does not match runtime")
        backend = SiteBackend.open(
            json.loads(runtime_path.read_text(encoding="utf-8")),
            data_root=database_path.parent,
            migration_hook=__import__(
                "backend.business", fromlist=["migrate_v1"]
            ).migrate_v1,
        )
        if backend.lifecycle.database_path != database_path:
            raise RuntimeError("deployed database path mismatch")
    else:
        backend = SiteBackend.open(
            runtime_path,
            migration_hook=__import__(
                "backend.business", fromlist=["migrate_v1"]
            ).migrate_v1,
        )
    backend.lifecycle.initialize()
    _BACKEND = backend
    _BACKEND_KEY = key
    return backend


def _cookie_name(request: Request) -> str:
    configured = str(_backend().session_cookie.get("name", COOKIE_FALLBACK))
    if request.url.scheme == "https":
        return configured
    return configured.removeprefix("__Host-")


def _digest(value: str, namespace: str = "value") -> str:
    return hashlib.sha256(f"autoslash:{namespace}:{value}".encode()).hexdigest()


def _owner(request: Request) -> tuple[str, str | None]:
    backend = _backend()
    cookie_name = _cookie_name(request)
    token = request.cookies.get(cookie_name)
    now = utc_now()
    with backend.lifecycle.connection(transaction=True) as connection:
        if token and len(token) >= 32:
            token_digest = _digest(token, "session")
            row = connection.execute(
                "SELECT owner_id FROM autoslash_sessions WHERE token_digest=?",
                (token_digest,),
            ).fetchone()
            if row is not None:
                connection.execute(
                    "UPDATE autoslash_sessions SET last_seen_at=? WHERE token_digest=?",
                    (now, token_digest),
                )
                return str(row["owner_id"]), None
        token = secrets.token_urlsafe(32)
        owner_id = f"owner_{secrets.token_hex(12)}"
        connection.execute(
            "INSERT INTO autoslash_sessions(token_digest,owner_id,created_at,last_seen_at) "
            "VALUES (?,?,?,?)",
            (_digest(token, "session"), owner_id, now, now),
        )
        return owner_id, token


def _finish(request: Request, response: Response, new_token: str | None) -> Response:
    if new_token:
        response.set_cookie(
            _cookie_name(request),
            new_token,
            httponly=True,
            secure=request.url.scheme == "https",
            samesite="lax",
            path="/",
        )
    response.headers["content-security-policy"] = CONTENT_SECURITY_POLICY
    response.headers["x-content-type-options"] = "nosniff"
    response.headers["referrer-policy"] = "same-origin"
    return response


async def _form_values(request: Request) -> dict[str, list[str]]:
    raw = (await request.body()).decode("utf-8", errors="replace")
    return parse_qs(raw, keep_blank_values=True)


def _form_value(values: dict[str, list[str]], key: str, default: str = "") -> str:
    return values.get(key, [default])[0].strip()


def _safe(value: Any) -> str:
    return html.escape(str(value), quote=True)


def _request_id(prefix: str) -> str:
    return f"{prefix}-{secrets.token_hex(5).upper()}"


def _advance_draft(
    connection: sqlite3.Connection,
    table: str,
    owner: str,
    expected_stage: str,
    next_stage: str,
    values: dict[str, object],
) -> bool:
    if table not in {"autoslash_quote_drafts", "autoslash_tracking_drafts"}:
        raise ValueError("unsupported draft table")
    row = connection.execute(
        f"SELECT stage FROM {table} WHERE owner_id=?", (owner,)
    ).fetchone()
    if row is None or row["stage"] != expected_stage:
        return False
    save_draft(connection, table, owner, next_stage, values)
    return True


def _workflow_conflict(title: str, message: str, href: str, view: str) -> HTMLResponse:
    response = _information_page(
        title,
        (message, f'<a class="orange-link" href="{href}">Start again</a>'),
        view,
    )
    response.status_code = 409
    return response


def _display_date(value: object, *, include_time: object = "") -> str:
    raw = str(value)
    match = re.fullmatch(r"(\d{4})-(\d{2})-(\d{2})", raw)
    if not match:
        return raw
    year, month, day = (int(part) for part in match.groups())
    months = (
        "Jan", "Feb", "Mar", "Apr", "May", "Jun",
        "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
    )
    label = f"{months[month - 1]} {day}, {year}"
    return f"{label} at {include_time}" if include_time else label


def _valid_date(value: str) -> bool:
    try:
        date.fromisoformat(value)
    except ValueError:
        return False
    return True


def _valid_time(value: str) -> bool:
    return re.fullmatch(r"(?:[01]\d|2[0-3]):[0-5]\d", value) is not None


def _header() -> str:
    return """
    <header class="clone-header">
      <div class="clone-header-inner">
        <a class="brand" href="/" aria-label="AutoSlash home">
          <img src="/static/site/assets/logo.svg" alt="AutoSlash">
        </a>
        <nav class="desktop-nav" aria-label="Primary">
          <a href="/">Get a Quote</a><span>|</span>
          <a href="/track">Track a Rental</a><span>|</span>
          <a href="/coupons">Coupons</a><span>|</span>
          <a href="/external-link?destination=reviews">Reviews</a><span>|</span>
          <a href="/external-link?destination=blog">Blog</a><span>|</span>
          <button class="about-toggle" type="button" aria-expanded="false">About Us⌄</button>
        </nav>
        <button class="menu-toggle" type="button" aria-expanded="false" aria-controls="mobile-nav">
          <img src="/static/site/assets/icon-mob-hamburger.svg" alt=""><span class="sr-only">Menu</span>
        </button>
        <a class="help-dot" href="/frequently-asked-questions" aria-label="Help">
          <img src="/static/site/assets/icon-question-mark.svg" alt="">
        </a>
      </div>
      <nav id="mobile-nav" class="mobile-nav" aria-label="Mobile navigation" hidden>
        <a href="/">Get a Quote</a><a href="/track">Track a Rental</a>
        <a href="/coupons">Coupons</a><a href="/our-story">Our Story</a>
        <a href="/how-we-do-it">How We Do It</a>
        <a href="/frequently-asked-questions">FAQ</a><a href="/contact-us">Contact Us</a>
      </nav>
      <div class="about-menu" hidden>
        <a href="/our-story">Our Story</a><a href="/how-we-do-it">How We Do It</a>
        <a href="/in-the-news">In the News</a>
        <a href="/frequently-asked-questions">FAQ</a><a href="/contact-us">Contact Us</a>
      </div>
      <a class="mobile-rental-banner" href="/reservations/lookup">
        <small>Need to book a new rental?</small>
        <strong>Click here and we'll find you a great deal!</strong>
      </a>
    </header>
    """


def _footer() -> str:
    return """
    <footer class="clone-footer">
      <div><p>Connect with us:</p><div class="social-dots" aria-label="Social links">
        <a href="/external-link?destination=facebook" aria-label="Facebook"><svg viewBox="0 0 320 512" aria-hidden="true"><path d="M279.14 288l14.22-92.66h-88.91v-60.13c0-25.35 12.42-50.06 52.24-50.06h40.42V6.26S260.43 0 225.36 0c-73.22 0-121.08 44.38-121.08 124.72v70.62H22.89V288h81.39v224h100.17V288z"/></svg></a>
        <a href="/external-link?destination=twitter" aria-label="Twitter"><svg viewBox="0 0 512 512" aria-hidden="true"><path d="M459.37 151.716c.325 4.548.325 9.097.325 13.645 0 138.72-105.583 298.558-298.558 298.558-59.452 0-114.68-17.219-161.137-47.106 8.447.974 16.568 1.299 25.34 1.299 49.055 0 94.213-16.568 130.274-44.832-46.132-.975-84.792-31.188-98.112-72.772 6.498.974 12.995 1.624 19.818 1.624 9.421 0 18.843-1.3 27.614-3.573-48.081-9.747-84.143-51.98-84.143-102.985v-1.299c13.969 7.797 30.214 12.67 47.431 13.319-28.264-18.843-46.781-51.005-46.781-87.391 0-19.492 5.197-37.36 14.294-52.954 51.655 63.675 129.3 105.258 216.365 109.807-1.624-7.797-2.599-15.918-2.599-24.04 0-57.828 46.782-104.934 104.934-104.934 30.213 0 57.502 12.67 76.67 33.137 23.715-4.548 46.456-13.32 66.599-25.34-7.798 24.366-24.366 44.833-46.132 57.827 21.117-2.273 41.584-8.122 60.426-16.243-14.292 20.791-32.161 39.308-52.628 54.253z"/></svg></a>
        <a href="/external-link?destination=youtube" aria-label="YouTube"><svg viewBox="0 0 576 512" aria-hidden="true"><path d="M549.7 124.1c-6.3-23.8-25-42.5-48.6-48.9C458.8 64 288 64 288 64S117.2 64 74.9 75.2c-23.6 6.4-42.3 25.1-48.6 48.9C15 167 15 256.4 15 256.4s0 89.4 11.3 132.3c6.3 23.8 25 41.7 48.6 48.1C117.2 448 288 448 288 448s170.8 0 213.1-11.2c23.6-6.4 42.3-24.3 48.6-48.1 11.3-42.9 11.3-132.3 11.3-132.3s0-89.4-11.3-132.3zM232 336.5v-160l142.7 80-142.7 80z"/></svg></a>
      </div>
      <nav><a href="/our-story">Our Story</a><span>|</span><a href="/external-link?destination=blog">Blog</a><span>|</span>
      <a href="/external-link?destination=reviews">Reviews</a><span>|</span><a href="/coupons">Coupons</a><span>|</span>
      <a href="/frequently-asked-questions">Help</a></nav></div>
      <div class="footer-brand"><img src="/static/site/assets/logo.svg" alt="AutoSlash">
      <p><a href="/privacy-policy">Privacy Policy</a><span>|</span><a href="/terms-of-use">Terms of Use</a>
      <span>|</span> © AutoSlash 2026</p></div>
    </footer>
    """


def _document(title: str, view: str, content: str, *, status_code: int = 200) -> HTMLResponse:
    markup = f"""<!doctype html><html lang="en"><head>
    <meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
    <title>{_safe(title)} | AutoSlash</title>
    <link rel="stylesheet" href="/static/site/autoslash.css">
    <link rel="stylesheet" href="/static/site/navigation.css">
    </head><body data-view="{_safe(view)}">{_header()}{content}{_footer()}
    <script src="/static/site/autoslash.js" defer></script></body></html>"""
    return HTMLResponse(markup, status_code=status_code)


def _field(
    label: str,
    name: str,
    *,
    input_type: str = "text",
    placeholder: str = "",
    value: str = "",
    required: bool = True,
) -> str:
    required_attr = " required" if required else ""
    number_attr = ' step="0.01"' if input_type == "number" else ""
    return (
        f'<label class="field"><span>{_safe(label)}</span>'
        f'<input type="{_safe(input_type)}" name="{_safe(name)}" '
        f'placeholder="{_safe(placeholder)}" value="{_safe(value)}"'
        f'{number_attr}{required_attr}></label>'
    )


def _select(label: str, name: str, options: tuple[str, ...], prompt: str) -> str:
    items = [f'<option value="">{_safe(prompt)}</option>']
    items.extend(f'<option value="{_safe(item)}">{_safe(item)}</option>' for item in options)
    return (
        f'<label class="field"><span>{_safe(label)}</span>'
        f'<select name="{_safe(name)}" required>{"".join(items)}</select></label>'
    )


def _plain_form_page(
    title: str,
    intro: str,
    action: str,
    fields: str,
    *,
    view: str,
    extra: str = "",
) -> HTMLResponse:
    body = f"""<main class="plain-page"><section class="plain-card">
      <h1>{_safe(title)}</h1><p class="plain-intro">{intro}</p>
      <form method="post" action="{_safe(action)}" class="public-form">{fields}
      <button class="orange-button" type="submit">Submit</button></form>{extra}
    </section></main>"""
    return _document(title, view, body)


def _tracking_page(
    stage: int,
    title: str,
    action: str,
    fields: str,
    *,
    message: str = "",
) -> HTMLResponse:
    labels = ("Rental Co.", "Date", "Price", "Deals", "Email")
    progress = "".join(
        f'<li class="{"active" if index <= stage else ""}">{label}</li>'
        for index, label in enumerate(labels, start=1)
    )
    note = f'<p class="form-message" role="alert">{_safe(message)}</p>' if message else ""
    body = f"""<main class="tracking-page">
      <section class="tracking-hero">
        <img class="tracking-car" src="/static/site/assets/car-facing-right-lg@2x.png" alt="">
        <a class="tracking-book-callout" href="/">
          <small>Need to book a new rental?</small>
          <strong>Click here and we'll<br>find you a great deal!</strong>
        </a>
        <section class="tracking-card">
          <ol class="workflow-steps">{progress}</ol>
          <form method="post" action="{_safe(action)}" class="tracking-form">
            <h1>{_safe(title)}</h1>{note}{fields}
            <button class="orange-button" type="submit">Next</button>
          </form>
        </section>
        <a class="tracking-lookup" href="/reservations/lookup">View/Cancel Existing Reservation</a>
      </section>
      <section class="tracking-explainer">
        <a class="tracking-video-link" href="/external-link?destination=video"
           aria-label="Open the AutoSlash savings video">
          <img class="tracking-video" src="/static/site/assets/pic-video-poster@2x.jpg"
               alt="AutoSlash rental savings explainer">
        </a>
        <h2>Just 3 easy steps to save on your car rental:</h2>
        <div class="tracking-tabs"><a href="/">To request a rental quote</a><span>To track a rental</span></div>
        <div class="tracking-steps">
          <article><img src="/static/site/assets/pic-steps-track-1.svg" alt=""><div class="tracking-step-copy"><b>1.</b><p>Tell us the confirmation # <br>and price of your <br>car rental...</p></div></article>
          <article><img src="/static/site/assets/pic-steps-track-2.svg" alt=""><div class="tracking-step-copy"><b>2.</b><p>Our super-smart computers (coded <br>by travel geeks) <br>get to work...</p></div></article>
          <article><img src="/static/site/assets/pic-steps-track-3.svg" alt=""><div class="tracking-step-copy"><b>3.</b><p>You relax! We <br>email you when <br>the price of your <br>rental drops!</p></div></article>
        </div>
      </section>
      <section class="tracking-community">
        <div><h2>Recent Reviews</h2><a href="/external-link?destination=reviews">Review us</a></div>
        <div class="tracking-feed"><h2>AutoSlash Tips</h2><a href="/external-link?destination=blog">Check out our blog</a>
          <article><a href="/external-link?destination=blog">Who Owns Hertz Car Rental?</a><i>August 22, 2026</i>
          <a href="/external-link?destination=blog">What to Know About Car Rentals in North Carolina</a><i>August 22, 2026</i>
          <a href="/external-link?destination=blog">Here’s How to Beat a Pricey Airport Car Rental Rate</a><i>August 22, 2026</i><a class="tracking-card-read-more" href="/external-link?destination=blog">Read more</a></article>
        </div>
        <div class="tracking-news"><h2>In the News</h2><a href="/external-link?destination=press">See all the press</a>
          <article>
            <a href="/external-link?destination=press">All About Autoslash: The #1 Tool to Save on Rental Cars!</a><i>July 29, 2024</i>
            <a href="/external-link?destination=press">5 ON YOUR SIDE: Real deal rental car advice</a><i>July 19, 2024</i>
            <a href="/external-link?destination=press">Beginner’s Guide: Save on Car Rentals with AutoSlash</a><i>May 30, 2024</i><a class="tracking-card-read-more" href="/external-link?destination=press">Read more</a>
          </article>
        </div>
      </section>
      <a class="source-chat-button" href="/contact-us"
         aria-label="Open AutoSlash support"><span aria-hidden="true"><i></i>Help!</span></a>
    </main>"""
    return _document("Track a Rental", "track", body)


def _confirmation(
    title: str,
    message: str,
    request_id: str,
    view: str,
    details: tuple[tuple[str, object], ...] = (),
) -> HTMLResponse:
    summary = ""
    if details:
        rows = "".join(
            f"<div><dt>{_safe(label)}</dt><dd>{_safe(value)}</dd></div>"
            for label, value in details
        )
        summary = f'<dl class="confirmation-summary">{rows}</dl>'
    body = f"""<main class="plain-page"><section class="plain-card confirmation-card">
      <h1>{_safe(title)}</h1><p>{_safe(message)}</p>
      {summary}
      <p class="request-id">Reference: <strong>{_safe(request_id)}</strong></p>
      <div class="local-notice">This offline clone saved the request locally. It did not
      contact the source site, a rental company, an email provider, or a payment service.</div>
      <p><a class="orange-link" href="/">Get another quote</a>
      <a class="text-link" href="/track">Track a rental</a></p>
    </section></main>"""
    return _document(title, view, body)


def _reference_html(kind: str) -> str:
    content = REFERENCE_PAGE_FILES[kind].read_text(encoding="utf-8", errors="ignore")
    content = re.sub(r"<script\b[^>]*>.*?</script>", "", content, flags=re.I | re.S)
    content = re.sub(
        r"<meta\b[^>]*http-equiv\s*=\s*[\"']?content-security-policy[\"']?[^>]*>",
        "",
        content,
        flags=re.I,
    )
    content = re.sub(
        r"<meta\b[^>]*\bname\s*=\s*[\"']?referrer[\"']?[^>]*>",
        "",
        content,
        flags=re.I,
    )
    local_links = {
        "/track": "/track",
        "/coupons": "/coupons",
        "/our-story": "/our-story",
        "/how-we-do-it": "/how-we-do-it",
        "/frequently-asked-questions": "/frequently-asked-questions",
        "/contact-us": "/contact-us",
        "/reservations/lookup": "/reservations/lookup",
        "/privacy-policy": "/privacy-policy",
        "/terms-of-use": "/terms-of-use",
    }
    for path, local in local_links.items():
        content = re.sub(
            rf"https?://(?:www\.)?autoslash\.com{re.escape(path)}(?=[\"'\s<>?#])",
            local,
            content,
            flags=re.I,
        )
    content = re.sub(
        r"https?://(?:www\.)?autoslash\.com(?P<path>/[^\"'\s<>]*)?",
        lambda match: match.group("path") or "/",
        content,
        flags=re.I,
    )
    content = re.sub(
        r"\b(href|action)=(?:[\"'][^\"']*(?:https?:)?//[^\"']*[\"']|[^\s>]*(?:https?:)?//[^\s>]*)",
        r'\1="/external-link?destination=external"',
        content,
        flags=re.I,
    )
    content = re.sub(
        r"url\(\s*[\"']?(?:https?:)?//[^)]*\)", "url(data:,)", content, flags=re.I
    )
    content = content.replace("https://", "about:blank#").replace("http://", "about:blank#")
    actions = {
        "quote-home": "/quote/pickup-location",
        "quote-vehicle": "/quote/vehicle",
        "quote-memberships": "/quote/memberships",
        "quote-contact": "/quote/contact-info",
    }
    if kind in actions:
        content = re.sub(
            r"(<form\b[^>]*\baction=)(?:\"[^\"]*\"|'[^']*'|[^\s>]+)",
            rf'\1"{actions[kind]}"',
            content,
            count=1,
            flags=re.I,
        )
    content = re.sub(
        r"/quote/vehicle/[a-f0-9-]+(?:\?[^\"'\s<>]*)?",
        "/quote/vehicle",
        content,
        flags=re.I,
    )
    content = re.sub(
        r"/quote/memberships/[a-f0-9-]+/(?:true|false)",
        "/quote/memberships",
        content,
        flags=re.I,
    )
    content = re.sub(
        r"/quote/contact-info/[a-f0-9-]+",
        "/quote/contact-info",
        content,
        flags=re.I,
    )
    if kind == "quote-contact":
        content = re.sub(
            r"(<select\b(?=[^>]*\bname=PointOfSaleCountry\b)[^>]*>)\s*</select>",
            r'\1<option value="US" selected>United States</option></select>',
            content,
            count=1,
            flags=re.I,
        )
    if "Which of these credit cards do you have?" in content:
        content = re.sub(
            r'<a\b(?=[^>]*\bclass="[^"]*\bgo-to-step2\b[^"]*")[^>]*>\s*Next\s*</a>',
            '<button type="submit" class="go-to-step2 btn">Next</button>',
            content,
            count=1,
            flags=re.I,
        )
    view = {"quote-home": "home", "quote-vehicle": "quote",
            "quote-memberships": "quote", "quote-contact": "quote"}.get(kind, kind)
    content = re.sub(
        r"<body([^>]*)>",
        lambda match: f'<body{match.group(1)} data-view="{view}" data-reference="true">',
        content,
        count=1,
        flags=re.I,
    )
    if kind == "help":
        content = content.replace(
            "</form>",
            '</form><p class="faq-empty-message" role="status" hidden>'
            'No results. No FAQ answers match your search. '
            '<a href="/frequently-asked-questions">Show all questions</a>.</p>',
            1,
        )
    if kind == "coupons":
        company_matches = re.findall(
            r"\bdata-company=(?:\"([^\"]+)\"|'([^']+)'|([^\s>]+))",
            content,
            flags=re.I,
        )
        companies = sorted(
            {next(part for part in match if part) for match in company_matches}
        )
        options = '<option value="All">All Companies</option>' + "".join(
            f'<option value="{_safe(company)}">{_safe(company)}</option>'
            for company in companies
        )
        content = re.sub(
            r"<select\b(?=[^>]*\bid=coupon-company-select\b)[^>]*>\s*</select>",
            '<select class="custom-select-no-search" id="coupon-company-select" '
            f'aria-label="Filter coupons by company">{options}</select>',
            content,
            count=1,
            flags=re.I,
        )
    mobile_trigger = (
        '<a href="#modal-mobile-menu" class="mobile-logo popup-from-top" '
        'aria-label="Open menu"><img class="mobile-menu-icon" '
        'src="/static/site/assets/icon-mob-hamburger.svg" alt=""></a>'
    )
    content = re.sub(
        r'<a href=#modal-mobile-menu class="mobile-logo popup-from-top sf-hidden">\s*</a>',
        mobile_trigger,
        content,
        count=1,
        flags=re.I,
    )
    mobile_panel = (
        '<div id="modal-mobile-menu" class="modal modal-mobile-menu '
        'mfp-with-anim mfp-hide sf-hidden" aria-hidden="true">'
        '<button type="button" class="mfp-close" aria-label="Close menu">×</button>'
        '<nav class="mobile-menu-nav" aria-label="Mobile primary">'
        '<a href="/">Get a Quote</a><a href="/track">Track a Rental</a>'
        '<a href="/reservations/lookup">View/Cancel Existing Reservation</a>'
        '<a href="/coupons">Coupons</a><a href="/our-story">Our Story</a>'
        '<a href="/how-we-do-it">How We Do It</a>'
        '<a href="/frequently-asked-questions">FAQ</a>'
        '<a href="/contact-us">Contact Us</a></nav></div>'
    )
    content = re.sub(
        r'<div id=modal-mobile-menu class="modal modal-mobile-menu '
        r'mfp-with-anim mfp-hide sf-hidden">\s*</div>',
        mobile_panel,
        content,
        count=1,
        flags=re.I,
    )
    quote_css = (
        '<link rel="stylesheet" href="/static/site/quote-reference.css">'
        if kind.startswith("quote-") else ""
    )
    additions = (
        quote_css
        + '<link rel="stylesheet" href="/static/site/navigation.css">'
        + '<script src="/static/site/reference-interactions.js" defer></script>'
        + '<script src="/static/site/autoslash.js" defer></script>'
    )
    return content.replace("</head>", additions + "</head>", 1)


def _reference_page(kind: str) -> HTMLResponse:
    return HTMLResponse(_reference_html(kind))


def _captured_quote_step(
    action: str, content: str, active_count: int, *, show_next: bool = True
) -> HTMLResponse:
    source = _reference_html("quote-vehicle")
    source = source.replace('action="/quote/vehicle"', f'action="{action}"', 1)
    pane = source.index("<div class=quote-step-pane>") + len("<div class=quote-step-pane>")
    controls = source.index("<div class=nav-controls>", pane)
    source = source[:pane] + content + source[controls:]
    if not show_next:
        source = re.sub(
            r"<input type=submit[^>]*value=Next[^>]*>", "", source, count=1, flags=re.I
        )
    labels = ("Where", "When", "Vehicle", "Deals", "Your details")
    for index, label in enumerate(labels):
        pattern = (
            rf'<li class=(?:"quote-steps-nav-item(?: active)?"|'
            rf'quote-steps-nav-item(?: active)?)[^>]*>{re.escape(label)}</li>'
        )
        replacement = (
            f'<li class="quote-steps-nav-item{" active" if index < active_count else ""}">'
            f"{label}</li>"
        )
        source = re.sub(pattern, replacement, source, count=1)
    return HTMLResponse(source)


app = FastAPI(title="AutoSlash offline clone", docs_url=None, redoc_url=None)
app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")


@app.middleware("http")
async def security_boundary(request: Request, call_next: Any) -> Response:
    if request.method not in {"GET", "HEAD", "OPTIONS"}:
        origin = request.headers.get("origin")
        parsed = urlparse(origin or "")
        if (
            not origin
            or parsed.scheme != request.url.scheme
            or parsed.netloc != request.url.netloc
            or parsed.path not in {"", "/"}
            or parsed.params
            or parsed.query
            or parsed.fragment
        ):
            return JSONResponse(
                {"detail": "same-origin mutation proof required"}, status_code=403
            )
    response = await call_next(request)
    response.headers.setdefault("content-security-policy", CONTENT_SECURITY_POLICY)
    response.headers.setdefault("x-content-type-options", "nosniff")
    response.headers.setdefault("referrer-policy", "same-origin")
    return response


@app.get("/__websitebench/health")
async def websitebench_health() -> dict[str, str]:
    with _backend().lifecycle.connection() as connection:
        connection.execute("SELECT 1").fetchone()
    return {"status": "ok"}


@app.get("/healthz")
async def healthz() -> dict[str, Any]:
    with _backend().lifecycle.connection() as connection:
        connection.execute("SELECT 1").fetchone()
    return {"ok": True, "site_id": SITE_ID}


@app.get("/", include_in_schema=False)
@app.get("/quote", include_in_schema=False)
@app.get("/get-a-quote", include_in_schema=False)
async def home(request: Request) -> Response:
    _, token = _owner(request)
    return _finish(request, _reference_page("quote-home"), token)


@app.get("/quote/pickup-location", include_in_schema=False)
async def pickup_location_entry(request: Request) -> Response:
    return await home(request)


@app.post("/quote/pickup-location", include_in_schema=False)
async def pickup_location(request: Request) -> Response:
    owner, token = _owner(request)
    values = await _form_values(request)
    location_type = _form_value(values, "location_type", "airport")
    local_pickup = _form_value(values, "location")
    airport_pickup = _form_value(values, "airport") or _form_value(
        values, "AirportId-display"
    )
    if location_type == "non-airport" and local_pickup:
        pickup = local_pickup
    else:
        location_type = "airport"
        pickup = airport_pickup
    if not pickup:
        return _finish(request, _reference_page("quote-home"), token)
    with _backend().lifecycle.connection(transaction=True) as connection:
        connection.execute(
            "DELETE FROM autoslash_quote_drafts WHERE owner_id=?", (owner,)
        )
        save_draft(
            connection, "autoslash_quote_drafts", owner, "where",
            {"pickup": pickup, "location_type": location_type},
        )
    content = (
        f'<h2>Do you want to return your rental to the same location?</h2>'
        f'<p><em>({_safe(pickup)})</em></p><div class="choice-grid">'
        '<button class="nav-control-btn nav-control-next btn" type="submit" '
        'name="same_location" value="yes">Yes</button>'
        '<button class="nav-control-btn nav-control-next btn" type="submit" '
        'name="same_location" value="no">No</button></div>'
    )
    return _finish(
        request,
        _captured_quote_step("/quote/dropoff-location", content, 1, show_next=False),
        token,
    )


@app.post("/quote/dropoff-location", include_in_schema=False)
async def quote_dropoff_location(request: Request) -> Response:
    owner, token = _owner(request)
    values = await _form_values(request)
    same = _form_value(values, "same_location", "yes")
    dropoff = _form_value(values, "dropoff")
    with _backend().lifecycle.connection(transaction=True) as connection:
        draft = read_draft(connection, "autoslash_quote_drafts", owner)
        pickup = str(draft.get("pickup", ""))
        if same == "no" and not dropoff:
            content = (
                "<h2>Where will you return the rental?</h2>"
                '<label class="field"><span>Drop-off city or address</span>'
                '<input class="input-large" name="dropoff" '
                'placeholder="city, neighborhood, or address" required></label>'
                '<input type="hidden" name="same_location" value="no">'
            )
            response = _captured_quote_step("/quote/dropoff-location", content, 1)
            return _finish(request, response, token)
        destination = pickup if same == "yes" else dropoff
        if not _advance_draft(
            connection, "autoslash_quote_drafts", owner, "where", "pickup-date",
            {"dropoff": destination, "same_location": same},
        ):
            return _finish(
                request,
                _workflow_conflict(
                    "Start your quote again",
                    "The previous location step is missing or no longer current.",
                    "/", "quote-workflow-required",
                ),
                token,
            )
    content = (
        "<h2>When will you pick up the rental?</h2>"
        '<label class="field"><span>Pickup date</span>'
        '<input class="input-large" type="date" name="pickup_date" required></label>'
        '<label class="field"><span>Pickup time</span>'
        '<input class="input-large" type="time" name="pickup_time" value="12:00" required></label>'
        "<p><strong>Non-airport locations are typically open 8am-5pm Mon-Fri, "
        "8am-12pm Sat, closed Sun.</strong></p>"
    )
    return _finish(
        request, _captured_quote_step("/quote/pickup-date", content, 2), token
    )


@app.get("/quote/pickup-date", include_in_schema=False)
async def quote_pickup_date_get(request: Request) -> Response:
    _, token = _owner(request)
    content = (
        "<h2>When will you pick up the rental?</h2>"
        '<label class="field"><span>Pickup date</span>'
        '<input class="input-large" type="date" name="pickup_date" required></label>'
        '<label class="field"><span>Pickup time</span>'
        '<input class="input-large" type="time" name="pickup_time" value="12:00" required></label>'
    )
    return _finish(
        request, _captured_quote_step("/quote/pickup-date", content, 2), token
    )


@app.post("/quote/pickup-date", include_in_schema=False)
async def quote_pickup_date(request: Request) -> Response:
    owner, token = _owner(request)
    values = await _form_values(request)
    pickup_date = _form_value(values, "pickup_date")
    pickup_time = _form_value(values, "pickup_time", "12:00")
    if not _valid_date(pickup_date) or not _valid_time(pickup_time):
        return await quote_pickup_date_get(request)
    with _backend().lifecycle.connection(transaction=True) as connection:
        if not _advance_draft(
            connection, "autoslash_quote_drafts", owner, "pickup-date", "dropoff-date",
            {"pickup_date": pickup_date, "pickup_time": pickup_time},
        ):
            return _finish(
                request,
                _workflow_conflict(
                    "Start your quote again",
                    "Complete the location steps before choosing dates.",
                    "/", "quote-workflow-required",
                ),
                token,
            )
    content = (
        "<h2>When will you drop off the rental?</h2>"
        '<label class="field"><span>Drop-off date</span>'
        '<input class="input-large" type="date" name="dropoff_date" required></label>'
        '<label class="field"><span>Drop-off time</span>'
        '<input class="input-large" type="time" name="dropoff_time" value="12:00" required></label>'
    )
    return _finish(
        request, _captured_quote_step("/quote/dropoff-date", content, 2), token
    )


@app.post("/quote/dropoff-date", include_in_schema=False)
async def quote_dropoff_date(request: Request) -> Response:
    owner, token = _owner(request)
    values = await _form_values(request)
    dropoff_date = _form_value(values, "dropoff_date")
    dropoff_time = _form_value(values, "dropoff_time", "12:00")
    with _backend().lifecycle.connection() as connection:
        draft = read_draft(connection, "autoslash_quote_drafts", owner)
    pickup_date = str(draft.get("pickup_date", ""))
    if (
        not _valid_date(dropoff_date)
        or not _valid_time(dropoff_time)
        or not _valid_date(pickup_date)
        or dropoff_date < pickup_date
    ):
        response = _captured_quote_step(
            "/quote/dropoff-date",
            "<h2>When will you drop off the rental?</h2>"
            '<p class="form-message">Select a drop-off date after the pickup date.</p>'
            '<input class="input-large" type="date" name="dropoff_date" required>',
            2,
        )
        return _finish(request, response, token)
    with _backend().lifecycle.connection(transaction=True) as connection:
        if not _advance_draft(
            connection, "autoslash_quote_drafts", owner, "dropoff-date", "vehicle",
            {"dropoff_date": dropoff_date, "dropoff_time": dropoff_time},
        ):
            return _finish(
                request,
                _workflow_conflict(
                    "Start your quote again",
                    "Complete the pickup-date step before choosing a drop-off date.",
                    "/", "quote-workflow-required",
                ),
                token,
            )
    return _finish(request, _reference_page("quote-vehicle"), token)


@app.get("/quote/vehicle", include_in_schema=False)
async def quote_vehicle(request: Request) -> Response:
    _, token = _owner(request)
    return _finish(request, _reference_page("quote-vehicle"), token)


@app.post("/quote/vehicle", include_in_schema=False)
async def quote_vehicle_post(request: Request) -> Response:
    owner, token = _owner(request)
    values = await _form_values(request)
    vehicle = _form_value(values, "CarClass")
    if vehicle not in VEHICLE_LABELS:
        return _finish(request, _reference_page("quote-vehicle"), token)
    with _backend().lifecycle.connection(transaction=True) as connection:
        if not _advance_draft(
            connection, "autoslash_quote_drafts", owner, "vehicle", "deals",
            {"vehicle_class": vehicle},
        ):
            return _finish(
                request,
                _workflow_conflict(
                    "Start your quote again",
                    "Complete the location and date steps before choosing a vehicle.",
                    "/", "quote-workflow-required",
                ),
                token,
            )
    return _finish(request, _reference_page("quote-memberships"), token)


@app.get("/quote/memberships", include_in_schema=False)
async def quote_memberships(request: Request) -> Response:
    _, token = _owner(request)
    return _finish(request, _reference_page("quote-memberships"), token)


@app.post("/quote/memberships", include_in_schema=False)
async def quote_memberships_post(request: Request) -> Response:
    owner, token = _owner(request)
    values = await _form_values(request)
    deals = values.get("AffiliationIds", [])
    if not deals or any(deal not in AFFILIATION_LABELS for deal in deals):
        return _finish(request, _reference_page("quote-memberships"), token)
    with _backend().lifecycle.connection(transaction=True) as connection:
        if not _advance_draft(
            connection, "autoslash_quote_drafts", owner, "deals", "contact",
            {"affiliation_ids": deals},
        ):
            return _finish(
                request,
                _workflow_conflict(
                    "Start your quote again",
                    "Choose a vehicle before adding memberships and discounts.",
                    "/", "quote-workflow-required",
                ),
                token,
            )
    return _finish(request, _reference_page("quote-contact"), token)


@app.get("/quote/contact-info", include_in_schema=False)
async def quote_contact_info(request: Request) -> Response:
    _, token = _owner(request)
    return _finish(request, _reference_page("quote-contact"), token)


@app.post("/quote/contact-info", include_in_schema=False)
async def quote_contact_info_post(request: Request) -> Response:
    owner, token = _owner(request)
    values = await _form_values(request)
    first = _form_value(values, "FirstName")
    last = _form_value(values, "LastName")
    email = _form_value(values, "Email").casefold()
    confirm = _form_value(values, "ConfirmEmail").casefold()
    license_country = _form_value(values, "PointOfSaleCountry")
    if not first or not last or not EMAIL_RE.fullmatch(email) or email != confirm:
        return _finish(request, _reference_page("quote-contact"), token)
    request_id = _request_id("ASQ")
    backend = _backend()
    with backend.lifecycle.connection(transaction=True) as connection:
        draft = connection.execute(
            "SELECT stage,payload_json FROM autoslash_quote_drafts WHERE owner_id=?",
            (owner,),
        ).fetchone()
        required = {
            "pickup", "location_type", "dropoff", "same_location",
            "pickup_date", "pickup_time", "dropoff_date", "dropoff_time",
            "vehicle_class", "affiliation_ids",
        }
        payload = json.loads(draft["payload_json"]) if draft is not None else {}
        if draft is None or draft["stage"] != "contact" or not required <= payload.keys():
            response = _information_page(
                "Complete your quote first",
                (
                    "Complete the earlier quote steps before submitting contact information.",
                    "Return to Get a Quote to choose locations, dates, vehicle, and deals.",
                ),
                "quote-workflow-required",
            )
            response.status_code = 409
            return _finish(request, response, token)
        if license_country not in COUNTRY_LABELS:
            return _finish(request, _reference_page("quote-contact"), token)
        payload.update({
            "first_name": first,
            "last_name": last,
            "email": email,
            "license_country": license_country,
        })
        connection.execute(
            "INSERT INTO autoslash_quote_requests"
            "(request_id,owner_id,payload_json,status,created_at) VALUES (?,?,?,?,?)",
            (request_id, owner, json.dumps(payload, sort_keys=True), "received", utc_now()),
        )
        backend.mail.enqueue(
            "quote-request", email, {"request_id": request_id},
            idempotency_key=f"quote:{request_id}", simulation=True, connection=connection,
        )
        connection.execute(
            "DELETE FROM autoslash_quote_drafts WHERE owner_id=?", (owner,)
        )
    response = RedirectResponse("/quote/confirmation", status_code=303)
    return _finish(request, response, token)


@app.get("/quote/confirmation", include_in_schema=False)
async def quote_confirmation(request: Request) -> Response:
    owner, token = _owner(request)
    with _backend().lifecycle.connection() as connection:
        row = connection.execute(
            "SELECT request_id,payload_json FROM autoslash_quote_requests "
            "WHERE owner_id=? ORDER BY created_at DESC,rowid DESC LIMIT 1",
            (owner,),
        ).fetchone()
    if row is None:
        return _finish(request, RedirectResponse("/", status_code=303), token)
    payload = json.loads(row["payload_json"])
    response = _confirmation(
        "Thanks! We're working on your quote.",
        "Your quote request has been received. No credit card is required.",
        str(row["request_id"]),
        "quote-confirmation",
        (
            ("Pickup", payload["pickup"]),
            ("Drop-off", payload["dropoff"]),
            (
                "Pickup date",
                _display_date(payload["pickup_date"], include_time=payload["pickup_time"]),
            ),
            (
                "Drop-off date",
                _display_date(payload["dropoff_date"], include_time=payload["dropoff_time"]),
            ),
            ("Vehicle", VEHICLE_LABELS.get(payload["vehicle_class"], payload["vehicle_class"])),
            (
                "Cards and discounts",
                ", ".join(
                    AFFILIATION_LABELS.get(item, item)
                    for item in payload["affiliation_ids"]
                ),
            ),
            ("Primary driver", f'{payload["first_name"]} {payload["last_name"]}'),
            (
                "Driver's license issued by",
                COUNTRY_LABELS.get(payload["license_country"], payload["license_country"]),
            ),
        ),
    )
    return _finish(request, response, token)


@app.get("/track", include_in_schema=False)
@app.get("/track-a-rental", include_in_schema=False)
async def track(request: Request) -> Response:
    _, token = _owner(request)
    fields = (
        _select("Company", "CompanyId", COMPANIES, "select your rental company")
        + _field(
            "Confirmation Number", "TrackingConfirmationNumber",
            placeholder="rental confirmation number",
        )
    )
    return _finish(
        request,
        _tracking_page(
            1, "Enter your rental company and confirmation number:",
            "/price-tracking/confirmation", fields,
        ),
        token,
    )


@app.post("/price-tracking/confirmation", include_in_schema=False)
async def tracking_confirmation(request: Request) -> Response:
    owner, token = _owner(request)
    values = await _form_values(request)
    company = _form_value(values, "CompanyId")
    confirmation = _form_value(
        values, "TrackingConfirmationNumber"
    ) or _form_value(values, "ConfirmationNumber")
    if company not in COMPANIES or not confirmation:
        response = _tracking_page(
            1, "Enter your rental company and confirmation number:",
            "/price-tracking/confirmation",
            _select("Company", "CompanyId", COMPANIES, "select your rental company")
            + _field(
                "Confirmation Number", "TrackingConfirmationNumber",
                placeholder="rental confirmation number",
            ),
            message="Choose a rental company and enter your confirmation number.",
        )
        return _finish(request, response, token)
    with _backend().lifecycle.connection(transaction=True) as connection:
        connection.execute(
            "DELETE FROM autoslash_tracking_drafts WHERE owner_id=?", (owner,)
        )
        save_draft(
            connection, "autoslash_tracking_drafts", owner, "date",
            {"company": company, "confirmation": confirmation},
        )
    fields = _field("Pickup date", "pickup_date", input_type="date") + _field(
        "Drop-off date", "dropoff_date", input_type="date"
    )
    return _finish(
        request,
        _tracking_page(2, "When is your rental?", "/price-tracking/date", fields),
        token,
    )


@app.post("/price-tracking/date", include_in_schema=False)
async def tracking_date(request: Request) -> Response:
    owner, token = _owner(request)
    values = await _form_values(request)
    pickup_date = _form_value(values, "pickup_date")
    dropoff_date = _form_value(values, "dropoff_date")
    if (
        not _valid_date(pickup_date)
        or not _valid_date(dropoff_date)
        or dropoff_date < pickup_date
    ):
        response = _tracking_page(
            2, "When is your rental?", "/price-tracking/date",
            _field("Pickup date", "pickup_date", input_type="date")
            + _field("Drop-off date", "dropoff_date", input_type="date"),
            message="Enter a valid pickup and drop-off date.",
        )
        return _finish(request, response, token)
    with _backend().lifecycle.connection(transaction=True) as connection:
        if not _advance_draft(
            connection, "autoslash_tracking_drafts", owner, "date", "price",
            {"pickup_date": pickup_date, "dropoff_date": dropoff_date},
        ):
            return _finish(
                request,
                _workflow_conflict(
                    "Start price tracking again",
                    "Enter the rental company and confirmation number before the dates.",
                    "/track", "tracking-workflow-required",
                ),
                token,
            )
    fields = _field(
        "Total rental price", "total_price", input_type="number", placeholder="0.00"
    ) + _field(
        "Currency", "currency", value="USD", required=True
    )
    return _finish(
        request,
        _tracking_page(
            3, "What price did you book?", "/price-tracking/price", fields
        ),
        token,
    )


@app.post("/price-tracking/price", include_in_schema=False)
async def tracking_price(request: Request) -> Response:
    owner, token = _owner(request)
    values = await _form_values(request)
    total = _form_value(values, "total_price")
    try:
        valid_total = 0 < float(total) < 100000
    except ValueError:
        valid_total = False
    if not valid_total:
        response = _tracking_page(
            3, "What price did you book?", "/price-tracking/price",
            _field("Total rental price", "total_price", input_type="number"),
            message="Enter the total price shown on your reservation.",
        )
        return _finish(request, response, token)
    with _backend().lifecycle.connection(transaction=True) as connection:
        if not _advance_draft(
            connection, "autoslash_tracking_drafts", owner, "price", "deals",
            {"total_price": total, "currency": "USD"},
        ):
            return _finish(
                request,
                _workflow_conflict(
                    "Start price tracking again",
                    "Enter the reservation dates before its total price.",
                    "/track", "tracking-workflow-required",
                ),
                token,
            )
    fields = (
        '<fieldset class="deal-options"><legend>Which discounts may apply?</legend>'
        '<label><input type="checkbox" name="deals" value="AAA"> AAA</label>'
        '<label><input type="checkbox" name="deals" value="AARP"> AARP</label>'
        '<label><input type="checkbox" name="deals" value="USAA"> USAA</label>'
        '<label><input type="checkbox" name="deals" value="none"> None of these</label>'
        "</fieldset>"
    )
    return _finish(
        request,
        _tracking_page(
            4, "Tell us about your eligible discounts:",
            "/price-tracking/deals", fields,
        ),
        token,
    )


@app.post("/price-tracking/deals", include_in_schema=False)
async def tracking_deals(request: Request) -> Response:
    owner, token = _owner(request)
    values = await _form_values(request)
    with _backend().lifecycle.connection(transaction=True) as connection:
        if not _advance_draft(
            connection, "autoslash_tracking_drafts", owner, "deals", "email",
            {"deals": values.get("deals", [])},
        ):
            return _finish(
                request,
                _workflow_conflict(
                    "Start price tracking again",
                    "Enter the booked price before selecting eligible discounts.",
                    "/track", "tracking-workflow-required",
                ),
                token,
            )
    fields = _field(
        "Email", "email", input_type="email", placeholder="ex. janedoe@example.com"
    ) + _field(
        "Confirm Email", "confirm_email", input_type="email", placeholder="confirm email"
    )
    return _finish(
        request,
        _tracking_page(
            5, "Where should we send price-drop alerts?",
            "/price-tracking/email", fields,
        ),
        token,
    )


@app.post("/price-tracking/email", include_in_schema=False)
async def tracking_email(request: Request) -> Response:
    owner, token = _owner(request)
    values = await _form_values(request)
    email = _form_value(values, "email").casefold()
    confirm = _form_value(values, "confirm_email").casefold()
    if not EMAIL_RE.fullmatch(email) or email != confirm:
        response = _tracking_page(
            5, "Where should we send price-drop alerts?",
            "/price-tracking/email",
            _field("Email", "email", input_type="email")
            + _field("Confirm Email", "confirm_email", input_type="email"),
            message="Enter the same valid email address twice.",
        )
        return _finish(request, response, token)
    request_id = _request_id("AST")
    backend = _backend()
    with backend.lifecycle.connection(transaction=True) as connection:
        draft = connection.execute(
            "SELECT stage,payload_json FROM autoslash_tracking_drafts WHERE owner_id=?",
            (owner,),
        ).fetchone()
        required = {
            "company", "confirmation", "pickup_date", "dropoff_date",
            "total_price", "currency", "deals",
        }
        payload = json.loads(draft["payload_json"]) if draft is not None else {}
        if draft is None or draft["stage"] != "email" or not required <= payload.keys():
            response = _information_page(
                "Complete price tracking first",
                (
                    "Complete the earlier tracking steps before submitting an email.",
                    "Return to Track a Rental to add the reservation, dates, price, and deals.",
                ),
                "tracking-workflow-required",
            )
            response.status_code = 409
            return _finish(request, response, token)
        payload["email"] = email
        connection.execute(
            "INSERT INTO autoslash_tracking_requests"
            "(request_id,owner_id,payload_json,status,created_at) VALUES (?,?,?,?,?)",
            (request_id, owner, json.dumps(payload, sort_keys=True), "watching", utc_now()),
        )
        backend.mail.enqueue(
            "price-tracking", email, {"request_id": request_id},
            idempotency_key=f"tracking:{request_id}", simulation=True,
            connection=connection,
        )
        connection.execute(
            "DELETE FROM autoslash_tracking_drafts WHERE owner_id=?", (owner,)
        )
    response = RedirectResponse("/price-tracking/complete", status_code=303)
    return _finish(request, response, token)


@app.get("/price-tracking/complete", include_in_schema=False)
async def tracking_complete(request: Request) -> Response:
    owner, token = _owner(request)
    with _backend().lifecycle.connection() as connection:
        row = connection.execute(
            "SELECT request_id,payload_json FROM autoslash_tracking_requests "
            "WHERE owner_id=? ORDER BY created_at DESC,rowid DESC LIMIT 1",
            (owner,),
        ).fetchone()
    if row is None:
        return _finish(request, RedirectResponse("/track", status_code=303), token)
    payload = json.loads(row["payload_json"])
    response = _confirmation(
        "We'll watch for lower prices.",
        "If a lower rate appears, AutoSlash notifies you. You decide whether to "
        "rebook and cancel the old reservation; no automatic rebooking occurs.",
        str(row["request_id"]),
        "tracking-confirmation",
        (
            ("Rental company", payload["company"]),
            ("Confirmation number", payload["confirmation"]),
            ("Pickup date", _display_date(payload["pickup_date"])),
            ("Drop-off date", _display_date(payload["dropoff_date"])),
            ("Booked total", f'${float(payload["total_price"]):.2f} {payload["currency"]}'),
            ("Eligible discounts", ", ".join(payload["deals"]) or "None selected"),
        ),
    )
    return _finish(request, response, token)


@app.get("/reservations/lookup", include_in_schema=False)
async def reservation_lookup(request: Request) -> Response:
    _, token = _owner(request)
    response = _plain_form_page(
        "Reservation Lookup",
        'View or cancel an existing reservation. '
        '<a href="/reservations/forgot">Don\'t remember your Trip ID?</a>',
        "/reservations/lookup",
        _field(
            "Trip ID or Confirmation Number", "confirmation",
            placeholder="from your confirmation email",
        )
        + _field("Email", "email", input_type="email", placeholder="ex. janedoe@example.com"),
        view="reservation-lookup",
        extra='<p><a href="/external-link?destination=priceline">Booked with Priceline?</a></p>',
    )
    return _finish(request, response, token)


@app.post("/reservations/lookup", include_in_schema=False)
async def reservation_lookup_post(request: Request) -> Response:
    owner, token = _owner(request)
    values = await _form_values(request)
    confirmation = _form_value(values, "confirmation")
    email = _form_value(values, "email").casefold()
    if not confirmation or not EMAIL_RE.fullmatch(email):
        return await reservation_lookup(request)
    request_id = _request_id("ASL")
    with _backend().lifecycle.connection(transaction=True) as connection:
        connection.execute(
            "INSERT INTO autoslash_lookup_requests"
            "(request_id,owner_id,confirmation_digest,email_digest,status,created_at) "
            "VALUES (?,?,?,?,?,?)",
            (
                request_id, owner, _digest(confirmation, "confirmation"),
                _digest(email, "email"), "not-found-local", utc_now(),
            ),
        )
    response = _confirmation(
        "We couldn't find a local reservation.",
        "This offline review database contains no source-site reservations. "
        "Check the Trip ID and email or request a Trip ID reminder.",
        request_id,
        "reservation-lookup",
    )
    return _finish(request, response, token)


@app.get("/reservations/forgot", include_in_schema=False)
@app.get("/reservations/email", include_in_schema=False)
async def forgot_trip(request: Request) -> Response:
    _, token = _owner(request)
    response = _plain_form_page(
        "Forgot your Trip ID?",
        "Enter the email address used for your AutoSlash quote or tracked rental.",
        "/reservations/forgot",
        _field("Email", "email", input_type="email", placeholder="ex. janedoe@example.com"),
        view="forgot-trip",
    )
    return _finish(request, response, token)


@app.post("/reservations/forgot", include_in_schema=False)
@app.post("/reservations/email", include_in_schema=False)
async def forgot_trip_post(request: Request) -> Response:
    owner, token = _owner(request)
    values = await _form_values(request)
    email = _form_value(values, "email").casefold()
    if not EMAIL_RE.fullmatch(email):
        return await forgot_trip(request)
    request_id = _request_id("ASR")
    backend = _backend()
    with backend.lifecycle.connection(transaction=True) as connection:
        backend.mail.enqueue(
            "trip-id-recovery", email, {"request_id": request_id},
            idempotency_key=f"recovery:{owner}:{request_id}",
            simulation=True, connection=connection,
        )
    response = _confirmation(
        "Check your email.",
        "If this address matches a local record, recovery instructions were placed "
        "in the local-only outbox. The public response does not reveal a match.",
        request_id,
        "forgot-trip",
    )
    return _finish(request, response, token)


@app.get("/contact-us", include_in_schema=False)
async def contact_us(request: Request) -> Response:
    _, token = _owner(request)
    fields = (
        _field("Name", "name", placeholder="ex. Jane Doe")
        + _field("Email", "email", input_type="email", placeholder="ex. janedoe@example.com")
        + _field("Confirm Email", "confirm_email", input_type="email", placeholder="confirm email")
        + _field("Subject", "subject", placeholder="ex. tracking help")
        + '<label class="field"><span>Description</span>'
        '<textarea name="description" required></textarea></label>'
    )
    response = _plain_form_page(
        "Contact AutoSlash Support",
        "Fill out the form below or email us directly at support@autoslash.com.",
        "/contact-us",
        fields,
        view="contact",
    )
    return _finish(request, response, token)


@app.post("/contact-us", include_in_schema=False)
async def contact_us_post(request: Request) -> Response:
    owner, token = _owner(request)
    values = await _form_values(request)
    name = _form_value(values, "name")
    email = _form_value(values, "email").casefold()
    confirm = _form_value(values, "confirm_email").casefold()
    subject = _form_value(values, "subject")
    description = _form_value(values, "description")
    if (
        not name or not EMAIL_RE.fullmatch(email) or email != confirm
        or not subject or not description
    ):
        return await contact_us(request)
    request_id = _request_id("ASC")
    backend = _backend()
    with backend.lifecycle.connection(transaction=True) as connection:
        connection.execute(
            "INSERT INTO autoslash_support_requests"
            "(request_id,owner_id,name,email,subject,description,status,created_at) "
            "VALUES (?,?,?,?,?,?,?,?)",
            (request_id, owner, name, email, subject, description, "received", utc_now()),
        )
        backend.mail.enqueue(
            "contact-request", email, {"request_id": request_id},
            idempotency_key=f"contact:{request_id}",
            simulation=True, connection=connection,
        )
    response = _confirmation(
        "Thanks for contacting us.",
        "Your support request was saved in the local review environment.",
        request_id,
        "contact",
    )
    return _finish(request, response, token)


@app.get("/frequently-asked-questions", include_in_schema=False)
async def help_page(request: Request) -> Response:
    _, token = _owner(request)
    return _finish(request, _reference_page("help"), token)


@app.get("/coupons", include_in_schema=False)
async def coupons(request: Request) -> Response:
    _, token = _owner(request)
    return _finish(request, _reference_page("coupons"), token)


@app.get("/our-story", include_in_schema=False)
async def our_story(request: Request) -> Response:
    _, token = _owner(request)
    return _finish(request, _reference_page("story"), token)


@app.get("/how-we-do-it", include_in_schema=False)
async def how_we_do_it(request: Request) -> Response:
    _, token = _owner(request)
    return _finish(request, _reference_page("how"), token)


def _information_page(title: str, paragraphs: tuple[str, ...], view: str) -> HTMLResponse:
    content = "".join(f"<p>{_safe(paragraph)}</p>" for paragraph in paragraphs)
    return _document(
        title,
        view,
        f'<main class="plain-page"><article class="plain-card info-card">'
        f"<h1>{_safe(title)}</h1>{content}</article></main>",
    )


@app.get("/in-the-news", include_in_schema=False)
async def in_the_news(request: Request) -> Response:
    _, token = _owner(request)
    return _finish(
        request,
        _information_page(
            "In the News",
            ("AutoSlash press links open outside the first-party site.",
             "External destinations are intentionally not contacted by this offline clone."),
            "news",
        ),
        token,
    )


@app.get("/privacy-policy", include_in_schema=False)
async def privacy_policy(request: Request) -> Response:
    _, token = _owner(request)
    return _finish(
        request,
        _information_page(
            "AUTOSLASH PRIVACY POLICY",
            (
                "The offline clone stores submitted synthetic review data only in its "
                "site-bound local database.",
                "No source-site, email, analytics, advertising, or payment request is sent.",
            ),
            "privacy",
        ),
        token,
    )


@app.get("/terms-of-use", include_in_schema=False)
async def terms_of_use(request: Request) -> Response:
    _, token = _owner(request)
    return _finish(
        request,
        _information_page(
            "Site Terms and Conditions of Use",
            (
                "This offline implementation reproduces the public review surface.",
                "It does not book, cancel, rebook, charge, or contact a real service.",
            ),
            "terms",
        ),
        token,
    )


@app.get("/coupons/{company}/{coupon_id}/{slug}", include_in_schema=False)
async def coupon_detail(
    request: Request, company: str, coupon_id: str, slug: str
) -> Response:
    _, token = _owner(request)
    title = slug.replace("-", " ").title()
    return _finish(
        request,
        _information_page(
            title,
            (
                f"{company.title()} coupon code: {coupon_id.upper()}",
                "Use Get a Quote to include eligible discounts. This page does not "
                "contact a rental company.",
            ),
            "coupon-detail",
        ),
        token,
    )


@app.get("/external-link", include_in_schema=False)
async def external_link(request: Request, destination: str = "external") -> Response:
    _, token = _owner(request)
    return _finish(
        request,
        _information_page(
            "External link",
            (
                f"{destination.title()} is outside the offline AutoSlash clone.",
                "Runtime network access is disabled, so this destination was not opened.",
            ),
            "external-link",
        ),
        token,
    )


@app.get("/account/sign-in", include_in_schema=False)
async def sign_in_notice(request: Request) -> Response:
    _, token = _owner(request)
    return _finish(
        request,
        _information_page(
            "Reservation Lookup",
            (
                "The verified anonymous source journey uses Trip ID and email lookup.",
                "No local password account is invented for this offline clone.",
            ),
            "reservation-lookup",
        ),
        token,
    )


@app.get("/api/session-summary")
async def session_summary(request: Request) -> Response:
    owner, token = _owner(request)
    with _backend().lifecycle.connection() as connection:
        quote_count = int(
            connection.execute(
                "SELECT COUNT(*) FROM autoslash_quote_requests WHERE owner_id=?",
                (owner,),
            ).fetchone()[0]
        )
        tracking_count = int(
            connection.execute(
                "SELECT COUNT(*) FROM autoslash_tracking_requests WHERE owner_id=?",
                (owner,),
            ).fetchone()[0]
        )
    response = JSONResponse(
        {"site_id": SITE_ID, "quote_requests": quote_count,
         "tracking_requests": tracking_count}
    )
    return _finish(request, response, token)


@app.api_route(
    "/{path:path}", methods=["GET"], include_in_schema=False
)
async def not_found(request: Request, path: str) -> Response:
    del path
    _, token = _owner(request)
    body = """<main class="not-found"><div>
    <img class="not-found-car" src="/static/site/assets/car-facing-right-lg@2x.png" alt="">
    <h1>Page Not Found</h1>
    <p>We're sorry, this page no longer exists.</p>
    <p>Please visit our <a href="/">home page</a> if you are not redirected in 5 seconds.</p>
    </div></main>"""
    return _finish(
        request, _document("Page not found", "not-found", body, status_code=404), token
    )


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(
        app,
        host=os.environ.get("HOST", "127.0.0.1"),
        port=int(os.environ.get("PORT", "3000")),
        log_level="warning",
    )