File size: 50,552 Bytes
7f8e190
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Insurify WebsiteBench offline clone.

Public entry pages are grounded in the 2026-08-23 anonymous captures.  The
quote, account, policy, and payment journeys are an explicit local model: no
runtime request leaves the clone and no real insurer or payment service is
contacted.
"""

from __future__ import annotations

import os
import re
import sys
from datetime import datetime
from pathlib import Path
from typing import Any
from urllib.parse import urlsplit

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

ROOT = Path(__file__).resolve().parent
if str(ROOT) not in sys.path:
    sys.path.insert(0, str(ROOT))

from backend import business  # noqa: E402
from backend.site_backend_integration import open_site_services  # noqa: E402
import views  # noqa: E402
from websitebench.local_clone_auth import (  # noqa: E402
    AuthConflict,
    AuthError,
    AuthRateLimited,
)
from websitebench.site_backend import PaymentError, PaymentRejected  # noqa: E402


SITE_ID = "insurify"
BACKEND, AUTH = open_site_services()
with BACKEND.lifecycle.connection(transaction=True) as connection:
    business.migrate(connection)

DEMO_ACCOUNT_ID = AUTH.seed_account(
    subject_id="insurify-demo-driver",
    email="demo@insurify.local",
    display_name="Jordan Sample",
    password="Compare123!",
)
with BACKEND.lifecycle.connection(transaction=True) as connection:
    business.seed_demo(connection, DEMO_ACCOUNT_ID)

APP = FastAPI(
    title="Insurify offline clone", docs_url=None, redoc_url=None, openapi_url=None
)
app = APP
APP.mount("/static", StaticFiles(directory=str(ROOT / "static")), name="static")

DEPLOYED_COOKIE = str(BACKEND.session_cookie["name"])
LOCAL_COOKIE = "websitebench-insurify-session"
CSP = (
    "default-src 'self'; img-src 'self' data:; style-src 'self'; script-src 'self'; "
    "connect-src 'self'; form-action 'self'; frame-ancestors 'none'; base-uri 'self'"
)
ZIP_RE = re.compile(r"^\d{5}$")
EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")


def _loopback(request: Request) -> bool:
    return (request.url.hostname or "").casefold() in {
        "127.0.0.1",
        "localhost",
        "::1",
        "[::1]",
        "testserver",
    }


def _cookie_name(request: Request) -> str:
    return LOCAL_COOKIE if _loopback(request) else DEPLOYED_COOKIE


def _origin(value: str) -> tuple[str, str, int]:
    parsed = urlsplit(value)
    return (
        parsed.scheme.casefold(),
        (parsed.hostname or "").casefold(),
        parsed.port or (443 if parsed.scheme.casefold() == "https" else 80),
    )


def _request_origin(request: Request) -> tuple[str, str, int]:
    return (
        request.url.scheme.casefold(),
        (request.url.hostname or "").casefold(),
        request.url.port or (443 if request.url.scheme.casefold() == "https" else 80),
    )


def _set_cookie(request: Request, response: Response, token: str) -> None:
    response.set_cookie(
        _cookie_name(request),
        token,
        secure=not _loopback(request),
        httponly=True,
        samesite="lax",
        path="/",
    )


@APP.middleware("http")
async def runtime_boundary(request: Request, call_next):
    if request.method in {"POST", "PUT", "PATCH", "DELETE"}:
        source = request.headers.get("origin") or request.headers.get("referer")
        invalid = source == "null" and not _loopback(request)
        if source and source != "null":
            invalid = _origin(source) != _request_origin(request)
        elif not source:
            invalid = not _loopback(request)
        if invalid:
            return JSONResponse(
                {"error": "cross-origin state changes are not allowed"}, status_code=403
            )
    supplied = request.cookies.get(_cookie_name(request))
    token, session = AUTH.ensure_session(supplied)
    request.state.auth_token = token
    request.state.auth_info = session
    response = await call_next(request)
    response.headers["Content-Security-Policy"] = CSP
    response.headers["Referrer-Policy"] = "no-referrer"
    response.headers["X-Content-Type-Options"] = "nosniff"
    response.headers["X-Frame-Options"] = "DENY"
    current = str(getattr(request.state, "auth_token", token))
    if current != supplied:
        _set_cookie(request, response, current)
    return response


def html(markup: str, status: int = 200) -> HTMLResponse:
    return HTMLResponse(markup, status_code=status)


def see_other(path: str) -> RedirectResponse:
    return RedirectResponse(path, status_code=303)


def db():
    return BACKEND.lifecycle.connection(transaction=True)


def account_of(request: Request) -> dict[str, Any] | None:
    session = getattr(request.state, "auth_info", {}) or {}
    if not session.get("authenticated"):
        return None
    return dict(session.get("account") or {})


def account_id_of(request: Request) -> str | None:
    account = account_of(request)
    return str(account["account_id"]) if account else None


def owner_key_of(request: Request) -> str:
    digest = AUTH.session_owner_digest(str(request.state.auth_token))
    return f"session:{digest}"


def _safe_next(value: Any) -> str:
    target = str(value or "/account/")
    return target if target.startswith("/") and not target.startswith("//") else "/account/"


def _quote(request: Request, quote_id: str) -> dict[str, Any] | None:
    with db() as connection:
        return business.get_quote(
            connection,
            quote_id,
            owner_key=owner_key_of(request),
            account_id=account_id_of(request),
        )


def _quote_or_404(request: Request, quote_id: str) -> dict[str, Any] | HTMLResponse:
    quote = _quote(request, quote_id)
    if quote is None:
        return html(views.not_found(account_of(request)), 404)
    return quote


# -------------------------------------------------------------------------
# health
# -------------------------------------------------------------------------


@APP.get("/favicon.ico", include_in_schema=False)
def favicon() -> Response:
    """The source links `/favicon.ico`; serve the captured Insurify mark there so no page logs a 404."""
    icon = ROOT / "static" / "assets" / "insurifycdn.com/ui/logo/InsurifyNew.svg"
    return Response(icon.read_bytes(), media_type="image/svg+xml",
                    headers={"Cache-Control": "public, max-age=86400"})


@APP.get("/__websitebench/health", response_class=JSONResponse)
def websitebench_health() -> dict[str, str]:
    return {"status": "ok"}


@APP.get("/healthz", response_class=JSONResponse)
def healthz() -> dict[str, object]:
    return {"ok": True, "site_id": SITE_ID, "status": "ok"}


# -------------------------------------------------------------------------
# source-grounded public pages
# -------------------------------------------------------------------------


@APP.get("/", response_class=HTMLResponse)
@APP.get("/compare/", response_class=HTMLResponse)
@APP.get("/sqaf/", response_class=HTMLResponse)
def home(request: Request):
    return html(views.home(account_of(request)))


@APP.get("/quote/start", response_class=HTMLResponse)
def quote_start(request: Request):
    return html(views.start_quote(account=account_of(request)))


@APP.get("/search", response_class=HTMLResponse)
def search(request: Request, q: str = ""):
    return html(views.search_page(q, account_of(request)))


@APP.get("/help/", response_class=HTMLResponse)
def help_page(request: Request):
    return html(views.help_page(account_of(request)))


PUBLIC_PAGES: dict[str, tuple[str, str, str, tuple[tuple[str, str], ...]]] = {
    "car-insurance": (
        "Compare Car Insurance Rates From $43/mo. (Updated August 2026)",
        "Find the lowest car insurance rates from 120+ insurers and save up to $1,100* annually with Insurify’s insurance-comparison tool.",
        "Car insurance",
        (
            ("Cheapest recent rates", "Drivers can compare liability-only and full-coverage estimates, then inspect each plan."),
            ("How to compare car insurance", "Look beyond price to limits, deductibles, exclusions, benefits, and carrier details."),
        ),
    ),
    "car-insurance/cheap-car-insurance": (
        "Top 10 Cheap Car Insurance Companies in August 2026",
        "Compare affordable insurers without giving up the coverage that matters.",
        "Car insurance",
        (("Find cheaper coverage", "Rates vary by driver, location, vehicle, history, and selected limits."),),
    ),
    "car-insurance/best-car-insurance": (
        "Best Car Insurance Companies (August 2026)",
        "Compare highly rated companies by coverage, service, and price.",
        "Car insurance",
        (("Best company for you", "The best match depends on the coverage and support you prefer."),),
    ),
    "car-insurance/companies": (
        "Compare Car Insurance Companies",
        "Review carrier profiles, common coverages, discounts, and customer experience.",
        "Insurance companies",
        (("Compare multiple carriers", "The offline quote journey returns Travelers, Liberty Mutual, Progressive, and Allstate options."),),
    ),
    "car-insurance/calculator": (
        "Calculator: Estimate Your Car Insurance Costs (August 2026)",
        "See how location, vehicle, mileage, driving history, coverage, and deductible change an estimate.",
        "Car insurance",
        (("What affects rates?", "Each quote is recalculated from the information and preferences entered in the local funnel."),),
    ),
    "car-insurance/knowledge": (
        "Car Insurance Knowledge Center",
        "Understand coverages, compare carriers, and make informed decisions.",
        "Insurance knowledge",
        (("Insurance without the jargon", "Browse practical guides or begin a side-by-side comparison."),),
    ),
    "homeowners-insurance": (
        "Compare Home Insurance Quotes Side by Side",
        "Compare homeowners coverage and bundle options online.",
        "Home insurance",
        (("Protect your home", "Review dwelling, personal property, liability, and deductible choices."),),
    ),
    "renters-insurance": (
        "Compare Renters Insurance Quotes",
        "Protect belongings and compare renters coverage in minutes.",
        "Renters insurance",
        (("Coverage for renters", "Compare personal property, liability, and additional living expense protection."),),
    ),
    "life-insurance": (
        "Compare Life Insurance Quotes",
        "Learn about term and permanent life insurance choices.",
        "Life insurance",
        (("Choose a policy type", "Consider term, benefit amount, eligibility, and policy terms."),),
    ),
    "health-insurance": (
        "Compare Health Insurance Plans",
        "Review health coverage guidance and plan-comparison entry points.",
        "Health insurance",
        (("Understand plan costs", "Compare premiums, deductibles, networks, and covered benefits."),),
    ),
    "pet-insurance": (
        "Compare Pet Insurance Quotes",
        "Protect your pet and compare accident and illness coverage.",
        "Pet insurance",
        (("Coverage for your pet", "Compare reimbursement, deductible, annual limit, and exclusions."),),
    ),
    "travel-insurance": (
        "Compare Travel Insurance",
        "Review coverage for trip interruption, delay, and emergency care.",
        "Travel insurance",
        (("Plan with confidence", "Inspect benefits, limits, and exclusions before selecting a plan."),),
    ),
    "business-insurance": (
        "Compare Business Insurance",
        "Explore coverage options for small businesses.",
        "Business insurance",
        (("Protect your business", "Compare liability and property coverage guidance."),),
    ),
    "insurify-car": (
        "Weekly Car Insurance from $23/week*",
        "Flexible car insurance with quotes in two minutes.",
        "Insurify Car",
        (
            ("2 minutes to quote, 4 minutes to buy.", "Enter a ZIP code, applicant details, vehicle information, and coverage preferences."),
            ("Insurance you control. Cancel anytime.", "Use the local policy-management surface to inspect or cancel a simulated record."),
        ),
    ),
    "company/about": (
        "About Insurify",
        "Insurance comparison should be simple, transparent, and accessible.",
        "Company",
        (("Our mission", "Help people compare, buy, and manage insurance in one place."),),
    ),
    "company/leadership": (
        "Insurify Leadership",
        "Meet the teams guiding Insurify's insurance-comparison platform.",
        "Company",
        (("Built around customers", "Leadership spans insurance, technology, data, and customer experience."),),
    ),
    "company/trust": (
        "Trust and Security at Insurify",
        "Learn how Insurify approaches privacy and secure comparison experiences.",
        "Company",
        (("Your information", "This local clone uses an isolated database and makes no runtime request to the source."),),
    ),
    "company/policy": (
        "Privacy Policy",
        "Review how information is described and handled.",
        "Company",
        (("Offline-clone privacy", "Credentials and quote inputs stay in the site-specific local runtime and are never placed in evidence artifacts."),),
    ),
    "company/terms": (
        "Terms of Service",
        "Terms for using Insurify's comparison experience.",
        "Company",
        (("Local fixture terms", "This clone provides no real insurance, carrier offer, legal advice, or live transaction."),),
    ),
    "company/contact": (
        "Contact Insurify",
        "Get help with quotes, account access, policy questions, or a failed action.",
        "Help & recovery",
        (
            ("Talk to an insurance agent", "Call (888) 866-0849 for the public support entry shown on the captured site."),
            ("Account and quote recovery", "Use the local password-recovery or quote-return forms without exposing private data."),
        ),
    ),
    # --- Reports & Data nav pages (2026-08-24 capture). The clone's original
    # hrefs were transcription errors; corrected to the real paths from the
    # Storyblok nav JSON in source-current/2026-08-23.anon-recon/company-policy.html.
    "car-insurance/report/data": (
        "Auto Insurance Data Center",
        "Explore downloadable car insurance data from Insurify's real-time database of auto insurance quotes and applications.",
        "Auto insurance data",
        (
            ("Car insurance rates by state", "See historical average rates for a full-coverage car insurance policy up through the most recent full month available. Data available in 40+ states going back to 2021. New data posted by the 5th of each month."),
            ("Car insurance rates by vehicle", "See historical average rates for a full-coverage car insurance policy up through the most recent full month available. Data available for 50 top models going back to 2021. New data posted by the 5th of each month."),
            ("Driving behavior by state", "Download the latest data on driver behavior in all 50 states including:"),
        ),
    ),
    "car-insurance/report": (
        "Car Insurance Costs Climb in the First Half of 2026: Insurify Projects Increases in 32 States by Year’s End",
        "Car insurance rates are on track to rise across half of the U.S. in 2026. Find out if your state will face higher premiums.",
        "Car insurance report",
        (
            ("Drivers benefited from a 6% drop in premiums last year, but Insurify projects…", "See the full report on Insurify."),
            ("The 10 most expensive states for car insurance", "Nationally, car insurance premiums have dropped since their height in 2024, but some drivers are still paying stubbornly high premiums. Location is a big factor in insurance pricing, as communities have varying levels of risk."),
            ("States with the biggest cost increases in the first half of 2026", "In the first six months of 2026, 27 states saw their rates increase, compared to just nine states with increases in the second half of 2025."),
        ),
    ),
    "homeowners-insurance/report/home-insurance-price-projections": (
        "Insurify Projects Home Insurance Rates Will Rise for the 5th Consecutive Year, After a 12% Increase in 2025",
        "Twenty states saw their home insurance premiums spike by double digits in 2025. Find out how rates could move in your state in 2026.",
        "Home insurance report",
        (
            ("The annual cost of home insurance will reach $3,057 (+4%) by the end of 2026…", "See the full report on Insurify."),
            ("Top 10 most expensive states for home insurance by the end of 2026", "The U.S. may not have experienced any hurricanes in 2025, but other forms of extreme weather generated losses in their place. Americans witnessed 23 billion-dollar disasters in 2025, the third most on record, behind only 2023 and 2024."),
            ("The 10 states that will see the largest cost increases in 2026", "As insurers adapt to extreme weather, Insurify projects that 45 states and Washington, D.C., will see home insurance rates rise over the next 12 months. California, coming off a record-setting pair of wildfires in early 2025, faces the largest potential increa"),
        ),
    ),
    "insights": (
        "Latest Articles",
        "Latest Articles",
        "Insights",
        (
            ("Insurify's insurance experts guide you through the basics of insights insurance.", "Survey: 88% of Americans Have Made Sacrifices to Deal With High Gas Prices; 24% Cut Back On Car Insurance"),
        ),
    ),
    "report": (
        "Insurify Reports",
        "Insurify Reports",
        "Insurify reports",
        (
            ("Latest reports", "Insurify’s Home Insurance Risk Index: America’s Least Insurable Counties, Ranked"),
        ),
    ),
}


# -------------------------------------------------------------------------
# quote journey
# -------------------------------------------------------------------------


@APP.get("/quote/new")
def quote_new_get(request: Request):
    """The homepage ZIP form posts here; a direct GET returns to the entry."""
    return see_other("/quote/start")


@APP.post("/quote/new")
async def quote_new(request: Request):
    form = await request.form()
    zip_code = str(form.get("zip_code") or form.get("zipcode") or "").strip()
    product = str(form.get("product") or "auto").strip().casefold()
    if product not in {"auto", "bundle", "home", "renters", "pet"}:
        product = "auto"
    if not ZIP_RE.fullmatch(zip_code):
        return html(
            views.start_quote(
                account=account_of(request),
                error="Enter a valid 5-digit US ZIP code.",
                zip_code=zip_code,
                product=product,
            ),
            400,
        )
    with db() as connection:
        quote = business.create_quote(
            connection,
            owner_key=owner_key_of(request),
            account_id=account_id_of(request),
            zip_code=zip_code,
            product=product,
        )
    first_step = {
        "home": "property-insured",
        "bundle": "property-insured",
        "renters": "property-address",
        "pet": "pet-species",
    }.get(product, "applicant")
    return see_other(f"/quote/{quote['id']}/{first_step}")


@APP.get("/quote/{quote_id}/property-insured", response_class=HTMLResponse)
def quote_property_insured(request: Request, quote_id: str):
    quote = _quote_or_404(request, quote_id)
    if isinstance(quote, HTMLResponse): return quote
    if quote.get("product") not in {"home", "bundle"}: return see_other(f"/quote/{quote_id}/applicant")
    return html(views.property_insured_form(quote, account_of(request)))


@APP.post("/quote/{quote_id}/property-insured")
async def quote_property_insured_post(request: Request, quote_id: str):
    form = await request.form(); value = str(form.get("property_insured") or "")
    if value not in {"0", "1"}:
        quote = _quote_or_404(request, quote_id)
        if isinstance(quote, HTMLResponse): return quote
        return html(views.property_insured_form(quote, account_of(request)), 400)
    with db() as connection:
        updated = business.update_quote(connection, quote_id, {"property_insured": value == "1"}, owner_key=owner_key_of(request), account_id=account_id_of(request))
    if updated is None: return html(views.not_found(account_of(request)), 404)
    return see_other(f"/quote/{quote_id}/property-address")


@APP.get("/quote/{quote_id}/property-address", response_class=HTMLResponse)
def quote_property_address(request: Request, quote_id: str):
    quote = _quote_or_404(request, quote_id)
    if isinstance(quote, HTMLResponse): return quote
    if quote.get("product") not in {"home", "bundle", "renters"}: return see_other(f"/quote/{quote_id}/applicant")
    return html(views.property_address_form(quote, account=account_of(request)))


@APP.post("/quote/{quote_id}/property-address")
async def quote_property_address_post(request: Request, quote_id: str):
    form = await request.form(); address = str(form.get("address_line") or "").strip(); unit = str(form.get("apartment_unit") or "").strip(); zip_code = str(form.get("zip_code") or "").strip(); errors = {}
    if not address: errors["address_line"] = "Enter the property address."
    if not ZIP_RE.fullmatch(zip_code): errors["zip_code"] = "Enter a valid 5-digit ZIP code."
    quote = _quote_or_404(request, quote_id)
    if isinstance(quote, HTMLResponse): return quote
    if errors: return html(views.property_address_form({**quote, "address_line": address, "apartment_unit": unit, "zip_code": zip_code}, errors, account_of(request)), 400)
    with db() as connection:
        updated = business.update_quote(connection, quote_id, {"address_line": address, "apartment_unit": unit, "zip_code": zip_code}, owner_key=owner_key_of(request), account_id=account_id_of(request))
    if updated is None: return html(views.not_found(account_of(request)), 404)
    return see_other(f"/quote/{quote_id}/applicant")


@APP.get("/quote/{quote_id}/pet-species", response_class=HTMLResponse)
def quote_pet_species(request: Request, quote_id: str):
    quote = _quote_or_404(request, quote_id)
    if isinstance(quote, HTMLResponse): return quote
    if quote.get("product") != "pet": return see_other(f"/quote/{quote_id}/applicant")
    return html(views.pet_species_form(quote, account_of(request)))


@APP.post("/quote/{quote_id}/pet-species")
async def quote_pet_species_post(request: Request, quote_id: str):
    form = await request.form(); species = str(form.get("pet_species") or "")
    if species not in {"Dog", "Cat"}:
        quote = _quote_or_404(request, quote_id)
        if isinstance(quote, HTMLResponse): return quote
        return html(views.pet_species_form(quote, account_of(request)), 400)
    with db() as connection:
        updated = business.update_quote(connection, quote_id, {"pet_species": species}, owner_key=owner_key_of(request), account_id=account_id_of(request))
    if updated is None: return html(views.not_found(account_of(request)), 404)
    return see_other(f"/quote/{quote_id}/pet-gender")


@APP.get("/quote/{quote_id}/pet-gender", response_class=HTMLResponse)
def quote_pet_gender(request: Request, quote_id: str):
    quote = _quote_or_404(request, quote_id)
    if isinstance(quote, HTMLResponse): return quote
    if quote.get("product") != "pet" or not quote.get("pet_species"): return see_other(f"/quote/{quote_id}/pet-species")
    return html(views.pet_gender_form(quote, account_of(request)))


@APP.post("/quote/{quote_id}/pet-gender")
async def quote_pet_gender_post(request: Request, quote_id: str):
    form = await request.form(); gender = str(form.get("pet_gender") or "")
    if gender not in {"Male", "Female"}:
        quote = _quote_or_404(request, quote_id)
        if isinstance(quote, HTMLResponse): return quote
        return html(views.pet_gender_form(quote, account_of(request)), 400)
    with db() as connection:
        updated = business.update_quote(connection, quote_id, {"pet_gender": gender}, owner_key=owner_key_of(request), account_id=account_id_of(request))
    if updated is None: return html(views.not_found(account_of(request)), 404)
    return see_other(f"/quote/{quote_id}/applicant")


@APP.get("/quote/{quote_id}/applicant", response_class=HTMLResponse)
def quote_applicant(request: Request, quote_id: str):
    quote = _quote_or_404(request, quote_id)
    if isinstance(quote, HTMLResponse):
        return quote
    return html(views.applicant_form(quote, account=account_of(request)))


@APP.post("/quote/{quote_id}/applicant")
async def quote_applicant_post(request: Request, quote_id: str):
    form = await request.form()
    values = {
        key: str(form.get(key) or "").strip()
        for key in (
            "first_name",
            "last_name",
            "birth_date",
            "email",
            "phone",
            "gender",
            "marital_status",
        )
    }
    errors: dict[str, str] = {}
    if not values["first_name"]:
        errors["first_name"] = "Enter your first name."
    if not values["last_name"]:
        errors["last_name"] = "Enter your last name."
    try:
        born = datetime.strptime(values["birth_date"], "%Y-%m-%d").date()
        age = (datetime.now().date() - born).days // 365
        if not 16 <= age <= 100:
            errors["birth_date"] = "Enter a driver age between 16 and 100."
    except ValueError:
        errors["birth_date"] = "Enter a valid date of birth."
    if not EMAIL_RE.fullmatch(values["email"]):
        errors["email"] = "Enter a complete email address."
    if len(re.sub(r"\D", "", values["phone"])) < 7:
        errors["phone"] = "Enter a valid phone number."
    current = _quote_or_404(request, quote_id)
    if isinstance(current, HTMLResponse):
        return current
    if errors:
        return html(
            views.applicant_form(
                {**current, **values}, errors, account=account_of(request)
            ),
            400,
        )
    with db() as connection:
        updated = business.update_quote(
            connection,
            quote_id,
            values,
            owner_key=owner_key_of(request),
            account_id=account_id_of(request),
        )
    if updated is None:
        return html(views.not_found(account_of(request)), 404)
    next_step = "vehicle" if updated.get("product") in {"auto", "bundle"} else "coverage"
    return see_other(f"/quote/{quote_id}/{next_step}")


@APP.get("/quote/{quote_id}/vehicle", response_class=HTMLResponse)
def quote_vehicle(request: Request, quote_id: str):
    quote = _quote_or_404(request, quote_id)
    if isinstance(quote, HTMLResponse):
        return quote
    return html(views.vehicle_form(quote, account=account_of(request)))


@APP.post("/quote/{quote_id}/vehicle")
async def quote_vehicle_post(request: Request, quote_id: str):
    form = await request.form()
    errors: dict[str, str] = {}
    try:
        year = int(str(form.get("vehicle_year") or ""))
        if not 1980 <= year <= 2026:
            raise ValueError
    except ValueError:
        year = 0
        errors["vehicle_year"] = "Select a valid vehicle year."
    make = str(form.get("vehicle_make") or "").strip()
    model = str(form.get("vehicle_model") or "").strip()
    try:
        annual_miles = int(str(form.get("annual_miles") or ""))
        if not 0 <= annual_miles <= 100_000:
            raise ValueError
    except ValueError:
        annual_miles = 0
        errors["annual_miles"] = "Enter annual mileage from 0 to 100,000."
    if not make:
        errors["vehicle_make"] = "Enter the vehicle make."
    if not model:
        errors["vehicle_model"] = "Enter the vehicle model."
    values: dict[str, Any] = {
        "vehicle_year": year,
        "vehicle_make": make,
        "vehicle_model": model,
        "vehicle_ownership": str(form.get("vehicle_ownership") or "Owned"),
        "annual_miles": annual_miles,
        "incidents": max(0, min(2, int(str(form.get("incidents") or "0")))),
        "currently_insured": str(form.get("currently_insured") or "1") == "1",
    }
    current = _quote_or_404(request, quote_id)
    if isinstance(current, HTMLResponse):
        return current
    if errors:
        return html(
            views.vehicle_form({**current, **values}, errors, account_of(request)),
            400,
        )
    with db() as connection:
        updated = business.update_quote(
            connection,
            quote_id,
            values,
            owner_key=owner_key_of(request),
            account_id=account_id_of(request),
        )
    if updated is None:
        return html(views.not_found(account_of(request)), 404)
    return see_other(f"/quote/{quote_id}/coverage")


@APP.get("/quote/{quote_id}/coverage", response_class=HTMLResponse)
def quote_coverage(request: Request, quote_id: str):
    quote = _quote_or_404(request, quote_id)
    if isinstance(quote, HTMLResponse):
        return quote
    return html(views.coverage_form(quote, account_of(request)))


@APP.post("/quote/{quote_id}/coverage")
async def quote_coverage_post(request: Request, quote_id: str):
    form = await request.form()
    level = str(form.get("coverage_level") or "standard")
    if level not in {"state-minimum", "standard", "full"}:
        level = "standard"
    try:
        deductible = int(str(form.get("deductible_cents") or "50000"))
    except ValueError:
        deductible = 50000
    if deductible not in {25000, 50000, 100000}:
        deductible = 50000
    with db() as connection:
        updated = business.update_quote(
            connection,
            quote_id,
            {"coverage_level": level, "deductible_cents": deductible},
            owner_key=owner_key_of(request),
            account_id=account_id_of(request),
        )
        if updated is not None:
            updated = business.generate_options(
                connection,
                quote_id,
                owner_key=owner_key_of(request),
                account_id=account_id_of(request),
            )
    if updated is None:
        return html(views.not_found(account_of(request)), 404)
    return see_other(f"/quote/{quote_id}/results")


@APP.get("/quote/{quote_id}/results", response_class=HTMLResponse)
def quote_results(request: Request, quote_id: str):
    quote = _quote_or_404(request, quote_id)
    if isinstance(quote, HTMLResponse):
        return quote
    if not quote.get("options"):
        return see_other(f"/quote/{quote_id}/coverage")
    return html(views.quote_results(quote, account_of(request)))


@APP.get("/quote/{quote_id}/plan/{option_id}", response_class=HTMLResponse)
def quote_plan(request: Request, quote_id: str, option_id: str):
    quote = _quote_or_404(request, quote_id)
    if isinstance(quote, HTMLResponse):
        return quote
    option = next((row for row in quote.get("options", []) if row["id"] == option_id), None)
    if option is None:
        return html(views.not_found(account_of(request)), 404)
    return html(views.plan_detail(quote, option, account_of(request)))


@APP.post("/quote/{quote_id}/select")
async def quote_select(request: Request, quote_id: str):
    form = await request.form()
    option_id = str(form.get("option_id") or "")
    with db() as connection:
        quote = business.select_option(
            connection,
            quote_id,
            option_id,
            owner_key=owner_key_of(request),
            account_id=account_id_of(request),
        )
    if quote is None:
        return html(views.not_found(account_of(request)), 404)
    return see_other(f"/quote/{quote_id}/enroll")


@APP.get("/quote/{quote_id}/enroll", response_class=HTMLResponse)
def quote_enroll(request: Request, quote_id: str):
    quote = _quote_or_404(request, quote_id)
    if isinstance(quote, HTMLResponse):
        return quote
    with db() as connection:
        option = business.selected_option(connection, quote)
    if option is None:
        return see_other(f"/quote/{quote_id}/results")
    return html(views.enrollment_form(quote, option, account=account_of(request)))


@APP.post("/quote/{quote_id}/enroll")
async def quote_enroll_post(request: Request, quote_id: str):
    form = await request.form()
    values = {
        key: str(form.get(key) or "").strip()
        for key in ("address_line", "city", "state", "zip_code")
    }
    errors = {key: f"Enter your {key.replace('_', ' ')}." for key, value in values.items() if not value}
    if values["zip_code"] and not ZIP_RE.fullmatch(values["zip_code"]):
        errors["zip_code"] = "Enter a valid 5-digit ZIP code."
    if str(form.get("agree") or "") != "1":
        errors["agree"] = "Accept the terms before continuing."
    quote = _quote_or_404(request, quote_id)
    if isinstance(quote, HTMLResponse):
        return quote
    with db() as connection:
        option = business.selected_option(connection, quote)
    if option is None:
        return see_other(f"/quote/{quote_id}/results")
    if errors:
        return html(
            views.enrollment_form(
                {**quote, **values}, option, errors, account_of(request)
            ),
            400,
        )
    with db() as connection:
        updated = business.update_policy_contact(
            connection,
            quote_id,
            values,
            owner_key=owner_key_of(request),
            account_id=account_id_of(request),
        )
    if updated is None:
        return html(views.not_found(account_of(request)), 404)
    return see_other(f"/quote/{quote_id}/payment")


@APP.get("/quote/{quote_id}/payment", response_class=HTMLResponse)
def quote_payment(request: Request, quote_id: str):
    quote = _quote_or_404(request, quote_id)
    if isinstance(quote, HTMLResponse):
        return quote
    with db() as connection:
        option = business.selected_option(connection, quote)
    if option is None:
        return see_other(f"/quote/{quote_id}/results")
    return html(views.payment_form(quote, option, account=account_of(request)))


@APP.post("/quote/{quote_id}/payment")
async def quote_payment_post(request: Request, quote_id: str):
    form = await request.form()
    scenario = str(form.get("scenario_id") or "")
    quote = _quote_or_404(request, quote_id)
    if isinstance(quote, HTMLResponse):
        return quote
    with db() as connection:
        option = business.selected_option(connection, quote)
    if option is None:
        return see_other(f"/quote/{quote_id}/results")
    if not str(form.get("billing_name") or "").strip() or str(form.get("confirm") or "") != "1":
        return html(
            views.payment_form(
                quote,
                option,
                error="Enter a billing name and confirm the final review.",
                account=account_of(request),
            ),
            400,
        )
    try:
        with db() as connection:
            current = business.get_quote(
                connection,
                quote_id,
                owner_key=owner_key_of(request),
                account_id=account_id_of(request),
            )
            if current is None:
                return html(views.not_found(account_of(request)), 404)
            existing = connection.execute(
                "SELECT * FROM insurify_policies WHERE quote_id=?", (quote_id,)
            ).fetchone()
            if existing is not None:
                return see_other(f"/quote/{quote_id}/confirmation")
            facts = business.payment_facts(connection, current)
            flow = BACKEND.payments.create_intent(
                owner=facts["owner"],
                amount_minor=facts["amount_minor"],
                currency=facts["currency"],
                fingerprint=facts["fingerprint"],
                idempotency_key=f"insurify.create:{quote_id}:{facts['fingerprint'][:18]}",
                connection=connection,
            )
            attempt = BACKEND.payments.attempt(
                flow_id=flow["flow_id"],
                owner=facts["owner"],
                amount_minor=facts["amount_minor"],
                currency=facts["currency"],
                fingerprint=facts["fingerprint"],
                scenario_id=scenario,
                idempotency_key=(
                    f"insurify.attempt:{quote_id}:"
                    f"{facts['fingerprint'][:18]}:{scenario}"
                ),
                connection=connection,
            )
            if attempt["status"] != "APPROVED":
                label = "declined" if attempt["status"] == "DECLINED" else "temporarily unavailable"
                return html(
                    views.payment_form(
                        current,
                        facts["option"],
                        error=f"The local sandbox result was {label}. Choose another scenario and retry.",
                        account=account_of(request),
                    ),
                    400,
                )
            consumed = BACKEND.payments.consume_approval(
                connection,
                flow_id=flow["flow_id"],
                owner=facts["owner"],
                amount_minor=facts["amount_minor"],
                currency=facts["currency"],
                fingerprint=facts["fingerprint"],
            )
            business.finalize_enrollment(
                connection,
                quote=current,
                facts=facts,
                payment_flow_id=flow["flow_id"],
                payment_attempt_id=consumed["attempt_id"],
                account_id=account_id_of(request),
            )
    except (PaymentError, PaymentRejected) as exc:
        return html(
            views.payment_form(
                quote,
                option,
                error=f"The local sandbox could not complete this attempt: {exc}",
                account=account_of(request),
            ),
            400,
        )
    return see_other(f"/quote/{quote_id}/confirmation")


@APP.get("/quote/{quote_id}/confirmation", response_class=HTMLResponse)
def quote_confirmation(request: Request, quote_id: str):
    quote = _quote_or_404(request, quote_id)
    if isinstance(quote, HTMLResponse):
        return quote
    with db() as connection:
        option = business.selected_option(connection, quote)
        policy = connection.execute(
            "SELECT * FROM insurify_policies WHERE quote_id=?", (quote_id,)
        ).fetchone()
    if option is None or policy is None:
        return see_other(f"/quote/{quote_id}/payment")
    return html(views.confirmation(quote, option, dict(policy), account_of(request)))


# -------------------------------------------------------------------------
# quote return, account, registration, and recovery
# -------------------------------------------------------------------------


@APP.get("/save/get-quote-login-form/", response_class=HTMLResponse)
def retrieve_page():
    return html(views.retrieve_quotes())


@APP.post("/save/get-quote-login-form/")
async def retrieve_page_post(request: Request):
    form = await request.form()
    email = str(form.get("email") or "").strip()
    dob = str(form.get("dob") or "").strip()
    try:
        birth_date = datetime.strptime(dob, "%m/%d/%Y").date().isoformat()
    except ValueError:
        return html(views.retrieve_quotes(error="Enter date of birth as MM/DD/YYYY."), 400)
    with db() as connection:
        quote = business.retrieve_quote(
            connection,
            email=email,
            birth_date=birth_date,
            new_owner_key=owner_key_of(request),
        )
    if quote is None:
        return html(
            views.retrieve_quotes(
                notice="If those details match a local quote, it is available after account sign-in."
            )
        )
    target = (
        f"/quote/{quote['id']}/results"
        if quote.get("options")
        else f"/quote/{quote['id']}/applicant"
    )
    return see_other(target)


@APP.get("/account/sign-in", response_class=HTMLResponse)
def sign_in_page(
    request: Request,
    email: str = "",
    provider: str = "",
    next: str = "/account/",
):
    if account_of(request):
        return see_other(_safe_next(next))
    notice = "Google sign-in is shown for source fidelity but is unavailable offline." if provider else ""
    return html(views.sign_in(email=email, notice=notice, next_url=_safe_next(next)))


@APP.post("/account/sign-in")
async def sign_in_post(request: Request):
    form = await request.form()
    email = str(form.get("email") or "").strip()
    password = str(form.get("password") or "")
    next_url = _safe_next(form.get("next"))
    old_owner = owner_key_of(request)
    try:
        result = AUTH.sign_in(
            str(request.state.auth_token), email=email, password=password
        )
    except AuthError:
        return html(
            views.sign_in(
                email=email,
                error="The email or password is incorrect.",
                next_url=next_url,
            ),
            400,
        )
    request.state.auth_token = result["session_token"]
    request.state.auth_info = {"authenticated": True, "account": result["account"]}
    with db() as connection:
        business.claim_quotes(
            connection, owner_key=old_owner, account_id=result["account"]["account_id"]
        )
    return see_other(next_url)


@APP.get("/account/register", response_class=HTMLResponse)
def register_page(request: Request):
    if account_of(request):
        return see_other("/account/")
    return html(views.register())


@APP.post("/account/register")
async def register_post(request: Request):
    form = await request.form()
    values = {
        "display_name": str(form.get("display_name") or "").strip(),
        "email": str(form.get("email") or "").strip(),
    }
    if str(form.get("terms") or "") not in {"on", "1"}:
        return html(views.register(values=values, error="Accept the terms to continue."), 400)
    try:
        AUTH.start_registration(
            str(request.state.auth_token),
            email=values["email"],
            display_name=values["display_name"],
            password=str(form.get("password") or ""),
            restart_invalid_flow=True,
        )
    except AuthRateLimited as exc:
        return html(
            views.register(
                values=values,
                error=f"Try again in {exc.retry_after} seconds.",
            ),
            429,
        )
    except (AuthConflict, AuthError) as exc:
        return html(views.register(values=values, error=str(exc)), 400)
    mail = AUTH.local_mail_for_session(
        str(request.state.auth_token), purpose="registration"
    )
    code = str(mail.get("verification_code") or "") if mail else ""
    return html(views.verify_registration(code=code))


@APP.post("/account/register/verify")
async def register_verify_post(request: Request):
    form = await request.form()
    old_owner = owner_key_of(request)
    try:
        AUTH.verify_registration_code(
            str(request.state.auth_token), str(form.get("code") or "")
        )
        result = AUTH.complete_registration(str(request.state.auth_token))
    except AuthError as exc:
        mail = AUTH.local_mail_for_session(
            str(request.state.auth_token), purpose="registration"
        )
        code = str(mail.get("verification_code") or "") if mail else ""
        return html(views.verify_registration(code=code, error=str(exc)), 400)
    request.state.auth_token = result["session_token"]
    request.state.auth_info = {"authenticated": True, "account": result["account"]}
    with db() as connection:
        business.claim_quotes(
            connection, owner_key=old_owner, account_id=result["account"]["account_id"]
        )
    return see_other("/account/?notice=Account+created")


@APP.get("/account/recover", response_class=HTMLResponse)
def recover_page():
    return html(views.recover())


@APP.post("/account/recover")
async def recover_post(request: Request):
    form = await request.form()
    try:
        result = AUTH.start_password_reset(
            str(request.state.auth_token),
            email=str(form.get("email") or ""),
            restart_invalid_flow=True,
        )
    except AuthRateLimited as exc:
        return html(views.recover(error=f"Try again in {exc.retry_after} seconds."), 429)
    except AuthError as exc:
        return html(views.recover(error=str(exc)), 400)
    mail = AUTH.local_mail_for_session(
        str(request.state.auth_token), purpose="password-reset"
    )
    code = str(mail.get("verification_code") or "") if mail else ""
    return html(views.recover(message=str(result["message"]), code=code))


@APP.post("/account/recover/complete")
async def recover_complete(request: Request):
    form = await request.form()
    try:
        AUTH.verify_password_reset_code(
            str(request.state.auth_token), str(form.get("code") or "")
        )
        token = AUTH.complete_password_reset(
            str(request.state.auth_token), new_password=str(form.get("password") or "")
        )
    except AuthError as exc:
        mail = AUTH.local_mail_for_session(
            str(request.state.auth_token), purpose="password-reset"
        )
        code = str(mail.get("verification_code") or "") if mail else ""
        return html(
            views.recover(
                message="Use the local reset code to choose a new password.",
                error=str(exc),
                code=code,
            ),
            400,
        )
    request.state.auth_token = token
    resolved = AUTH.resolve_session(token) or {}
    request.state.auth_info = resolved
    return see_other("/account/?notice=Password+updated")


@APP.post("/account/sign-out")
def sign_out(request: Request):
    AUTH.sign_out(str(request.state.auth_token))
    token = AUTH.create_anonymous_session()
    request.state.auth_token = token
    request.state.auth_info = {"authenticated": False, "account": None}
    return see_other("/")


@APP.get("/account/", response_class=HTMLResponse)
def dashboard(request: Request, notice: str = ""):
    account = account_of(request)
    if account is None:
        return see_other("/account/sign-in?next=/account/")
    with db() as connection:
        quotes = business.list_quotes(connection, str(account["account_id"]))
        policies = business.list_policies(connection, str(account["account_id"]))
    return html(views.dashboard(account, quotes, policies, notice=notice))


@APP.get("/account/policies")
def policy_collection(request: Request):
    return see_other("/account/")


@APP.get("/account/policies/{policy_id}", response_class=HTMLResponse)
def policy_detail(request: Request, policy_id: str, notice: str = ""):
    account = account_of(request)
    if account is None:
        return see_other(f"/account/sign-in?next=/account/policies/{policy_id}")
    with db() as connection:
        policy = business.get_policy(connection, policy_id, str(account["account_id"]))
    if policy is None:
        return html(views.not_found(account), 404)
    return html(views.policy_detail(account, policy, notice=notice))


@APP.post("/account/policies/{policy_id}/cancel")
def policy_cancel(request: Request, policy_id: str):
    account = account_of(request)
    if account is None:
        return see_other(f"/account/sign-in?next=/account/policies/{policy_id}")
    with db() as connection:
        changed = business.cancel_policy(connection, policy_id, str(account["account_id"]))
    notice = "Policy canceled in the offline fixture." if changed else "Policy was already canceled."
    return see_other(f"/account/policies/{policy_id}?notice={notice.replace(' ', '+')}")


@APP.get("/account/quotes/{quote_id}/documents", response_class=HTMLResponse)
def quote_documents(request: Request, quote_id: str):
    account = account_of(request)
    if account is None:
        return see_other(f"/account/sign-in?next=/account/quotes/{quote_id}/documents")
    with db() as connection:
        quote = business.get_quote(
            connection, quote_id, account_id=str(account["account_id"]), allow_seed=False
        )
        documents = business.list_documents(
            connection, quote_id=quote_id, account_id=str(account["account_id"])
        )
    if quote is None:
        return html(views.not_found(account), 404)
    return html(views.quote_documents(account, quote, documents))


@APP.post("/account/quotes/{quote_id}/cancel")
def quote_cancel(request: Request, quote_id: str):
    account = account_of(request)
    if account is None:
        return see_other("/account/sign-in?next=/account/")
    with db() as connection:
        changed = business.cancel_quote(
            connection,
            quote_id,
            owner_key=owner_key_of(request),
            account_id=str(account["account_id"]),
        )
    notice = "Quote canceled." if changed else "That quote cannot be canceled."
    return see_other(f"/account/?notice={notice.replace(' ', '+')}")


# -------------------------------------------------------------------------
# remaining captured content and branded recovery
# -------------------------------------------------------------------------


@APP.get("/{path:path}", response_class=HTMLResponse)
def content_or_not_found(request: Request, path: str):
    key = path.strip("/")
    if key == "company/contact":
        return html(views.contact_page(account_of(request)))
    page = PUBLIC_PAGES.get(key)
    if page:
        title, subtitle, category, sections = page
        return html(
            views.article(
                title,
                subtitle=subtitle,
                canonical_path=key,
                account=account_of(request),
                category=category,
                sections=sections,
                page_class=(
                    "article-page car-article-page"
                    if key == "car-insurance"
                    else "article-page"
                ),
            )
        )
    return html(views.not_found(account_of(request)), 404)


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(
        APP,
        host=os.environ.get("HOST", "127.0.0.1"),
        port=int(os.environ.get("PORT", "8000")),
    )