File size: 99,866 Bytes
366d6fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Polished, functional and entirely local Angi WebsiteBench clone."""

from __future__ import annotations

import html
import json
import os
import secrets
from pathlib import Path
from typing import Any
from urllib.parse import parse_qs, urlencode

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

from angi_app import db, seed
from angi_app.api import Ctx, ensure_profile, router, set_cookie
from angi_app.services import SERVICES

SITE_ID = "angi"
ROOT = Path(__file__).resolve().parent
ARTICLE_TOPICS = [
    "planning-a-local-plumbing-project",
    "questions-to-ask-a-home-service-pro",
    "understanding-a-synthetic-project-estimate",
    "preparing-for-a-repair-visit",
    "comparing-home-service-quotes",
    "seasonal-home-maintenance-checklist",
    "when-to-repair-or-replace-a-fixture",
    "how-to-document-a-home-project",
    "building-a-realistic-remodel-budget",
    "simple-ways-to-prevent-water-damage",
    "choosing-a-project-time-window",
    "reading-a-local-provider-profile",
    "organizing-project-messages",
    "home-safety-before-a-service-visit",
    "what-a-project-deposit-means",
    "reviewing-completed-local-work",
    "planning-an-electrical-inspection",
    "preparing-for-seasonal-hvac-service",
    "painting-project-scope-basics",
    "roof-maintenance-planning",
    "one-time-cleaning-project-guide",
    "landscaping-project-checklist",
    "handyperson-visit-preparation",
    "keeping-project-records-together",
]
HUB_PATHS = {
    "appliances",
    "construction",
    "electrical",
    "flooring",
    "foundation",
    "home-exterior",
    "home-interior",
    "hvac",
    "landscaping",
    "pest-control",
    "plumbing",
    "real-estate",
    "remodeling",
    "roofing-siding",
    "outdoor-property",
    "waste-disposal",
}
POPULAR_CATEGORY_SLUGS = """
asbestos-abatement awning-contractors basement-leak-repair basement-remodeling basement-waterproofing bathtub-refinishing blind-installers carpet-installation carpet-stretching countertop-contractors crawl-space-encapsulation deck-cleaning deck-repair deck-staining demolition-services door-installation drainage-companies driveway-sealcoating dryer-vent-companies drywall-installers emergency-plumbers emergency-roofing excavation-companies exterior-painting fireplace-repair flooring-companies foundation-contractors foundation-repair furnace-repair furniture-refinishing garage-floor-coatings garage-remodeling gardeners ge-appliance-repair generator-installation generator-repair gravel-driveway-companies home-additions home-remodeling house-appraisers hvac-repairs install-above-ground-pools install-chain-link-fence install-seamless-gutters install-security-cameras install-water-softener interior-painting junk-removal kitchen-remodeling lawn-aeration masonry metal-roof-installers metal-roofers natural-gas-plumbers paint-stripping patio-companies plumbing plumbing-handymen plumbing-repair pool-liner-installation pool-repair pool-services power-washing recliner-repair repair-home-audio repair-patio-furniture roof-repair roof-siding sandblasting-services septic-tank-companies shed-construction shower-door-installation shower-installers siding-contractors soil-delivery spray-foam-insulation sprinkler-repair tile-contractors tree-trimming tv-antenna-installation tv-mount-install wallpaper-installation wasp-bee-removal weed-services welding-services well-pump-repair-service whirlpool-appliance-repair window-ac-repair window-cleaning window-companies window-screen-repair wood-floor-refinishing yard-clean-up
""".split()
HEADER_MENUS = (
    (
        "Interior",
        "/home-interior",
        (("Appliance Repair", "appliance-repair"), ("Carpet Cleaning", "carpet-cleaning"), ("Contractors", "contractor"), ("Drywall", "drywall"), ("Electrical", "electrical"), ("Flooring", "flooring"), ("HVAC", "hvac"), ("House Cleaning", "house-cleaning"), ("Interior Painting", "interior-painting"), ("Plumbing", "plumbing"), ("Remodeling", "kitchen-and-bath-remodeling")),
        (("How Much Does a Closet Remodel Cost?", "/articles/closet-remodel-cost.htm"), ("How Much Does It Cost to Build or Replace a Staircase?", "/articles/how-much-does-building-stairs-and-railings-cost.htm"), ("How Much Does Widening a Doorway Cost?", "/articles/widening-doorway-cost.htm"), ("How Much Does Wallpaper Removal Cost?", "/articles/how-much-does-it-cost-remove-wallpaper.htm")),
    ),
    (
        "Exterior",
        "/home-exterior",
        (("Concrete Repair", "concrete-repair"), ("Doors", "doors"), ("Driveways", "driveways"), ("Exterior Painting", "exterior-painting"), ("Garage Doors", "garage-doors"), ("Gutter Cleaning", "gutter-cleaning"), ("Gutter Repair", "gutter-repair-replacement"), ("Home Builders", "home-builders"), ("Masonry", "masonry"), ("Roofing", "roofing"), ("Siding", "siding"), ("Windows", "windows")),
        (("How Much Does It Cost to Install Exterior Trim?", "/articles/exterior-trim-installation-cost.htm"), ("How Much Does Ipe Wood Decking Cost?", "/articles/how-much-does-ipe-wood-decking-cost.htm"), ("How Much Does a Dog Fence Cost to Install?", "/articles/different-types-dog-fences-and-how-much-they-cost.htm"), ("How Much Does It Cost to Pressure Wash a House?", "/articles/how-much-does-it-cost-pressure-wash-house.htm")),
    ),
    (
        "Lawn & Garden",
        "/landscaping",
        (("Decks", "decks-and-porches"), ("Fencing", "fencing"), ("Land Surveying", "land-surveying"), ("Landscaping", "landscaping"), ("Lawn & Yard Work", "lawn-and-yard-work"), ("Leaf Removal", "leaf-removal"), ("Patios", "sunroom-and-patio-remodeling"), ("Pool Installation", "swimming-pools"), ("Sprinkler Systems", "lawn-irrigation"), ("Sunrooms", "sunroom-contractors"), ("Tree Service", "tree-service")),
        (("How Much Does Interlocking Paver Installation Cost?", "/articles/interlocking-pavers-cost.htm"), ("How Much Does a Land Survey Cost?", "/articles/how-much-does-land-survey-cost.htm"), ("How Much Does Flowerbed Installation Cost?", "/articles/flowerbed-installation-cost.htm"), ("How Much Does Site Preparation Cost?", "/articles/site-preparation-cost.htm")),
    ),
    (
        "More",
        "/articles",
        (("Basement Waterproofing", "basement-waterproofing"), ("Handyperson", "handyman-service"), ("Junk Hauling", "hauling"), ("Locksmiths", "locksmiths"), ("Moving Companies", "moving"), ("Pest Control", "pest-control"), ("Pressure Washing", "pressure-washing"), ("Septic Tanks", "septic-tank")),
        (("How Much Does It Cost to Remodel a House?", "/articles/how-much-does-it-cost-to-remodel-a-house.htm"), ("How Much Do Well Water Treatment Systems Cost?", "/articles/well-water-treatment-systems-cost.htm"), ("How Much Does It Cost to Replace Weatherstripping?", "/articles/weatherstripping-replacement-cost.htm"), ("How Much Does It Cost to Rent a Dump Trailer?", "/articles/cost-to-rent-a-dump-trailer.htm")),
    ),
    (
        "Articles & Advice",
        "/articles",
        (("Appliances", "/appliances"), ("Foundation", "/foundation"), ("Bathroom Remodeling", "/remodeling/bathroom-remodeling"), ("Chimney", "/home-exterior/chimney"), ("Home Cleaning", "/home-interior/home-cleaning"), ("New Build", "/construction/new-build"), ("Electrical", "/electrical"), ("Flooring", "/flooring"), ("Furniture", "/home-interior/furniture"), ("Driveway", "/outdoor-property/driveway"), ("HVAC", "/hvac"), ("Construction", "/construction"), ("Home Exterior", "/home-exterior"), ("Home Interior", "/home-interior"), ("Kitchen Remodeling", "/remodeling/kitchen-remodeling"), ("Landscaping", "/landscaping"), ("Moving & Relocation", "/real-estate/moving-relocation"), ("Outdoor Living", "/outdoor-property/outdoor-living"), ("Pest Control", "/pest-control"), ("Plumbing", "/plumbing"), ("Real Estate", "/real-estate"), ("Remodeling", "/remodeling"), ("Roofing & Siding", "/roofing-siding"), ("Waste Disposal", "/waste-disposal"), ("Project Cost Center", "/articles/cost")),
        (("How Much Does It Cost to Paint Your Home?", "/articles/cost-paint-interior-and-exterior.htm"), ("How Much Does It Cost to Repair a Linoleum Floor?", "/articles/linoleum-floor-repair-cost.htm"), ("How Much Does HVAC Maintenance Cost?", "/articles/ac-service-cost.htm"), ("How Much Does Solar Water Heater Repair Cost?", "/articles/solar-water-heater-repair-cost.htm")),
    ),
)
SERVICE_PRESENTATIONS = {
    "plumbing": ("plumbers", "plumbing-hero.jpg", "plumbing-hero-mobile.jpg"),
    "electrical": ("electrical pros", "heroes/hero-electrician.jpg", "heroes/hero-electrician.jpg"),
    "heating-cooling": ("heating and cooling pros", "hvac.jpg", "hvac.jpg"),
    "interior-painting": ("interior painting pros", "article-family-kitchen.jpg", "article-family-kitchen-small.jpg"),
    "roofing": ("roofing pros", "roofing.jpg", "roofing.jpg"),
    "house-cleaning": ("house cleaning pros", "cleaning.jpg", "cleaning.jpg"),
    "landscaping": ("landscaping pros", "heroes/hero-gardening.jpg", "heroes/hero-gardening.jpg"),
    "handyman": ("handyperson pros", "handyperson.jpg", "handyperson.jpg"),
}
app = FastAPI(title="Angi local home services", docs_url=None, redoc_url=None, openapi_url=None)
app.include_router(router)
app.mount("/static", StaticFiles(directory=ROOT / "static"), name="static")


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


def category_navigation() -> str:
    menus = []
    for label, view_all, primary, research in HEADER_MENUS:
        primary_links = "".join(
            f'<a href="{esc(path if path.startswith("/") else f"/nearme/{path}/")}">{esc(name)}</a>'
            for name, path in primary
        )
        research_links = "".join(
            f'<a href="{esc(path)}">{esc(name)}</a>' for name, path in research
        )
        primary_heading = "Research & plan" if label == "Articles & Advice" else "Find a pro"
        secondary_heading = "Featured articles" if label == "Articles & Advice" else "Research & plan"
        menus.append(
            f'<details class="category-menu"><summary>{esc(label)}</summary><div class="category-panel">'
            f'<section><b>{primary_heading}</b><nav>{primary_links}</nav><a class="view-all" href="{esc(view_all if label == "Articles & Advice" else "/nearme/")}">View all</a></section>'
            f'<section><b>{secondary_heading}</b><nav>{research_links}</nav><a class="view-all" href="{esc(view_all)}">View all</a></section>'
            "</div></details>"
        )
    return "".join(menus)


def popular_categories() -> str:
    links = "".join(
        f'<a href="/nearme/{slug}/">{esc("plumbers" if slug == "plumbing" else slug.replace("-", " "))} near me</a>'
        for slug in POPULAR_CATEGORY_SLUGS
    )
    return f'<section class="popular-categories"><details><summary>Popular Categories</summary><nav>{links}</nav></details></section>'


def source_footer() -> str:
    return """<footer class="source-footer"><div class="footer-main"><section class="footer-app"><h2>Get our Angi-powered app</h2><p>Download the app</p><div><a href="/external/app-store"><small>Download on the</small><b>App Store</b></a><a href="/external/google-play"><small>Get it on</small><b>Google Play</b></a></div></section><div class="footer-columns"><details class="footer-column" open><summary>Homeowner services</summary><nav><a href="/companylist/">Find local businesses</a><a href="/nearme/">Services near me</a></nav></details><details class="footer-column" open><summary>For service pros</summary><nav><a href="/register?role=provider">Register your business</a><a href="/pro/register">Business center</a></nav></details><details class="footer-column" open><summary>Resources</summary><nav><a href="/articles">Solution center</a><a href="/articles/cost">Project cost center</a><a href="/faq">FAQs</a></nav></details><details class="footer-column" open><summary>About us</summary><nav><a href="/how-it-works.htm">How it works</a><a href="/aboutus.htm">Who we are</a><a href="/careers">Careers</a><a href="/in-the-press.htm">Press</a><a href="/external/investor-relations">Investor relations</a><a href="/contact-us">Contact us</a><a href="/happiness-guarantee.htm">Happiness guarantee</a><a href="/landing/affiliatepartners">Affiliate partners</a></nav></details></div><div class="footer-legal"><img src="/static/source/icons/angi_logo.svg" alt="Angi"><nav><a href="/terms">Terms of Use</a><a href="/privacy">Privacy Policy</a><a href="/external/accessibility-tools">Accessibility Tools</a><a href="/do-not-sell">Do Not Sell or Share My Personal Information</a></nav><span>© Copyright 1995-2026, Angi. All Rights Reserved.</span></div><nav class="footer-social" aria-label="Social links"><a href="/external/x" aria-label="X">𝕏</a><a href="/external/facebook" aria-label="Facebook">f</a><a href="/external/pinterest" aria-label="Pinterest">p</a><a href="/external/youtube" aria-label="YouTube">▶</a><a href="/external/instagram" aria-label="Instagram">◎</a></nav></div></footer>"""


def service_presentation(slug: str, label: str) -> tuple[str, str, str]:
    if slug in SERVICE_PRESENTATIONS:
        return SERVICE_PRESENTATIONS[slug]
    groups = (
        (("roof", "gutter"), "heroes/hero-gutter.jpg"),
        (("tree", "lawn", "garden", "yard", "weed", "landscap", "soil", "sprinkler"), "heroes/hero-gardening.jpg"),
        (("electric", "generator", "security", "tv-", "antenna"), "heroes/hero-electrician.jpg"),
        (("insulation", "furnace", "hvac", "ac-repair"), "heroes/hero-insulation.jpg"),
        (("crawl", "basement", "foundation", "pest", "wasp"), "heroes/hero-crawlspace.jpg"),
        (("siding", "window", "exterior", "awning"), "heroes/hero-vinyl.jpg"),
        (("deck", "patio", "door", "driveway", "masonry", "concrete", "shed", "pool"), "heroes/hero-framing.jpg"),
        (("plumb", "drain", "water", "well", "septic"), "plumbing-hero.jpg"),
        (("clean", "carpet", "shower", "bathtub", "tile", "wallpaper", "furniture", "recliner"), "cleaning.jpg"),
    )
    hero = next((image for terms, image in groups if any(term in slug for term in terms)), "handyperson.jpg")
    noun = "plumbers" if slug == "plumbing" else f"{label.lower()} pros"
    return noun, hero, hero


def money(cents: int) -> str:
    return f"${cents / 100:,.0f}"


def current(request: Request) -> Ctx:
    return Ctx(request)


def layout(request: Request, title: str, body: str, *, active: str = "") -> HTMLResponse:
    c = current(request)
    signed_in = bool(c.account_id and c.profile)
    # Keep the deterministic fixture visibly authenticated without rendering
    # account-specific source data in captures or committed artifacts.
    label = "Hi Member" if signed_in else "Hi Homeowner"
    avatar = "S"
    account = "/account" if signed_in else "/login"
    if signed_in:
        primary_links = f"<a class='{'on' if active == 'services' else ''}' href='/search'>✦ Find Pros</a><a class='{'on' if active == 'projects' else ''}' href='/myprojects'>My Projects</a><a href='/inbox?state=source'>Inbox</a>"
        header_actions = f"<a class='header-search' href='/search' aria-label='Search'><img src='/static/source/icons/search.svg' alt=''></a><a class='login' href='{account}'><span>{avatar}</span><b>{esc(label)}</b></a><button class='menu-button' type='button' aria-label='Open menu'><img src='/static/source/icons/hamburger.svg' alt=''></button>"
    else:
        primary_links = f"<a class='{'on' if active == 'services' else ''}' href='/search'>✦ Find Pros</a><a href='/register?role=provider'>Join as a Pro</a>"
        header_actions = "<a class='header-search' href='/search' aria-label='Search'><img src='/static/source/icons/search.svg' alt=''></a><a class='guest-login' href='/login'>Log In</a><a class='signup' href='/register'>Sign Up</a><button class='menu-button' type='button' aria-label='Open menu'><img src='/static/source/icons/hamburger.svg' alt=''></button>"
    category_links = category_navigation()
    return HTMLResponse(f"""<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>{esc(title)} | Angi</title><link rel="icon" href="/static/favicon.svg"><link rel="stylesheet" href="/static/site.css?v=angi-r23"></head>
<body><a class="skip" href="#main">Skip to content</a><div class="sandbox" hidden>WebsiteBench local home-services sandbox — no real provider is contacted and no real payment is made.</div>
<header class="source-header"><a class="logo" href="/" aria-label="Angi home"><img src="/static/source/icons/angi_logo.svg" alt="Angi"></a><a class="desktop-service-search" href="/search">How can we help?</a><nav class="primary-links" aria-label="Primary">{primary_links}</nav><div class="header-actions">{header_actions}</div><nav class="category-links" aria-label="Project categories">{category_links}</nav></header>
<main id="main">{body}</main>{source_footer()}
<div id="toast" role="status" aria-live="polite"></div><script src="/static/app.js?v=angi-r23"></script></body></html>""")


def provider_card(provider: dict[str, Any]) -> str:
    services = json.loads(provider["services_json"])
    service_label = services[0].replace("-", " ").title()
    badges = "".join(["<span>✓ Screened</span>" if provider["verified"] else "", "<span>Licensed</span>" if provider["licensed"] else "", "<span>Insured</span>" if provider["insured"] else ""])
    return f"""<article class="pro-card"><a class="pro-avatar" href="/pros/{esc(provider['slug'])}">{''.join(x[0] for x in provider['name'].split()[:2])}</a><div class="pro-main"><p class="eyebrow">{esc(service_label)}</p><h3><a href="/pros/{esc(provider['slug'])}">{esc(provider['name'])}</a></h3><p class="rating"><b>★ {provider['rating']:.1f}</b> · {provider['review_count']} reviews · {provider['years_in_business']} years</p><div class="badges">{badges}</div><p>{esc(provider['bio'])}</p><div class="card-foot"><span>Responds in about {provider['response_minutes']} min</span><a class="button small" href="/pros/{esc(provider['slug'])}">View profile</a><button class="save" data-favorite="{esc(provider['provider_id'])}" aria-label="Save {esc(provider['name'])}">♡</button></div></div></article>"""


@app.get("/healthz")
def healthz() -> JSONResponse:
    with SERVICES.auth.connect() as connection:
        connection.execute("SELECT 1").fetchone()
    build = os.environ.get("DEPLOYMENT_BUILD_ID", os.environ.get("SOURCE_REF", ""))
    return JSONResponse({"ok": True, "site_id": SITE_ID, "version": "angi-offline-v1"}, headers={"X-WebsiteBench-Container-Build-ID": build})


def _verification_token(request: Request) -> bool:
    expected = os.environ.get("WEBSITEBENCH_VERIFY_TOKEN", "")
    supplied = request.headers.get("x-websitebench-verify-token", "")
    return bool(expected and supplied and secrets.compare_digest(expected, supplied))


@app.post("/__websitebench__/session")
async def verification_session(request: Request) -> JSONResponse:
    """Create one guarded, deterministic local browser fixture session."""

    if not _verification_token(request):
        return JSONResponse({"error": "fixture endpoint unavailable"}, status_code=404)
    form = parse_qs((await request.body()).decode("utf-8", "replace"))
    actor = str((form.get("actor") or ["homeowner"])[0])
    if actor not in {"homeowner", "provider"}:
        return JSONResponse({"error": "unknown fixture actor"}, status_code=422)
    email = f"verify-{actor}@angi.example.test"
    password = "LocalFixture!2026"
    account_id = SERVICES.auth.seed_account(
        subject_id=f"angi-verify-{actor}",
        email=email,
        display_name=f"Synthetic {actor.title()}",
        password=password,
        email_verified=True,
    )
    session_token, _ = SERVICES.auth.ensure_session(None)
    signed_in = SERVICES.auth.sign_in(session_token, email=email, password=password)
    account = signed_in["account"]
    with SERVICES.auth.connect() as connection:
        ensure_profile(
            connection,
            account_id=account_id,
            email=email,
            name=account["display_name"],
        )
        connection.execute(
            "UPDATE an_profiles SET role=?,phone=?,city=?,state=?,zip=? WHERE account_id=?",
            (actor, "212-555-0100", "Brooklyn", "NY", "11201", account_id),
        )
        project_id = f"fixture-{actor}-project"
        connection.execute(
            """INSERT OR IGNORE INTO an_projects(
                 project_id,account_id,service_slug,title,status,current_step,
                 scope_json,location_json,schedule_json,confirmation_code,
                 hired_provider_id,selected_quote_id,appointment_at,deposit_cents,
                 final_cents,refund_cents,created_at,updated_at
               ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
            (
                project_id,
                account_id,
                "plumbing",
                "Synthetic plumbing repair",
                "matched",
                5,
                db.dumps({"issue": "leak", "description": "Synthetic fixture"}),
                db.dumps({"city": "Brooklyn", "state": "NY", "zip": "11201"}),
                db.dumps({"date": "2026-09-12", "time_window": "morning"}),
                "ANG-FIXTURE",
                None,
                None,
                None,
                0,
                0,
                0,
                1,
                1,
            ),
        )
        connection.execute(
            "INSERT OR IGNORE INTO an_quotes VALUES (?,?,?,?,?,?,?,?,?,?)",
            (
                f"fixture-{actor}-quote",
                project_id,
                "pro-brightpipe",
                64000,
                12800,
                1,
                "2026-09-12 09:00",
                "Synthetic diagnostic quote.",
                "offered",
                1,
            ),
        )
        connection.execute(
            "INSERT OR IGNORE INTO an_messages VALUES (?,?,?,?,?,?)",
            (
                f"fixture-{actor}-message",
                project_id,
                "pro-brightpipe",
                "provider",
                "Synthetic local fixture message.",
                1,
            ),
        )
        connection.execute(
            "INSERT OR IGNORE INTO an_events VALUES (?,?,?,?,?)",
            (
                f"fixture-{actor}-event",
                project_id,
                "matched",
                "Synthetic providers matched locally",
                1,
            ),
        )
        connection.execute(
            "INSERT OR IGNORE INTO an_favorites VALUES (?,?,?)",
            (account_id, "pro-brightpipe", 1),
        )
    response = JSONResponse({"ok": True, "actor": actor, "project_id": project_id})
    set_cookie(response, request, signed_in["session_token"])
    return response


@app.post("/__websitebench__/reset")
def verification_reset(request: Request) -> JSONResponse:
    """Reset all site-owned and auth state behind the same verifier token."""

    if not _verification_token(request):
        return JSONResponse({"error": "fixture endpoint unavailable"}, status_code=404)
    SERVICES.auth.reset_site_state(
        site_reset=seed.reset_business_state,
        seed_accounts=[],
    )
    return JSONResponse({"ok": True, "site_id": SITE_ID, "reset": "deterministic"})


@app.get("/")
def home(request: Request) -> HTMLResponse:
    categories = [
        ("handyman", "handyperson", "Handyperson"), ("landscaping", "landscaping", "Landscaping"),
        ("plumbing", "plumbing", "Plumbing"), ("electrical", "electrical", "Electrical"),
        ("handyman", "remodeling", "Remodeling"), ("roofing", "roofing", "Roofing"),
        ("interior-painting", "painting", "Painting"), ("house-cleaning", "cleaning", "Cleaning"),
        ("heating-cooling", "hvac", "HVAC"), ("handyman", "windows", "Windows"),
        ("handyman", "concrete", "Concrete"),
    ]
    service_cards = "".join(
        f"<a class='home-category' href='/services/{slug}'><img src='/static/source/icons/{icon}.svg' alt=''><span>{label}</span></a>"
        for slug, icon, label in categories
    )
    demand_items = [
        ("house-cleaning", "cleaning", "Cleaning &amp; Maid Services", 13),
        ("heating-cooling", "hvac", "Air Conditioning", 8),
        ("roofing", "roofing", "Roofing", 7),
        ("handyman", "handyperson", "Handyman Service", 7),
        ("landscaping", "landscaping", "Landscaping", 6),
        ("handyman", "remodeling", "Addition and Remodeling", 6),
        ("pest-control", "landscaping", "Pest Control", 5),
        ("interior-painting", "painting", "Painting", 5),
    ]
    demand_cards = "".join(
        f'<a class="demand-card" href="/search?service={slug}&amp;zip=90013"><img src="/static/source/icons/{icon}.svg" alt=""><span><b>{label}</b><small><em>⌁</em> {count} homeowners interested</small></span></a>'
        for slug, icon, label, count in demand_items
    )
    project_items = [
        ("/services/handyman", "handyperson.jpg", "Handyperson for Small Projects", "4.6", "599k+", "$158"),
        ("/services/house-cleaning", "cleaning.jpg", "One-time Cleaning Service", "4.5", "314k+", "$102"),
        ("/services/heating-cooling", "hvac.jpg", "Air Conditioning Service &amp; Repair", "4.7", "306k+", "$350"),
        ("/services/plumbing", "plumbing.jpg", "Faucet &amp; Plumbing Repair Services", "4.6", "568k+", "$226"),
        ("/services/roofing", "roofing.jpg", "Roof Installation &amp; Repair", "4.7", "325k+", "$471"),
        ("/search?q=bathroom", "bathroom.jpg", "Bathroom Remodel", "4.4", "180k+", "$2,500"),
    ]
    project_cards = [
        f'<a class="home-project-card" href="{href}"><div><b>{title}</b><p><span>★</span> {rating} ({reviews}) <i>|</i> from {price}</p></div><img src="/static/source/{image}" alt="{title}"></a>'
        for href, image, title, rating, reviews, price in project_items
    ]
    cost_guides = [
        ("article-baseboard-heat.jpg", "new-furnace-cost", "LAUREN BONGARD", "MAR 17, 2026", "How Much Does a New Furnace Cost? [2026 Data]", "When it’s time to replace the furnace, review this guide for new furnace costs based on type, size, and efficiency, plus furnace installation costs."),
        ("article-snow-house.jpg", "roof-snow-removal-cost", "ANGI", "MAR 5, 2026", "How Much Does Roof Snow Removal Cost? [2026 Data]", "Discover the average cost of roof snow removal, key price factors, and ways to save. Get transparent estimates to protect your home this winter."),
        ("article-snow-suburban.jpg", "insulation-installation-cost", "RACHEL HOFFMAN", "MAY 30, 2026", "How Much Does Insulation Installation Cost? [2026 Data]", "New insulation can make your home more comfortable and boost energy efficiency. Use this insulation cost guide to get an accurate estimate for the installation."),
        ("plumbing.jpg", "plumbing-repair-cost", "STEPHANIE MICKELSON", "MAR 17, 2026", "How Much Does Plumbing Repair Cost? [2026 Data]", "The costs for common plumbing issues are determined based on parts, labor, and expertise level. Read our guide to find out how much you should budget."),
        ("cleaning.jpg", "deep-cleaning-house-cost", "ANGI", "MAR 17, 2026", "How Much Does Deep Cleaning a House Cost? [2026 Data]", "Discover the average cost of deep cleaning a house, key price factors, and tips to save. Get accurate estimates to plan your next deep clean with confidence."),
        ("article-cozy-family.jpg", "winterize-house-cost", "RACHEL HOFFMAN", "AUG 3, 2026", "How Much Does It Cost to Winterize a House? [2026 Data]", "Winterizing a house depends on its type, size, location, and more. Our guide breaks down how much it costs to winterize a home."),
    ]
    cost_guide_cards = "".join(
        f'<article class="cost-guide-card"><a href="/articles/{slug}.htm"><img src="/static/source/{image}" alt="{title}"><small>{author} &nbsp;·&nbsp; {date}</small><h3>{title}</h3><p>{intro}</p></a></article>'
        for image, slug, author, date, title, intro in cost_guides
    )
    body = f"""<section class="hero angi-home-hero"><div class="hero-carousel" aria-hidden="true"><img data-hero="vinyl" src="/static/source/heroes/hero-vinyl.jpg" alt=""><img class="active" data-hero="tree" src="/static/source/heroes/hero-tree.jpg" alt=""><img data-hero="roofer" src="/static/source/hero-roofer.jpg" alt=""><img data-hero="electrician" src="/static/source/heroes/hero-electrician.jpg" alt=""><img data-hero="insulation" src="/static/source/heroes/hero-insulation.jpg" alt=""><img data-hero="framing" src="/static/source/heroes/hero-framing.jpg" alt=""><img data-hero="crawlspace" src="/static/source/heroes/hero-crawlspace.jpg" alt=""><img data-hero="gutter" src="/static/source/heroes/hero-gutter.jpg" alt=""><img data-hero="gardening" src="/static/source/heroes/hero-gardening.jpg" alt=""></div><div class="hero-overlay"><h1>The one you trust to find the ones you trust.</h1><form class="hero-form" action="/search"><label class="service-search"><span class="sr-only">What can we help you with?</span><input name="q" placeholder="What can we help you with?" autocomplete="off"></label><label class="zip-search"><span aria-hidden="true">⌖</span><span class="sr-only">Zip Code</span><input name="zip" value="90013" aria-label="Zip Code" inputmode="numeric" pattern="[0-9]{{5}}"></label><button type="submit" aria-label="Search local pros">⌕</button></form></div></section>
<section class="home-category-strip" aria-label="Popular project categories">{service_cards}</section>
<section class="resume-project"><h2>Pick up where you left off</h2><article><div><p>BASED ON YOUR RECENT SEARCH</p><h3>Foundation, Basement or Crawlspace - Waterproofing / Encapsulation</h3><a href="/search?q=foundation+waterproofing&amp;zip=90013">Resume</a></div><div class="resume-portraits" aria-hidden="true"><img src="/static/source/mitchell-grant.jpg" alt=""><img src="/static/source/handyperson.jpg" alt=""><img src="/static/source/hero-roofer.jpg" alt=""><img src="/static/source/cleaning.jpg" alt=""></div></article></section>
<section class="demand-section"><h2>Most in-demand home services in <em>90013</em></h2><p>Don't miss your chance to book a pro</p><div class="demand-list">{demand_cards}</div></section>
<section class="cost-guide-signup"><div><h2>Knowledge is priceless - so our cost guides are free.</h2><p>Sign up to get free project cost info in your inbox.</p></div><form action="/articles/cost"><label><span>✉</span><input type="email" name="email" placeholder="Email address" required></label><label><span>⌖</span><input name="zip" value="90013" aria-label="ZIP Code" inputmode="numeric" pattern="[0-9]{{5}}" required></label><button type="submit">Sign me up</button></form></section>
<section class="home-project-section"><h2>Popular home projects</h2><div class="home-image-grid">{''.join(project_cards[:3])}</div></section>
<section class="home-project-section"><h2>Keep your home in tip-top shape</h2><div class="home-image-grid">{''.join(project_cards[3:])}</div></section>
<section class="popular-cost-guides"><div><h2>Popular cost guides</h2><p>From average costs to expert advice, get all the answers you need to get your job done.</p><a class="cost-guide-all" href="/articles/cost">See all articles</a><div class="cost-guide-grid">{cost_guide_cards}</div></div></section>
{popular_categories()}"""
    return layout(request, "Home services made simple", body, active="services")


def search_gate_modal() -> str:
    """Source-observed public search gate; submission stays inside the local clone."""

    underlay = """<div class="pro-search-underlay" aria-hidden="true"><div class="pro-underlay-head"><img src="/static/source/icons/angi_logo.svg" alt=""><span>Pro Directory</span><i>⌕</i><b>eg: roof inspection, faucet repair, etc.</b><em>●</em><small>zip code</small></div><nav class="pro-underlay-nav"><span>House⌄</span><span>Yard⌄</span><span>Health⌄</span><span>More⌄</span></nav><section class="pro-underlay-filter"><p>Search Results:</p><div><b>Distance: Any⌄</b><b>Begins With: All⌄</b><i>Angi Certified</i><i>Super Service Award</i><i>Offers Discount</i><a>Reset All Filters</a></div><button>Filter Results&nbsp; ›</button></section><div class="pro-underlay-cards"><article><header>●&nbsp; Angi Certified</header><div class="skeleton wide"></div><div class="skeleton short"></div><h3>★★★★★ <b>5.0</b> ( &nbsp; )</h3><p>♢&nbsp; Offers Coupon</p><p>⌖&nbsp; Serves</p><p>❇&nbsp; Super Service Award</p><div class="skeleton rows"></div><button>Request a Quote</button></article><article><header>●&nbsp; Angi Certified</header><div class="skeleton wide"></div><div class="skeleton short"></div><h3>★★★★★ <b>5.0</b> ( &nbsp; )</h3><p>♢&nbsp; Offers Coupon</p><p>⌖&nbsp; Serves</p><p>❇&nbsp; Super Service Award</p><div class="skeleton rows"></div><button>Request a Quote</button></article></div><div class="pro-underlay-lower"><article><b>5.0</b><div class="skeleton rows"></div><button>Request a Quote</button></article><aside>Helpful Topics<hr>What keeps reviews honest?<br>How are companies displayed?<br>What is Angi's background check policy?</aside></div></div>"""
    return underlay + """<div class="pro-search-gate" role="presentation"><section class="pro-search-dialog" role="dialog" aria-modal="true" aria-labelledby="pro-search-title"><svg class="pro-search-book" aria-hidden="true" viewBox="0 0 64 64"><path d="M18 8h30v48H18zM12 14h8M12 24h8M12 34h8M12 44h8M12 54h8"/><circle cx="33" cy="25" r="7"/><path d="M23 46c0-7 4-11 10-11s10 4 10 11v5H23z"/></svg><h2 id="pro-search-title">Find Pros for your Project</h2><p>Enter a category and zip code to search for local pros.</p><form action="/search"><label><img src="/static/source/icons/search.svg" alt=""><input name="q" placeholder="eg: roof inspection, faucet repair, etc."></label><label><svg aria-hidden="true" viewBox="0 0 24 24"><path fill-rule="evenodd" clip-rule="evenodd" d="M12.6545 11.0434L8.00076 17.5591L3.3466 11.0437C0.642577 7.25828 3.34848 2 8.00046 2C12.6523 2 15.3582 7.25796 12.6545 11.0434ZM1.71917 12.2062C-1.93044 7.09707 1.72171 0 8.00046 0C14.279 0 17.9312 7.09665 14.282 12.2058L9.24007 19.265C8.63272 20.1153 7.36896 20.1154 6.76156 19.2651L1.71917 12.2062ZM7.99995 9C9.10452 9 9.99995 8.10457 9.99995 7C9.99995 5.89543 9.10452 5 7.99995 5C6.89538 5 5.99995 5.89543 5.99995 7C5.99995 8.10457 6.89538 9 7.99995 9Z"/></svg><input name="zip" placeholder="zip code" inputmode="numeric"></label><button type="submit">Search</button></form></section></div>"""


@app.get("/search")
def search(request: Request) -> HTMLResponse:
    q = request.query_params
    query = q.get("q", "").strip().lower()
    service = q.get("service", "")
    zip_code = q.get("zip", "")
    verified = q.get("verified") == "1"
    rating = float(q.get("rating", "0") or 0)
    price = int(q.get("price", "0") or 0)
    sort = q.get("sort", "recommended")
    try:
        page = max(1, int(q.get("page", "1") or 1))
    except ValueError:
        page = 1
    if not q:
        states = [
            "Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware",
            "Washington DC", "Florida", "Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa",
            "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota",
            "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico",
            "New York", "North Carolina", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island",
            "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington",
            "West Virginia", "Wisconsin", "Wyoming",
        ]
        state_links = "".join(f"<a href='/search?state={esc(state.lower().replace(' ', '-'))}'>{esc(state)} Pros</a>" for state in states)
        body = f"""<section class="directory-hero"><img src="/static/source/companylist-hero.jpg" alt="Local home service pro at work"><div class="directory-overlay"><h1>Find top-rated pros in your area.</h1><form action="/search"><label><span class="sr-only">What can we help you with?</span><input name="q" placeholder="What can we help you with?"></label><label class="directory-zip"><svg aria-hidden="true" viewBox="0 0 24 24"><path fill-rule="evenodd" clip-rule="evenodd" d="M12.6545 11.0434L8.00076 17.5591L3.3466 11.0437C0.642577 7.25828 3.34848 2 8.00046 2C12.6523 2 15.3582 7.25796 12.6545 11.0434ZM1.71917 12.2062C-1.93044 7.09707 1.72171 0 8.00046 0C14.279 0 17.9312 7.09665 14.282 12.2058L9.24007 19.265C8.63272 20.1153 7.36896 20.1154 6.76156 19.2651L1.71917 12.2062ZM7.99995 9C9.10452 9 9.99995 8.10457 9.99995 7C9.99995 5.89543 9.10452 5 7.99995 5C6.89538 5 5.99995 5.89543 5.99995 7C5.99995 8.10457 6.89538 9 7.99995 9Z"></path></svg><input name="zip" value="11201" aria-label="Zip Code"></label><button aria-label="Search">⌕</button></form></div></section>
<section class="state-directory"><h2>Find Pros in Your State <span>⌃</span></h2><div>{state_links}</div></section>"""
        return layout(request, "Search Real Local Reviews, Home Services Guide", body + search_gate_modal(), active="services")
    with SERVICES.auth.connect() as connection:
        services = db.rows(connection.execute("SELECT * FROM an_services ORDER BY name").fetchall())
        providers = db.rows(connection.execute("SELECT * FROM an_providers").fetchall())
    if query and not service:
        match = next((item for item in services if query in item["name"].lower() or query in item["summary"].lower()), None)
        service = match["slug"] if match else ""
    for item in providers:
        item["services"] = json.loads(item["services_json"])
        item["distance"] = db.distance(zip_code, item["zip"]) if zip_code else 0
    if service:
        providers = [item for item in providers if service in item["services"]]
    if zip_code:
        providers = [item for item in providers if item["distance"] <= item["radius_miles"]]
    if verified:
        providers = [item for item in providers if item["verified"]]
    if rating:
        providers = [item for item in providers if item["rating"] >= rating]
    if price:
        providers = [item for item in providers if item["price_level"] <= price]
    keys = {"rating": lambda x: -x["rating"], "reviews": lambda x: -x["review_count"], "distance": lambda x: x["distance"], "price": lambda x: x["price_level"]}
    providers.sort(key=keys.get(sort, lambda x: (-x["verified"], -x["rating"], x["response_minutes"])))
    total_providers = len(providers)
    page_size = 19
    page_count = max(1, (total_providers + page_size - 1) // page_size)
    page = min(page, page_count)
    page_providers = providers[(page - 1) * page_size : page * page_size]
    options = "".join(f"<option value='{esc(item['slug'])}' {'selected' if item['slug']==service else ''}>{esc(item['name'])}</option>" for item in services)
    cards = "".join(provider_card(item) for item in page_providers)
    empty = "" if total_providers else "<div class='empty'><h2>No pros match those filters</h2><p>Try a nearby ZIP, lower rating threshold or clear filters. Your project details are unchanged.</p><a class='button' href='/search'>Expand search</a></div>"
    base_query = {
        key: value
        for key, value in {
            "q": query,
            "service": service,
            "zip": zip_code,
            "verified": "1" if verified else "",
            "rating": str(rating) if rating else "",
            "price": str(price) if price else "",
            "sort": sort if sort != "recommended" else "",
        }.items()
        if value
    }
    pager = "" if page_count == 1 else "<nav class='pagination' aria-label='Provider pages'>" + "".join(
        f"<a class='{'active' if number == page else ''}' href='/search?{urlencode({**base_query, 'page': number})}'>{number}</a>"
        for number in range(1, page_count + 1)
    ) + "</nav>"
    body = f"""<section class="search-head"><p class="kicker">Compare local help</p><h1>Find a home service pro</h1><form action="/search"><input name="q" value="{esc(query)}" placeholder="Search services"><input name="zip" value="{esc(zip_code)}" placeholder="ZIP code"><button class="button">Search</button></form></section><div class="search-layout"><aside><form class="filter-form" action="/search"><h2>Refine results</h2><label>Service<select name="service"><option value="">All services</option>{options}</select></label><label>ZIP<input name="zip" value="{esc(zip_code)}" inputmode="numeric"></label><label>Minimum rating<select name="rating"><option value="0">Any rating</option><option value="4.5" {'selected' if rating==4.5 else ''}>4.5 and up</option><option value="4.8" {'selected' if rating==4.8 else ''}>4.8 and up</option></select></label><label>Price level<select name="price"><option value="0">Any price</option><option value="1" {'selected' if price==1 else ''}>$</option><option value="2" {'selected' if price==2 else ''}>$$ or less</option></select></label><label class="check"><input type="checkbox" name="verified" value="1" {'checked' if verified else ''}> Screened profiles only</label><button class="button wide">Apply filters</button><a href="/search">Clear all</a></form></aside><section class="results"><div class="result-bar"><p><b>{total_providers}</b> pros found {('near '+esc(zip_code)) if zip_code else ''}</p><form><input type="hidden" name="service" value="{esc(service)}"><input type="hidden" name="zip" value="{esc(zip_code)}"><label>Sort <select name="sort" onchange="this.form.submit()"><option value="recommended">Recommended</option><option value="rating" {'selected' if sort=='rating' else ''}>Highest rated</option><option value="reviews" {'selected' if sort=='reviews' else ''}>Most reviews</option><option value="distance" {'selected' if sort=='distance' else ''}>Distance</option><option value="price" {'selected' if sort=='price' else ''}>Price</option></select></label></form></div>{empty}<div class="pro-list">{cards}</div>{pager}</section></div>"""
    return layout(request, "Find a pro", body + search_gate_modal(), active="services")


@app.get("/find")
def find(request: Request) -> HTMLResponse:
    """Render the source site's public find entry as a local destination."""

    body = """<section class="source-find"><h1>Find top-rated service pros for your project!</h1><form action="/search"><input name="q" placeholder="How can we help?"><span class="find-pin" aria-hidden="true"><svg viewBox="0 0 24 24"><path fill-rule="evenodd" clip-rule="evenodd" d="M12.65 11.04 8 17.56l-4.65-6.52C.64 7.26 3.35 2 8 2s7.36 5.26 4.65 9.04ZM1.72 12.21C-1.93 7.1 1.72 0 8 0s9.93 7.1 6.28 12.21l-5.04 7.06a1.52 1.52 0 0 1-2.48 0L1.72 12.2ZM8 9a2 2 0 1 0 0-4 2 2 0 0 0 0 4Z"/></svg></span><input name="zip" placeholder="Zip code" aria-label="Zip code" inputmode="numeric"><button aria-label="Search"><span></span></button></form><h2>Popular categories</h2><nav><a href="/nearme/remodeling/">Additions &amp; Remodels <span>›</span></a><a href="/nearme/heating-cooling/">Air Conditioning &amp; Cooling <span>›</span></a><a href="/nearme/handyman/">Builders (New Homes), Architects &amp; Designers <span>›</span></a><a href="/nearme/bathroom-remodeling/">Bathroom <span>›</span></a><a href="/nearme/cabinets/">Cabinets &amp; Countertops <span>›</span></a><a href="/nearme/carpentry/">Carpentry <span>›</span></a><a href="/nearme/carpet/">Carpet <span>›</span></a><a href="/nearme/house-cleaning/">Cleaning Services <span>›</span></a><a href="/nearme/concrete/">Concrete, Brick &amp; Stone <span>›</span></a><a href="/nearme/decks/">Decks, Porches, Gazebos &amp; Play Equipment <span>›</span></a></nav></section>"""
    return layout(request, "Find home service professionals", body, active="services")


@app.get("/services/{slug}")
def service_detail(slug: str, request: Request) -> HTMLResponse:
    with SERVICES.auth.connect() as connection:
        service = db.row(connection.execute("SELECT * FROM an_services WHERE slug=?", (slug,)).fetchone())
        providers = db.rows(connection.execute("SELECT * FROM an_providers").fetchall())
    if not service:
        return layout(request, "Service not found", "<section class='empty'><h1>Service not found</h1><a href='/search'>Browse services</a></section>")
    providers = [item for item in providers if slug in json.loads(item["services_json"])][:3]
    pro_noun, hero_image, mobile_hero_image = service_presentation(slug, service["name"])
    body = f"""<nav class="service-jump"><a href="#top-rated-pros">Top Rated Pros</a><a href="#recent-reviews">Recent Reviews</a><a href="#faq">FAQ</a><a class="button" href="#top-rated-pros">Get matched with pros</a></nav><div class="service-mobile-search"><a href="/search">How can we help?</a></div>
<div class="source-crumb"><a href="/services/{esc(slug)}">{esc(service['name'])}</a><span>/</span><b>{esc(service['name'])} Pros</b></div>
<section class="source-service-hero"><picture><source media="(max-width:800px)" srcset="/static/source/{esc(mobile_hero_image)}"><img src="/static/source/{esc(hero_image)}" alt="{esc(service['name'])} professional at work"></picture><div><h1>Get matched with top {esc(pro_noun)} in Los Angeles, CA</h1><p>Enter your zip and get matched with up to 3 pros</p><form action="/search"><input type="hidden" name="service" value="{esc(slug)}"><label><svg aria-hidden="true" viewBox="0 0 24 24"><path fill-rule="evenodd" clip-rule="evenodd" d="M12.6545 11.0434L8.00076 17.5591L3.3466 11.0437C0.642577 7.25828 3.34848 2 8.00046 2C12.6523 2 15.3582 7.25796 12.6545 11.0434ZM1.71917 12.2062C-1.93044 7.09707 1.72171 0 8.00046 0C14.279 0 17.9312 7.09665 14.282 12.2058L9.24007 19.265C8.63272 20.1153 7.36896 20.1154 6.76156 19.2651L1.71917 12.2062ZM7.99995 9C9.10452 9 9.99995 8.10457 9.99995 7C9.99995 5.89543 9.10452 5 7.99995 5C6.89538 5 5.99995 5.89543 5.99995 7C5.99995 8.10457 6.89538 9 7.99995 9Z"></path></svg><input name="zip" value="11201" aria-label="ZIP code"></label><button class="button">Start Matching</button></form></div></section>
<section class="matching"><h2>Matching on Angi</h2><div><p><i><img src="/static/source/matching-message.svg" alt=""></i><span>Share some details about your home project.</span></p><p><i><img src="/static/source/matching-pro.svg" alt=""></i><span>Within moments, match with highly-rated local pros.</span></p><p><i><img src="/static/source/matching-quotes.svg" alt=""></i><span>Compare quotes and choose the best pro for the job.</span></p></div></section>
<section id="top-rated-pros" class="source-provider-list"><h2>{esc(pro_noun).capitalize()} near you</h2><div class="pro-list">{''.join(provider_card(item) for item in providers)}</div></section>
<section id="estimate" class="detail-columns"><div><p class="kicker">Local cost planning</p><h2>Estimate this project</h2><p>Choose a scope and urgency to save a deterministic local range. No provider is contacted.</p></div><form class="panel" data-estimate data-service="{esc(slug)}"><label>Project size<select name="size"><option value="small">Small repair</option><option value="medium">Medium project</option><option value="large">Large project</option></select></label><label>Urgency<select name="urgency"><option value="standard">Standard</option><option value="urgent">Urgent</option></select></label><label>ZIP code<input name="zip" value="11201" inputmode="numeric" required pattern="[0-9]{{5}}"></label><button class="button wide">Save local estimate</button><div data-estimate-result></div></form></section>"""
    return layout(request, service["name"], body, active="services")


@app.get("/pros/{slug}")
def provider_detail(slug: str, request: Request) -> HTMLResponse:
    with SERVICES.auth.connect() as connection:
        provider = db.row(connection.execute("SELECT * FROM an_providers WHERE slug=?", (slug,)).fetchone())
        if not provider:
            return layout(request, "Provider not found", "<section class='empty'><h1>Provider not found</h1><a href='/search'>Find another pro</a></section>")
        portfolio = db.rows(connection.execute("SELECT * FROM an_portfolio WHERE provider_id=?", (provider["provider_id"],)).fetchall())
        reviews = db.rows(connection.execute("SELECT * FROM an_public_reviews WHERE provider_id=? AND public=1 ORDER BY created_at DESC", (provider["provider_id"],)).fetchall())
    services = json.loads(provider["services_json"])
    availability = json.loads(provider["availability_json"])
    gallery = "".join(f"<article class='portfolio' style='--tone:{esc(item['tone'])}'><i>Project photo</i><h3>{esc(item['title'])}</h3><p>{esc(item['caption'])}</p></article>" for item in portfolio)
    review_html = "".join(f"<article class='review'><p class='stars'>{'★'*item['rating']}{'☆'*(5-item['rating'])}</p><p>{esc(item['body'])}</p><small>{esc(item['author'])} · {esc(item['service_type'])}</small></article>" for item in reviews)
    slots = "".join(f"<option value='{esc(slot)}'>{esc(slot.replace('2026-', ''))}</option>" for slot in availability) or "<option value=''>No current availability</option>"
    service_opts = "".join(f"<option value='{esc(s)}'>{esc(s.replace('-', ' ').title())}</option>" for s in services)
    display_name = "Tony's Plumbing, Inc." if slug == "bright-pipe-plumbing" else provider["name"]
    display_reviews = 490 if slug == "bright-pipe-plumbing" else provider["review_count"]
    display_years = 32 if slug == "bright-pipe-plumbing" else provider["years_in_business"]
    display_services = "Sewer Main - Clear, Plumbing for a Remodel or Addition - Install, Faucets, Fixtures and Pipes <br class='mobile-service-break'>Repair or Replace, <u>+24 more</u>" if slug == "bright-pipe-plumbing" else esc(provider["bio"])
    display_about = "Over many years of quality and professional service; Tony's Plumbing, a family owned &amp; operated business, has acquired the ability to quickly and accurately diagnose the work that needs to be done. This makes it possible for us to provide you with a realistic and fair estimate before any service is begun. If we can help you with a project or an estima..." if slug == "bright-pipe-plumbing" else esc(provider["bio"])
    body = f"""<div class="profile-crumb"><a href="/">Angi</a><span>/</span><a href="/search">CA</a><span>/</span><b>Harbor City</b></div>
<section class="source-profile"><div class="profile-summary"><span class="approved">ⓐ Approved (Corporate)</span><h1>{esc(display_name)}</h1><p class="source-rating"><b>★★★★★</b> <strong>{provider['rating']:.1f}</strong> <span>({display_reviews})</span></p><p>{display_services}</p><button class="phone-link" data-start-project data-service="{esc(services[0])}"><svg aria-hidden="true" viewBox="0 0 24 24"><rect width="24" height="24" fill="none"></rect><path d="M6.739 17.528c3.998 3.998 8.184 4.676 10.522 4.676 2.701 0 4.677-2.338 4.677-3.507 0-1.298-3.52-3.706-4.677-3.507-1.099.187-2.338 2.338-2.338 2.338s-2.806-1.637-4.677-3.507c-1.87-1.871-3.507-4.677-3.507-4.677s2.151-1.239 2.338-2.338c.199-1.158-2.209-4.677-3.507-4.677-1.169 0-3.507 1.976-3.507 4.677 0 2.338.678 6.523 4.676 10.522Z"/><path d="M13.657 3.015c3.882.2 6.988 3.314 7.196 7.196M13.04 6.508c2.554.192 4.595 2.234 4.787 4.787"/></svg><u>Phone number</u></button></div><img class="source-profile-logo" src="/static/source/provider-logo.jpg" alt="Local plumbing business logo"><aside><button class="button" data-start-project data-service="{esc(services[0])}">Request quote</button><hr><h2>Contact Information</h2><p>25039 VERMONT AVE, Harbor City, CA 90710<br><u>https:&#47;&#47;www.tonysplumbingpro.com/</u></p></aside></section>
<nav class="source-profile-tabs"><a href="#about">About</a><a href="#portfolio">Photos</a><a href="#reviews">Reviews</a><a href="#availability">More</a></nav>
<section id="about" class="profile-about"><h2>About us</h2><p>{display_about}</p><a href="#portfolio"><u>Read more</u></a><h2>Business highlights</h2><p>⚙&nbsp;&nbsp; {display_years} years of experience</p></section>
<section id="portfolio" class="section"><div class="section-title"><h2>Project portfolio</h2><span>Synthetic examples</span></div><div class="portfolio-grid">{gallery}</div></section>
<section id="reviews" class="section"><div class="section-title"><h2>Homeowner reviews</h2><span>Public local-demo reviews only</span></div><div class="review-grid">{review_html or '<p>No public reviews yet.</p>'}</div></section>
<section id="availability" class="detail-columns"><div><p class="kicker">Availability</p><h2>Choose a preferred time</h2><p>Selection is carried into a local request and can be changed later.</p></div><form class="panel" data-quick-start data-service="{esc(services[0])}"><label>Service<select name="service">{service_opts}</select></label><label>Preferred appointment<select name="appointment">{slots}</select></label><button class="button wide">Start request with this time</button><p class="fine">Nothing is sent to {esc(provider['name'])}; this is a synthetic workflow.</p></form></section>"""
    return layout(request, provider["name"], body, active="services")


@app.get("/nearme/")
def all_nearby_services(request: Request) -> HTMLResponse:
    return find(request)


@app.get("/nearme/{slug}/")
def nearby_directory(slug: str, request: Request) -> HTMLResponse:
    service_aliases = {
        "hvac": "heating-cooling",
        "interior-painting": "interior-painting",
        "house-cleaning": "house-cleaning",
        "handyman-service": "handyman",
    }
    service_slug = service_aliases.get(slug, slug)
    try:
        page = max(1, int(request.query_params.get("page", "1")))
    except ValueError:
        page = 1
    with SERVICES.auth.connect() as connection:
        service = db.row(
            connection.execute(
                "SELECT * FROM an_services WHERE slug=?", (service_slug,)
            ).fetchone()
        )
        providers = db.rows(
            connection.execute(
                "SELECT * FROM an_providers ORDER BY verified DESC,rating DESC,review_count DESC"
            ).fetchall()
        )
    if service:
        providers = [
            item
            for item in providers
            if service_slug in json.loads(item["services_json"])
        ]
    page_size = 19
    page_count = max(1, (len(providers) + page_size - 1) // page_size)
    page = min(page, page_count)
    items = providers[(page - 1) * page_size : page * page_size]
    label = service["name"] if service else slug.replace("-", " ").title()
    pro_noun, hero_image, mobile_hero_image = service_presentation(slug, label)
    pager = "".join(
        f"<a class='{'active' if number == page else ''}' href='/nearme/{esc(slug)}/?page={number}'>{number}</a>"
        for number in range(1, page_count + 1)
    )
    body = f"""<div class="service-mobile-search"><a href="/search">How can we help?</a></div><div class="source-crumb"><a href="/nearme/">Services near me</a><span>/</span><b>{esc(label)} Pros</b></div><section class="source-service-hero"><picture><source media="(max-width:800px)" srcset="/static/source/{esc(mobile_hero_image)}"><img src="/static/source/{esc(hero_image)}" alt="{esc(label)} professional at work"></picture><div><h1>Get matched with top {esc(pro_noun)} in Los Angeles, CA</h1><p>Enter your zip and get matched with up to 3 pros</p><form action="/search"><input type="hidden" name="service" value="{esc(service_slug)}"><label><span aria-hidden="true">⌖</span><input name="zip" value="90013" aria-label="ZIP code"></label><button class="button">Start Matching</button></form></div></section><section class="matching"><h2>Matching on Angi</h2><div><p><i><img src="/static/source/matching-message.svg" alt=""></i><span>Share some details about your home project.</span></p><p><i><img src="/static/source/matching-pro.svg" alt=""></i><span>Within moments, match with highly-rated local pros.</span></p><p><i><img src="/static/source/matching-quotes.svg" alt=""></i><span>Compare quotes and choose the best pro for the job.</span></p></div></section><section class="section source-provider-list"><h2>{esc(pro_noun).capitalize()} near you</h2><div class="pro-list">{''.join(provider_card(item) for item in items)}</div><nav class="pagination" aria-label="Provider pages">{pager}</nav></section>"""
    return layout(request, f"{label} near me", body, active="services")


@app.get("/companylist/")
def company_list(request: Request) -> HTMLResponse:
    states = [
        ("al", "Alabama"), ("ak", "Alaska"), ("az", "Arizona"),
        ("ar", "Arkansas"), ("ca", "California"), ("co", "Colorado"),
        ("ct", "Connecticut"), ("de", "Delaware"), ("dc", "Washington DC"),
        ("fl", "Florida"), ("ga", "Georgia"), ("hi", "Hawaii"),
        ("id", "Idaho"), ("il", "Illinois"), ("in", "Indiana"),
        ("ia", "Iowa"), ("ks", "Kansas"), ("ky", "Kentucky"),
        ("la", "Louisiana"), ("me", "Maine"), ("md", "Maryland"),
        ("ma", "Massachusetts"), ("mi", "Michigan"), ("mn", "Minnesota"),
        ("ms", "Mississippi"), ("mo", "Missouri"), ("mt", "Montana"),
        ("ne", "Nebraska"), ("nv", "Nevada"), ("nh", "New Hampshire"),
        ("nj", "New Jersey"), ("nm", "New Mexico"), ("ny", "New York"),
        ("nc", "North Carolina"), ("nd", "North Dakota"), ("oh", "Ohio"),
        ("ok", "Oklahoma"), ("or", "Oregon"), ("pa", "Pennsylvania"),
        ("ri", "Rhode Island"), ("sc", "South Carolina"), ("sd", "South Dakota"),
        ("tn", "Tennessee"), ("tx", "Texas"), ("ut", "Utah"),
        ("vt", "Vermont"), ("va", "Virginia"), ("wa", "Washington"),
        ("wv", "West Virginia"), ("wi", "Wisconsin"), ("wy", "Wyoming"),
    ]
    links = "".join(
        f"<a href='/companylist/us/{code}/'>{name} Pros</a>" for code, name in states
    )
    return layout(
        request,
        "Search Real Local Reviews, Home Services Guide",
        f"<section class='directory-hero'><img src='/static/source/companylist-hero.jpg' alt='Local home service pro at work'><div class='directory-overlay'><h1>Find top-rated pros in your area.</h1><form action='/search'><label><input name='q' placeholder='What can we help you with?'></label><label class='directory-zip'><span>⌖</span><input name='zip' value='90013' aria-label='Zip code'></label><button aria-label='Search'>⌕</button></form></div></section><section class='state-directory'><h2>Find Pros in Your State <span>⌃</span></h2><div>{links}</div></section>",
        active="services",
    )


@app.get("/companylist/us/{state}/")
def state_company_list(state: str, request: Request) -> HTMLResponse:
    state_names = {"ca": "California", "ny": "New York"}
    state_name = state_names.get(state.lower(), state.upper())
    california_cities = [
        "Acton", "Adelanto", "Agoura Hills", "Agua Dulce", "Aguanga", "Ahwahnee", "Alameda", "Albany", "Alhambra", "Aliso Viejo", "Alpine", "Alta", "Altadena", "Alturas", "Amador City", "American Canyon", "Anaheim",
        "Goleta", "Gonzales", "Goshen", "Graeagle", "Granada Hills", "Grand Terrace", "Granite Bay", "Grass Valley", "Greenbrae", "Greenfield", "Greenville", "Gridley", "Groveland", "Guadalupe", "Gualala", "Guerneville", "Gustine",
        "Penryn", "Perris", "Petaluma", "Phelan", "Phillipsville", "Pico Rivera", "Piedmont", "Pilot Hill", "Pine Grove", "Pine Mountain Club", "Pinole", "Pioneer", "Pismo Beach", "Pittsburg", "Placentia", "Placerville", "Planada",
    ]
    city_links = "".join(f"<a href='/companylist/us/{esc(state)}/{esc(city.lower().replace(' ', '-'))}/'>{esc(city)} Pros</a>" for city in california_cities)
    return layout(
        request,
        f"Home service pros in {state.upper()}",
        f"<section class='directory-hero'><img src='/static/source/companylist-hero.jpg' alt='Local home service pro at work'><div class='directory-overlay'><h1>Find top-rated pros in your area.</h1><form action='/search'><label><input name='q' placeholder='What can we help you with?'></label><label class='directory-zip'><span>⌖</span><input name='zip' value='90013' aria-label='Zip code'></label><button aria-label='Search'>⌕</button></form></div></section><section class='state-directory city-directory'><h2>Find Pros in these {esc(state_name)} cities <span>⌃</span></h2><div>{city_links}</div></section>",
        active="services",
    )


@app.get("/companylist/us/{state}/{city}/")
def city_company_list(state: str, city: str) -> RedirectResponse:
    location = city.replace("-", " ").title()
    query = urlencode({"service": "plumbing", "location": location, "state": state.upper()})
    return RedirectResponse(
        f"/search?{query}",
        status_code=303,
    )


@app.get("/companylist/us/{state}/{city}/{slug}.htm")
def source_company_detail(
    state: str, city: str, slug: str, request: Request
) -> HTMLResponse:
    if slug.endswith("companies"):
        service = "plumbing" if "plumbing" in slug else "handyman"
        return nearby_directory(service, request)
    if "221484" in slug or slug.lower().startswith("tony"):
        return provider_detail("bright-pipe-plumbing", request)
    with SERVICES.auth.connect() as connection:
        providers = db.rows(
            connection.execute("SELECT slug FROM an_providers ORDER BY slug").fetchall()
        )
    exact = next((item for item in providers if item["slug"] == slug), None)
    if exact is None:
        index = sum(slug.encode("utf-8")) % len(providers)
        exact = providers[index]
    return provider_detail(str(exact["slug"]), request)


@app.get("/articles")
def article_collection(request: Request) -> HTMLResponse:
    try:
        page = max(1, min(2, int(request.query_params.get("page", "1"))))
    except ValueError:
        page = 1
    page_size = 12
    items = ARTICLE_TOPICS[(page - 1) * page_size : page * page_size]
    cards = "".join(
        f"<article class='article-card'><p class='kicker'>Home project guide</p><h2><a href='/articles/{esc(slug)}.htm'>{esc(slug.replace('-', ' ').title())}</a></h2><p>Synthetic editorial guidance for planning a local WebsiteBench home project.</p><a href='/articles/{esc(slug)}.htm'>Read guide →</a></article>"
        for slug in items
    )
    cost_variant = request.url.path.rstrip("/") == "/articles/cost"
    hub_class = "solution-center-hero cost-center-hero" if cost_variant else "solution-center-hero"
    hub_crumb = "Angi&nbsp; / &nbsp;Solution Center" if cost_variant else "Angi"
    hub_title = "Project Cost Center" if cost_variant else "Angi Solution Center"
    hub_image = "articles-cost-hero.jpg" if cost_variant else "articles-current-hero.jpg"
    hub_alt = "Bathroom Remodel" if cost_variant else "Family enjoying their home"
    hub_credit = "Photo: Joe Hendrickson / iStock" if cost_variant else "Photo: PeopleImages / iStock / Getty Images Plus / Getty Images"
    explore_items = [
        (("article-cozy-family" if cost_variant else "article-snow-house"), "closet-remodel-cost", ("Family sitting cozy at home looking out the window" if cost_variant else "A house during winter all covered in snow")),
        ("article-baseboard-heat", "plumbing-cost-guide", "Warm feet near a baseboard heater"),
        ("article-family-kitchen", "kitchen-remodel-cost", "Family spending time in a kitchen"),
        ("article-washing-dishes", "dishwasher-installation-cost", "Father and daughter washing dishes"),
        ("article-snow-suburban", "winter-home-maintenance", "Snow-covered suburban house"),
        ("article-paying-bills", "home-project-budget", "Couple planning a home project budget"),
    ]
    explore_cards = "".join(
        f"<a href='/articles/{slug}.htm'><picture><source media='(max-width:800px)' srcset='/static/source/{image}-small.jpg'><img src='/static/source/{image}.jpg' alt='{esc(alt)}'></picture></a>"
        for image, slug, alt in explore_items
    )
    return layout(request, "Home Project Guides and Advice", f"<section class='{hub_class}'><div><small>{hub_crumb}</small><h1>{hub_title}</h1></div><figure><img src='/static/source/{hub_image}' alt='{hub_alt}'><figcaption>{hub_credit}</figcaption></figure></section><section class='solution-trust'><b>TRUSTED BY HOMEOWNERS</b><span>★ <strong>4.6</strong><br><small>Average homeowner rating for Angi pros</small></span><span>● <strong>150m+</strong><br><small>Homeowners helped since 1995</small></span></section><section class='solution-explore'><h2>Explore top articles</h2><p>From average costs to expert advice, get all the answers you need to get your job done.</p><div>{explore_cards}</div></section><section class='section article-results'><div class='article-grid'>{cards}</div><nav class='pagination' aria-label='Article pages'><a class='{'active' if page == 1 else ''}' href='/articles?page=1'>1</a><a class='{'active' if page == 2 else ''}' href='/articles?page=2'>2</a></nav></section>")


@app.get("/articles/cost")
def cost_articles(request: Request) -> HTMLResponse:
    return article_collection(request)


@app.get("/articles/author/{slug}")
def article_author(slug: str, request: Request) -> HTMLResponse:
    if slug == "angi":
        body = """<nav class="author-crumb"><a href="/">Angi</a><span>/</span><a href="/articles">Solution Center</a><span>/</span><b>Authors</b></nav><section class="source-author"><div><h1>Angi</h1><p class="author-role">Home Solutions Center</p><p>This article was created with the help of AI technology and edited by our editorial team for clarity and accuracy in accordance with Angi’s AI policy. We use AI tools to help deliver useful, easy-to-understand articles for Angi readers like you. Although AI technology supports our content creation, professional editors always review and fact-check it.</p><a class="author-web" href="#author-articles" aria-label="Author articles"><img src="/static/source/author-personalweb.png" alt=""></a></div><img class="author-logo" src="/static/source/author-angi.png" alt="Angi"></section><section id="author-articles" class="section"><h2>Articles by Angi</h2><a href="/articles/closet-remodel-cost.htm">Closet remodel cost guide</a></section>"""
        return layout(request, "Articles by Angi", body)
    return layout(
        request,
        f"Articles by {slug.replace('-', ' ').title()}",
        f"<section class='prose'><p class='kicker'>Solution Center author</p><h1>{esc(slug.replace('-', ' ').title())}</h1><p>Browse locally reproduced article-family fixtures without loading a remote CMS.</p><a class='button' href='/articles'>View all guides</a></section>",
    )


@app.get("/articles/{slug}.htm")
def article_detail(slug: str, request: Request) -> HTMLResponse:
    title = slug.replace("-", " ").title()
    if slug == "closet-remodel-cost":
        title = "How Much Does a Closet Remodel Cost? [2026 Data]"
    return layout(
        request,
        title,
        f"<section class='article-source-hero'><p>Solution Center &nbsp;/&nbsp; Remodeling &nbsp;/&nbsp; Utility Space Remodel &nbsp;/&nbsp; Closet Remodel &nbsp;/&nbsp; {esc(title)}</p><div><article><h1>{esc(title)}</h1><p>Closet service costs depend on your project and location. Check with a local pro for your specific job.</p></article><form action='/service-request/category/12046'><h2>Get quotes from closet pros near you</h2><label><svg aria-hidden='true' viewBox='0 0 24 24'><path fill-rule='evenodd' clip-rule='evenodd' d='M12.65 11.04 8 17.56l-4.65-6.52C.64 7.26 3.35 2 8 2s7.36 5.26 4.65 9.04ZM1.72 12.21C-1.93 7.1 1.72 0 8 0s9.93 7.1 6.28 12.21l-5.04 7.06a1.52 1.52 0 0 1-2.48 0L1.72 12.2ZM8 9a2 2 0 1 0 0-4 2 2 0 0 0 0 4Z'/></svg><input name='zip' placeholder='Enter your ZIP' inputmode='numeric'></label><button>Request Project Quotes</button><small>No obligation · 100% free</small></form></div></section><section class='article-byline'><div class='article-author'><img src='/static/source/mitchell-grant.jpg' alt='Mitchell Grant'><p><span>Written by <a href='/articles/author/mitchell-grant'><u>Mitchell Grant</u></a></span><small>Contributing Writer</small></p></div><p class='article-updated'>Updated Jul 9, 2026</p><nav><h2>In this article</h2><a href='#cost'>Size</a><a href='#factors'>Professional Costs</a><a href='#tips'>Additional Pros</a></nav></section><article class='prose article-detail'><h2 id='cost'>Cost Insights:</h2><p>Plan the scope, timing, access needs, and questions you want a local provider to answer.</p></article>",
    )


@app.get("/service-request/task/{task_id}")
@app.get("/service-request/category/{task_id}")
@app.get("/service-request-pro-direct/category/{task_id}")
def service_request(task_id: str, request: Request) -> HTMLResponse:
    return source_not_found(request)


@app.get("/chat")
def local_chat(request: Request) -> HTMLResponse:
    return layout(
        request,
        "Project help",
        "<section class='prose'><p class='kicker'>Local support</p><h1>How can we help with your project?</h1><p>This offline chat surface creates no external conversation. Open a project to keep a synthetic support case in its timeline.</p><a class='button' href='/myprojects'>Open my projects</a></section>",
    )


@app.get("/pro/register")
def provider_registration(request: Request) -> HTMLResponse:
    return source_not_found(request)


def source_not_found(request: Request) -> HTMLResponse:
    body = """<section class="source-404"><header><a href="/" aria-label="Angi home"><img src="/static/source/icons/angi_logo.svg" alt="Angi"></a><nav class="source-404-actions"><a href="/register">Sign Up Now</a><a href="/login">Sign In</a><a href="/register?role=provider">Business Owners</a></nav><button type="button" aria-label="Open menu"><span></span><span></span><span></span></button><nav class="source-404-categories"><a href="/search?service=interior">Interior</a><a href="/search?service=exterior">Exterior</a><a href="/search?service=lawn">Lawn &amp; Garden</a><a href="/search">More</a><a href="/articles">Articles &amp; Advice</a></nav></header><main><h1>Hmm, we can't find the page you're looking<br class="desktop-only"> for.</h1><p>Start a new search or go to the <a href="/">homepage</a> to get back on track.</p><form action="/search"><label><i aria-hidden="true"></i><input name="q" placeholder="What are you looking for?"></label><button>Search</button></form><h2>Popular projects near you</h2><nav><a href="/nearme/house-cleaning/">Cleaning Services</a><a href="/nearme/handyman/">Handyperson Services</a><a href="/nearme/plumbing/">Plumbing Services</a><a href="/nearme/home-additions/">Additions &amp; Remodeling</a><a href="/nearme/lawn-care/">Lawn &amp; Garden Care</a><a href="/nearme/interior-painting/">Painting Services</a><a href="/nearme/local-moving-companies/">Moving Services</a><a href="/nearme/electrician/">Electrical Services</a></nav></main><footer><b>Top cities</b><span aria-hidden="true">⌄</span></footer></section>"""
    response = layout(request, "404 Page Not Found", body)
    response.status_code = 404
    return response


@app.get("/privacy")
@app.get("/privacy-request")
def privacy_not_found(request: Request) -> HTMLResponse:
    return source_not_found(request)


@app.get("/terms")
def legal_page(request: Request) -> HTMLResponse:
    nav = """<a class="active" href="/terms">Angi Terms of Use</a><a href="#membership">Angi Membership Agreement</a><a href="#project-submission">Angi Project Submission Customer Agreement</a><a href="/privacy">Angi Privacy Policy</a><a href="#mobile-alerts">Angi Mobile Alerts Terms and Conditions</a><a href="#book-now">Book Now Terms</a><a href="#eula">Mobile Application EULA</a><a href="#key-membership">Angi Key Membership Terms</a><a href="/happiness-guarantee.htm">Happiness Guarantee</a><a href="#conduct">Angi Code of Conduct</a><a href="#large-providers">Large Service Providers</a><a href="#pro-terms">Angi Pro Terms</a>"""
    body = f"""<section class="legal-center"><header class="legal-brand"><img src="/static/source/icons/angi_logo.svg" alt="Angi"><span>Legal Center</span></header><div class="legal-layout"><aside>{nav}</aside><main><h1>Angi Terms of Use</h1><label>Version<select aria-label="Version"><option>Version 4.2&nbsp; (Current)</option></select></label><div class="legal-effective"><span>Effective August 13th 2026</span><a href="/static/terms.txt" download>Download</a></div><hr><article><h2>Angi Terms of Use</h2><p><i>Last updated on August 13, 2026</i></p><p>Angi Inc. (“Angi”) helps consumers research, hire, rate, and review a variety of service contractors and health related professionals (collectively, “Service Providers”). The following Terms of Use outline your obligations when using the Angi websites, mobile applications, and services.</p><h3>1. ACCEPTANCE OF TERMS</h3><p>The Angi website available at www.angi.com, the Angi mobile application, all related sites and mobile applications, and the various content, features, and services offered on and in connection with these sites and applications, including the Angi magazine (collectively, the “Sites and Services”) are owned and operated by Angi and can only be accessed and used by you under the Terms of Use described below (“Terms of Use”).<span class="legal-caps">PLEASE READ THESE TERMS OF USE CAREFULLY. BY ACCESSING, DOWNLOADING, OR USING ANY OF THE SITES AND SERVICES, YOU AGREE TO BECOME BOUND BY THESE TERMS AND CONDITIONS. IF YOU DO NOT AGREE TO ALL THE TERMS AND CONDITIONS, THEN YOU MAY NOT ACCESS AND USE THE SITES AND SERVICES.</span></p></article></main></div></section>"""
    return layout(request, "Angi Terms of Use", body)


@app.get("/do-not-sell")
def do_not_sell_page(request: Request) -> HTMLResponse:
    body = """<section class="do-not-sell-source"><h1>Do Not Sell or Share My Personal Information</h1><p>We work with vendors that use cookies and other tracking technologies to gather information about your interactions with our website and third-party websites to deliver advertisements relevant to your interest. This collection of your personal information for advertising purposes is defined as a “sale” or “sharing” of data under the California Consumer Protection Act, as amended (“CCPA”), and as a “sale” under the Virginia Consumer Data Protection Act (“VCDPA”). To opt out of the collection for your personal information for advertising purposes pursuant to the CCPA or VCDPA, please modify your settings below under “Cookies Settings”</p><p>For more information, please visit our <a href="/privacy">privacy policy</a>.</p><button type="button" aria-pressed="false" onclick="this.textContent='Cookie Settings Saved';this.setAttribute('aria-pressed','true')">Cookie Settings</button></section><section class="do-not-sell-footer"><div class="app-links"><span>Download the app</span><div><a href="/external/app-store">Download on the App Store</a><a href="/external/google-play">Get it on Google Play</a></div></div><nav><b>Homeowner services</b><a href="/companylist/">Find local businesses</a><a href="/nearme/">Services near me</a></nav><nav><b>For service pros</b><a href="/register?role=provider">Register your business</a><a href="/register?role=provider">Business center</a></nav><nav><b>Resources</b><a href="/articles">Solution center</a><a href="/articles/cost">Project cost center</a><a href="/faq">FAQs</a></nav><nav><b>About us</b><a href="/how-it-works.htm">How it works</a><a href="/aboutus.htm">Who we are</a><a href="/careers">Careers</a><a href="/in-the-press.htm">Press</a></nav></section>"""
    return layout(request, "Do Not Sell or Share My Personal Information", body)


@app.get("/external/{target}")
def external_notice(target: str, request: Request) -> HTMLResponse:
    return layout(request, "External destination", f"<section class='prose'><h1>External destination</h1><p>{esc(target.replace('-', ' ').title())} is documented in the external-link inventory. This offline clone does not contact third-party services.</p><a class='button' href='/'>Return home</a></section>")


@app.get("/how-it-works.htm")
@app.get("/landing/how-it-works")
@app.get("/aboutus.htm")
@app.get("/landing/aboutus")
@app.get("/careers")
@app.get("/landing/careers")
@app.get("/in-the-press.htm")
@app.get("/landing/press")
@app.get("/contact-us")
@app.get("/landing/contact-us")
@app.get("/happiness-guarantee.htm")
@app.get("/landing/happiness-guarantee")
@app.get("/landing/affiliatepartners")
def corporate_page(request: Request) -> HTMLResponse:
    title = request.url.path.strip("/").split("/")[-1].replace(".htm", "").replace("-", " ").title()
    slug = request.url.path.rstrip("/").split("/")[-1].replace(".htm", "")
    if slug == "careers":
        body = """<section class="careers-source-page"><section class="careers-source-hero"><img src="/static/source/careers-houses.jpg" alt="Colorful houses"><div><h1>Welcome home.</h1><p>We’re on a mission to help everyone love where they live. And we’re looking for ambitious people who want to make it happen. <strong>Join our team.</strong></p><a class="button" href="#open-roles">Join our team</a></div></section><section class="careers-benefits" id="open-roles"><h2>Good work starts with happy employees.</h2><p>So our benefits help support a well-balanced<br>life for you and your family.</p><div class="careers-benefit-grid"><article><i aria-hidden="true">♥</i><h3>Medical, dental, and vision</h3><p>for you and your family. From flexible plans to local support, our synthetic careers page keeps every control reachable.</p></article></div></section></section>"""
        return layout(request, "Careers", body)
    if slug == "affiliatepartners":
        body = """<section class="affiliate-source-page"><section class="affiliate-source-hero"><img src="/static/source/affiliate-hero.jpg" alt="Angie with Pros"><div><h1>Grow your business as an Angi Affiliate partner</h1><p>Angi Affiliate partners drive high quality traffic and leads from homeowners interested in home services.</p></div></section><section class="affiliate-ways"><h2>Ways to work with us</h2><p>To learn more, email <a href="mailto:affiliate@angi.com">affiliate@angi.com</a></p><div><article><i aria-hidden="true">☎</i><h3>Connect homeowners</h3></article><article><i aria-hidden="true">↗</i><h3>Share Angi</h3></article><article><i aria-hidden="true">⌘</i><h3>Build partnerships</h3></article></div></section></section>"""
        return layout(request, "Affiliate Partners", body)
    if slug in {"press", "in-the-press"}:
        body = """<section class="press-source-page"><div class="press-source-hero"><nav aria-label="Breadcrumb"><a href="/">Angi</a><span>/</span><a href="/articles">Solution Center</a></nav><div class="press-source-copy"><h1>Angi News and Media</h1><p>The home for everything home</p></div><figure><img src="/static/source/press-hero.jpg" alt="Man drilling"><figcaption>Photo: Image Source / Angi</figcaption></figure></div><section class="press-source-intro"><p><strong>Check out the Angi media room for company press releases, industry analysis, information about the company, spokespeople, media assets and more.</strong><br><br><strong>Have questions? Email us at <a href="mailto:mediarelations@angi.com">mediarelations@angi.com</a></strong></p></section><section class="press-source-sections"><h2>About Angi</h2><h2>Press Releases</h2><h2>Blog Posts</h2><h2>Research</h2><h2>Images &amp; B-Roll</h2></section></section>"""
        return layout(request, "Angi News and Media", body)
    hero = {
        "aboutus": ("about-hero.jpg", "Home is the most important place on earth", "We make it easy for people to love their homes — and for pros to thrive doing the work they love.", "How Angi Works"),
        "contact-us": ("contact-hero.jpg", "Need Help?", "We’ll point you to the right place.", "Contact support"),
        "happiness-guarantee": ("guarantee-hero.jpg", "Our Happiness Guarantee", "When you book and pay with Angi, we’ll cover your project up to the full purchase price, plus limited damage protection. If you’re not satisfied with your home project or service, we’ll work to make it right.", "Start a Project"),
        "how-it-works": ("guarantee-hero.jpg", "Home care, simplified", "Find trusted pros and fair pricing for any home project — and get the job done right, guaranteed.", "Start a project"),
    }.get(slug)
    if hero:
        image, heading, copy, action = hero
        hero_class = {
            "aboutus": "corporate-source-hero about-source-hero",
            "contact-us": "corporate-source-hero contact-source-hero",
            "happiness-guarantee": "corporate-source-hero guarantee-source-hero",
            "how-it-works": "corporate-source-hero how-source-hero",
        }.get(slug, "corporate-source-hero")
        continuation = "<section class='about-modules'><img src='/static/source/about-module2.jpg' alt='Homeowner improving a room'><article><h2>We help people love their homes</h2></article></section>" if slug == "aboutus" else ""
        if slug == "happiness-guarantee":
            continuation = "<section class='guarantee-module'><img src='/static/source/about-module2.jpg' alt='Homeowner improving a room'></section>"
        if slug == "how-it-works":
            continuation = """<section class="how-brands"><div><b>Angie’s list</b><i aria-hidden="true"></i><img src="/static/source/icons/angi_logo.svg" alt="Angi"></div><p>Whether you know us as Angie's List or Angi, our dedication is the same: helping people love where they live.</p></section><section class="how-next"></section>"""
        if slug == "contact-us":
            follow = """<section class="contact-help"><h2>If you’re using Angi to improve your home:</h2><div><article><h3>Instantly booked services</h3><p>If you instantly booked a <b>pre-priced service directly through Angi</b> (for instance, Angi Mowing or Angi Cleaning):</p><a class="button" href="/myprojects">Get Help</a></article><article><h3>Services booked via retail partners</h3><p>Open your local project timeline to review the synthetic booking and support options.</p><a class="button" href="/myprojects">Get Help</a></article></div></section>"""
        else:
            follow = "" if slug in {"aboutus", "happiness-guarantee", "how-it-works"} else "<section class='corporate-follow'><h2>If you’re using Angi to improve your home, you’re in the right place.</h2></section>"
        action_html = "" if slug == "contact-us" else f"<a class='button' href='/find'>{action}</a>"
        kicker_html = "<em>How Angi Works</em>" if slug == "how-it-works" else ""
        return layout(request, title, f"<section class='{hero_class}'><img src='/static/source/{image}' alt=''><div>{kicker_html}<h1>{heading}</h1><p>{copy}</p>{action_html}</div></section>{follow}{continuation}")
    return layout(
        request,
        title,
        f"<section class='prose'><p class='kicker'>About this local Angi replica</p><h1>{esc(title)}</h1><p>This source-observed corporate page family is represented locally with reachable navigation and no remote dependency.</p><a class='button' href='/'>Return home</a></section>",
    )


def auth_page(request: Request, mode: str) -> HTMLResponse:
    configs = {
        "register": ("Create your account", "Save providers and manage local projects.", "<label>Full name<input name='name' required></label><label>Email<input name='email' type='email' required></label><label>Password<input name='password' type='password' minlength='10' required></label>", "Create account", "Already a member? <a href='/login'>Log in</a>"),
        "login": ("Welcome back", "Continue your synthetic home project.", "<label>Email<input name='email' type='email' required></label><label>Password<input name='password' type='password' required></label>", "Log in", "<a href='/forgot-password'>Forgot password?</a> · <a href='/register'>Create account</a>"),
        "verify": ("Verify locally", "Read the demo code displayed on this page, then enter it below in the same browser session.", "<div id='local-mail' class='local-mail'>Loading local code…</div><label>Verification code<input name='code' inputmode='numeric' required></label>", "Verify account", "No email is sent outside this site."),
        "forgot": ("Reset your password", "The next page displays a demo reset code for this browser session; no email is delivered.", "<label>Email<input name='email' type='email' required></label>", "Create local reset code", "<a href='/login'>Return to login</a>"),
        "reset": ("Choose a new password", "Enter the demo code displayed on this page in the same browser session.", "<div id='local-mail' class='local-mail'>Loading local code…</div><label>Reset code<input name='code' required></label><label>New password<input name='password' type='password' minlength='10' required></label>", "Update password", "No external delivery is used."),
    }
    heading, intro, fields, button, foot = configs[mode]
    body = f"<section class='auth-shell'><div class='auth-copy'><a class='logo' href='/'><i></i>angi</a><p class='kicker'>Local account</p><h1>{heading}</h1><p>{intro}</p><ul><li>Generated WebsiteBench account store</li><li>Local verification and recovery</li><li>No real email or provider contact</li></ul></div><form class='auth-card' data-auth='{mode}'>{fields}<p class='form-error' role='alert'></p><button class='button wide'>{button}</button><p>{foot}</p></form></section>"
    return layout(request, heading, body)


@app.get("/register")
def register_page(request: Request): return auth_page(request, "register")


@app.get("/login")
def login_page(request: Request): return auth_page(request, "login")


@app.get("/verify")
def verify_page(request: Request): return auth_page(request, "verify")


@app.get("/forgot-password")
def forgot_page(request: Request): return auth_page(request, "forgot")


@app.get("/reset-password")
def reset_page(request: Request): return auth_page(request, "reset")


@app.get("/account")
@app.get("/account/settings")
@app.get("/consumer/my-contact-details")
@app.get("/consumer/profile")
def account(request: Request) -> HTMLResponse:
    c = current(request)
    if not c.account_id:
        return RedirectResponse("/login?next=/account", 303)
    mobile_profile = ""
    if request.url.path in {"/consumer/profile", "/account/settings"}:
        mobile_profile = """<section class="account-mobile-profile"><h1>Account</h1><aside><div class="account-mobile-person"><i aria-hidden="true">♙</i><div><b>Sample Homeowner</b></div></div><h2>Settings</h2><a href="/consumer/my-contact-details"><span aria-hidden="true">♙</span><b>Contact details</b><i aria-hidden="true">›</i></a><a href="/consumer/notification-settings"><span aria-hidden="true">♧</span><b>Notifications</b><i aria-hidden="true">›</i></a><button type="button" data-logout><span aria-hidden="true">⇥</span><b>Log out</b></button></aside></section><nav class="source-projects-bottom-nav account-bottom-nav" aria-label="Account navigation"><a href="/search"><i>+</i><span>Find pros</span></a><a href="/myprojects"><i>▣</i><span>My projects</span></a><a class="active" href="/consumer/profile"><i>♙</i><span>Account</span></a></nav>"""
    body = f"""<section class="source-account-page"><a class="source-account-back" href="/myprojects" aria-label="Back">‹</a><h1>Account</h1>{mobile_profile}<div class="source-account-grid"><aside><div class="source-account-person"><i aria-hidden="true">♙</i><b>Sample Homeowner</b></div><h2>Settings</h2><a class="active" href="/account">♙ <span>Contact details</span></a><a href="/consumer/notification-settings">♧ <span>Notifications</span></a><button type="button" data-logout>⇥ <span>Log out</span></button></aside><section><h2>Contact details</h2><form data-profile data-source-profile>Loading profile…</form></section></div></section><div class="source-account-legal"><nav><a href="/terms">Terms and conditions</a><a href="/privacy">Privacy</a><a href="/privacy-request">Your Privacy Rights</a><a href="/do-not-sell">Do Not Sell</a></nav><span>© Copyright 1995-2026, Angi. All Rights Reserved.</span></div>"""
    return layout(request, "Account", body, active="projects")


@app.get("/consumer/notification-settings")
def notification_settings(request: Request) -> HTMLResponse:
    c = current(request)
    if not c.account_id:
        return RedirectResponse("/login?next=/consumer/notification-settings", 303)
    body = """<section class="source-account-page"><a class="source-account-back" href="/myprojects" aria-label="Back">‹</a><h1>Account</h1><div class="source-account-grid"><aside><div class="source-account-person"><i aria-hidden="true">♙</i><b>Synthetic Homeowner</b></div><h2>Settings</h2><a href="/account">♙ <span>Contact details</span></a><a class="active" href="/consumer/notification-settings">♧ <span>Notifications</span></a><button type="button" data-logout>⇥ <span>Log out</span></button></aside><section><h2>Notifications</h2><form class="notification-card" data-notifications><h3>Angi Newsletter</h3><p>Choose how you receive homeowner tips, seasonal reminders, and local project ideas.</p><label class="notification-row"><span>Email</span><span class="notification-switch"><input type="checkbox" name="newsletter_email"><i aria-hidden="true"></i></span></label><label class="notification-row"><span>SMS</span><span class="notification-switch"><input type="checkbox" name="newsletter_sms"><i aria-hidden="true"></i></span></label><p class="form-error" role="alert"></p></form></section></div></section>"""
    return layout(request, "Notifications", body, active="projects")


@app.get("/myprojects")
@app.get("/consumer/my-projects")
def source_projects(request: Request) -> HTMLResponse:
    c = current(request)
    if not c.account_id:
        return RedirectResponse("/login?next=/myprojects", 303)
    force_empty = request.query_params.get("state") == "empty"
    body = f"""<section class="source-projects-page"><h1>My projects</h1><nav class="source-project-tabs" aria-label="Project status"><button class="active" type="button">In progress</button><button type="button">Past projects</button></nav><div class="source-project-content" data-project-list data-source-project-list data-state="{'empty' if force_empty else 'live'}">Loading projects…</div></section><div class="source-projects-legal"><nav><a href="/terms">Terms and conditions</a><a href="/privacy">Privacy.</a><a href="/privacy-request">Your Privacy Rights</a><a href="/do-not-sell">Do Not Sell</a></nav><span>© Copyright 1995-2026, Angi. All Rights Reserved.</span></div><nav class="source-projects-bottom-nav" aria-label="Account navigation"><a href="/search"><i>+</i><span>Find pros</span></a><a class="active" href="/myprojects"><i>▣</i><span>My projects</span></a><a href="/account"><i>♙</i><span>Account</span></a></nav>"""
    return layout(request, "My projects", body, active="projects")


@app.get("/saved")
def saved(request: Request) -> HTMLResponse:
    c = current(request)
    if not c.account_id:
        return RedirectResponse("/login?next=/saved", 303)
    return layout(request, "Saved providers", "<section class='account-head'><div><p class='kicker'>Your shortlist</p><h1>Saved providers</h1><p>Compare synthetic profiles before starting a request.</p></div><a class='button' href='/search'>Find more pros</a></section><section data-saved class='pro-list'>Loading saved providers…</section>")


@app.get("/inbox")
def inbox(request: Request) -> HTMLResponse:
    c = current(request)
    if not c.account_id:
        return RedirectResponse("/login?next=/inbox", 303)
    if request.query_params.get("state") == "source":
        return RedirectResponse("/myprojects?state=empty", 303)
    with SERVICES.auth.connect() as connection:
        messages = db.rows(connection.execute(
            "SELECT m.body, m.sender, p.title, p.project_id FROM an_messages m JOIN an_projects p ON p.project_id=m.project_id WHERE p.account_id=? ORDER BY m.created_at DESC",
            (c.account_id,),
        ).fetchall())
    cards = "".join(f"<article class='review'><b>{esc(item['title'])}</b><p>{esc(item['body'])}</p><small>{esc(item['sender']).title()}</small><a class='button small' href='/projects/{esc(item['project_id'])}'>Open conversation</a></article>" for item in messages)
    body = f"<section class='account-head'><div><p class='kicker'>Project conversations</p><h1>Inbox</h1><p>Messages remain in this local Angi workspace.</p></div><a class='button' href='/account#projects'>My Projects</a></section><section class='review-grid'>{cards or '<div class=empty><h2>No messages yet</h2><p>Start a project and message a matched pro to populate your inbox.</p></div>'}</section>"
    return layout(request, "Inbox", body, active="projects")


@app.get("/projects/{project_id}")
def project_page(project_id: str, request: Request) -> HTMLResponse:
    c = current(request)
    if not c.account_id:
        return RedirectResponse(f"/login?next=/projects/{project_id}", 303)
    body = f"""<section class="project-head"><a href="/account#projects">← All projects</a><p class="kicker">Local home project</p><h1>Build your request, compare quotes and manage the job</h1><p>Every action is contained in this synthetic WebsiteBench sandbox.</p></section><ol class="project-progress" data-project-progress></ol><section data-project data-project-id="{esc(project_id)}"><div class="loading">Loading project…</div></section>"""
    return layout(request, "Manage home project", body, active="projects")


@app.get("/provider/dashboard")
def provider_dashboard(request: Request) -> HTMLResponse:
    c = current(request)
    if not c.account_id:
        return RedirectResponse("/login?next=/provider/dashboard", 303)
    force_empty = " data-force-empty='1'" if request.query_params.get("state") == "empty" else ""
    body = f"<section class='account-head'><div><p class='kicker'>Provider workspace · synthetic</p><h1>Bright Pipe leads & jobs</h1><p>This account-only demo shows your own projects matched to Bright Pipe. Updates add timeline notes; they do not change booking status or contact a real homeowner.</p></div><a class='button outline' href='/account'>Homeowner view</a></section><section class='panel' data-provider-leads{force_empty}>Loading local leads…</section>"
    return layout(request, "Provider lead management", body, active="projects")


@app.get("/help")
@app.get("/faq")
@app.get("/landing/faq")
def help_page(request: Request) -> HTMLResponse:
    body = """<section class="faq-hero"><div><p><a href="/">Angi</a><span>/</span><b>Solution Center</b></p><h1>Frequently Asked Questions</h1></div><figure><img src="/static/source/faq-hero.jpg" alt="Family enjoying drinks at patio"><figcaption>Photo: Maskot / Getty Images</figcaption></figure></section><section class="faq-body"><h2>Any questions? We’re here to help…</h2><div class="faq-list"><details open><summary>What is Angi?</summary><p>Angi helps homeowners get home projects done well and helps home service professionals grow their business. We started in 1995 with a simple goal to help people find skilled home pros in their area. Now more than 25 years later, we've evolved to help people with everything from finding, booking and hiring a skilled pro, to researching costs, finding inspiration and discovering project possibilities. With an extensive nationwide network of more than 200,000 skilled home pros, Angi has helped more than 150 million people maintain, repair, renovate and improve their homes and has helped hundreds of thousands of small local businesses grow.</p></details><details><summary>How does Angi work?</summary><p>Search local services, compare provider details, and create a project in this local sandbox.</p></details><details><summary>How do I find a pro?</summary><p>Use Find Pros to browse services and top-rated local providers.</p></details><details><summary>How are projects managed?</summary><p>Your local account keeps projects, messages, estimates, and appointments together.</p></details></div></section>"""
    return layout(request, "Help & support", body)


@app.get("/safety")
def safety(request: Request) -> HTMLResponse:
    return layout(request, "Local safety policy", "<section class='prose'><p class='kicker'>WebsiteBench safety</p><h1>This marketplace is local and synthetic</h1><p>Provider identities, licenses, insurance, reviews, quotes, messages and appointments are demo records. Registration and reset codes are displayed on their public pages for the current browser session; no email is delivered. Payments are disabled: even the approval test input is rejected, with no booking approval or real charge. Support cases never leave this site.</p><h2>What we never do</h2><ul><li>Contact or hire a real provider</li><li>Send a quote request or message externally</li><li>Charge a real card or create a real refund</li><li>Publish a review to Angi.com</li></ul><a class='button' href='/'>Return home</a></section>")


@app.get("/{category}")
@app.get("/{category}/{topic}")
def content_hub(category: str, request: Request, topic: str = "") -> HTMLResponse:
    if category not in HUB_PATHS:
        raise HTTPException(status_code=404)
    label = " ".join(part.replace("-", " ") for part in (category, topic) if part).title()
    service = "plumbing" if category == "plumbing" else category
    if category == "plumbing" and not topic:
        body = """<section class="content-source-hero"><p>Plumbing</p><h1>Plumbing</h1><div><p>Plumbing is the system of pipes, fixtures, and fittings that brings water into your home and carries waste out. From dripping faucets and slow drains to water heater issues and full bathroom remodels, these projects range from quick fixes to complex installations. Whether you need guidance on a DIY repair or want to connect with a local pro, Angi has the resources to help.</p><form action="/service-request-pro-direct/category/12058"><label><svg aria-hidden="true" viewBox="0 0 24 24"><path fill-rule="evenodd" clip-rule="evenodd" d="M12.65 11.04 8 17.56l-4.65-6.52C.64 7.26 3.35 2 8 2s7.36 5.26 4.65 9.04ZM1.72 12.21C-1.93 7.1 1.72 0 8 0s9.93 7.1 6.28 12.21l-5.04 7.06a1.52 1.52 0 0 1-2.48 0L1.72 12.2ZM8 9a2 2 0 1 0 0-4 2 2 0 0 0 0 4Z"/></svg><input name="zip" placeholder="ZIP Code" inputmode="numeric"></label><button>Request Project Quote</button></form></div></section><section class="content-related"><h2>Related to Plumbing</h2><nav><a href="/plumbing/fixtures">Fixtures</a><a href="/plumbing/water-treatment">Water Treatment</a><a href="/plumbing/gas-systems">Gas Systems</a><a href="/plumbing/water-supply">Water Supply</a><a href="/plumbing/drainage">Drainage</a><a href="/plumbing/pipes">Pipes</a><a href="/plumbing/sewers">Sewers</a><a href="/plumbing/water-heater">Water Heaters</a></nav></section>"""
        return layout(request, label, body, active="services")
    return layout(
        request,
        label,
        f"<section class='search-head'><p class='kicker'>Home project hub</p><h1>{esc(label)}</h1><p>Browse guides, costs, and local synthetic provider options for this source-observed topic family.</p><div class='actions'><a class='button' href='/nearme/{esc(service)}/'>Find local pros</a><a class='button outline' href='/articles'>Read project guides</a></div></section>",
        active="services",
    )


@app.exception_handler(404)
async def not_found(request: Request, _exc):
    response = layout(request, "Page not found", "<section class='empty'><h1>We couldn't find that page</h1><p>Browse local services or return to your projects.</p><a class='button' href='/'>Go home</a></section>")
    response.status_code = 404
    return response