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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
"""Capterra WebsiteBench clone — persistent backend app.

Routes stay identical to the accepted R2 frontend surface; business logic
(accounts, signed-cookie sessions, review drafts/revisions/submissions,
admin reset) is server-side and backed by SQLite via clone/backend/db.py.
The database path and site identity come only from ``backend/runtime.json``.
Validation is generic source-site behavior: any whole-star rating 1-5 with
non-empty text is accepted; benchmark values are ordinary seed data.
"""

from __future__ import annotations

import functools
import importlib.util
import hashlib
import hmac
import http.client
import ipaddress
import json
import os
import re
import secrets
import sys
import time
import unicodedata
from collections.abc import Mapping
from contextlib import asynccontextmanager
from pathlib import Path
from urllib.parse import parse_qs, quote, urlencode, urlsplit

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

import uvicorn
from fastapi import FastAPI, Request, Response
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, RedirectResponse
from starlette.exceptions import HTTPException as StarletteHTTPException
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates

from websitebench.local_clone_auth import (
    MAIL_LOCAL_ONLY,
    MAIL_OUTCOME_UNKNOWN,
    MAIL_SMTP_PENDING,
    RESET_PUBLIC_MESSAGE,
    AuthConflict,
    AuthError,
    AuthLocked,
    AuthRateLimited,
    AuthRejected,
    AuthValidationError,
    LocalAuthStore,
)
from websitebench.site_backend import load_runtime
from backend.site_backend_integration import open_site_services
from backend.categories import (
    category_index,
    category_label,
)
from websitebench.public_clone_auth import (
    VerificationUnavailable,
    load_public_clone_registration_verification,
)
from websitebench.public_clone_auth.fastapi import (
    consume_registration_ticket,
    registration_script_response,
    send_registration_code,
    verify_registration_code,
)

SCOPE_ROOT = ROOT.parent / "scope"


def _load_scope_routes() -> dict[str, dict[str, object]]:
    """Load the accepted control contract used by the offline UI."""

    payload = json.loads(
        (SCOPE_ROOT / "routes.json").read_text(encoding="utf-8")
    )
    return {str(route["id"]): route for route in payload["routes"]}


SCOPE_ROUTES = _load_scope_routes()


def _load_backend_db():
    module_name = "capterra_clone_backend_db"
    if module_name in sys.modules:
        return sys.modules[module_name]
    spec = importlib.util.spec_from_file_location(
        module_name, ROOT / "backend" / "db.py"
    )
    assert spec is not None and spec.loader is not None
    module = importlib.util.module_from_spec(spec)
    sys.modules[module_name] = module
    spec.loader.exec_module(module)
    return module


backend_db = _load_backend_db()
SITE_BACKEND_RUNTIME = load_runtime(ROOT.parent / "backend" / "runtime.json")

SITE_ID = backend_db.SITE_ID
PUBLIC_REGISTRATION_VERIFICATION = load_public_clone_registration_verification()
VERSION = "capterra-r3-backend-2026-08-02.19"
FIXTURE_ID = "capterra-v2-474-h2"
FROZEN_CLOCK = backend_db.FROZEN_CLOCK
PRODUCT_ID = backend_db.PRODUCT_ID
PRODUCT_NAME = backend_db.PRODUCT_NAME
RECEIPT_ID = backend_db.RECEIPT_CODE
REVIEW_TEXT_MAX_CODEPOINTS = 2000
SESSION_COOKIE = "clawbench_capterra_h2"
AUTH_SESSION_COOKIE = SITE_BACKEND_RUNTIME.cookie_name
CSRF_VALUE = "capterra-h2-public-fixture"
ADMIN_TOKEN_HEADER = "X-WebsiteBench-Admin-Token"
LEGACY_ADMIN_TOKEN_HEADER = "X-Clawbench-Admin-Token"
ASSETS_BASE = "/static/assets/source-current/2026-07-25"
PUBLIC_REPLAY_ROOT = ROOT / "static" / "public-replay" / "pages"
PRIMARY_ACCOUNT_SLUG = backend_db.PRIMARY_ACCOUNT[0]
SECONDARY_ACCOUNT_SLUG = backend_db.SECONDARY_ACCOUNT[0]
KNOWN_ACCOUNT_SLUGS = {
    PRIMARY_ACCOUNT_SLUG,
    SECONDARY_ACCOUNT_SLUG,
}
REVIEW_PAGE_SIZE = 25
REVIEW_PAGE_COUNT = 9
R2_ROUTE_PATHS = {
    "auth-register": "/auth/register",
    "auth-register-verify": "/auth/register/verify",
    "auth-login": "/auth/login",
    "auth-logout": "/auth/logout",
    "auth-password-forgot": "/auth/password/forgot",
    "auth-password-verify": "/auth/password/verify",
    "auth-password-reset": "/auth/password/reset",
    "auth-local-inbox": "/auth/local-inbox",
    "local-comparison": "/compare",
    "software-favorites": f"/favorites/software/{PRODUCT_ID}",
}
R2_ROUTE_UI = {
    "auth-register": {
        "eyebrow": "Local Capterra account",
        "title": "Create a local Capterra account",
        "purpose": "Use this site’s account to write reviews, compare products, and save software here.",
        "field_label": "Email address",
        "placeholder": "name@example.com",
        "action": "Continue",
    },
    "auth-register-verify": {
        "eyebrow": "Email verification",
        "title": "Verify your email address",
        "purpose": "Enter the six-character code from local Capterra messages.",
        "field_label": "Six-character code",
        "placeholder": "ABC123",
        "action": "Verify email",
    },
    "auth-login": {
        "eyebrow": "Local Capterra account",
        "title": "Sign in to your local account",
        "purpose": "Access reviews, comparisons, and saved software on this site.",
        "field_label": "Email address",
        "placeholder": "name@example.com",
        "action": "Sign in",
    },
    "auth-logout": {
        "eyebrow": "Your account",
        "title": "Sign out of Capterra",
        "purpose": "Revoke this browser session when you have finished.",
        "field_label": "Current session",
        "placeholder": "Signed in",
        "action": "Sign out",
    },
    "auth-password-forgot": {
        "eyebrow": "Account recovery",
        "title": "Reset your password",
        "purpose": "If the account exists here, a recovery message will appear in local Capterra messages.",
        "field_label": "Account email",
        "placeholder": "name@example.com",
        "action": "Continue",
    },
    "auth-password-verify": {
        "eyebrow": "Account recovery",
        "title": "Enter your verification code",
        "purpose": "Open local Capterra messages for the six-character code.",
        "field_label": "Six-character code",
        "placeholder": "ABC123",
        "action": "Verify code",
    },
    "auth-password-reset": {
        "eyebrow": "Account recovery",
        "title": "Choose a new password",
        "purpose": "Create a secure password you haven’t used before.",
        "field_label": "New password",
        "placeholder": "Use 12 or more characters",
        "action": "Update password",
    },
    "auth-local-inbox": {
        "eyebrow": "Messages",
        "title": "Your Capterra messages",
        "purpose": "Review messages stored for this browser session. External email is not implied.",
        "field_label": "Search messages",
        "placeholder": "Search your inbox",
        "action": "View messages",
    },
    "local-comparison": {
        "eyebrow": "Buyer workspace",
        "title": "Compare software",
        "purpose": "See product ratings, pricing, and features side by side.",
        "field_label": "Products selected",
        "placeholder": "Notion and one alternative",
        "action": "Update comparison",
    },
    "software-favorites": {
        "eyebrow": "Buyer workspace",
        "title": "Save software to favorites",
        "purpose": "Keep products you’re interested in together for easy comparison.",
        "field_label": "Selected product",
        "placeholder": "Notion",
        "action": "Update favorites",
    },
}
R2_STATE_COPY = {
    "entry": ("Ready for input", "Enter your information to continue."),
    "invalid": (
        "Check the highlighted value",
        "Review the field below and try again.",
    ),
    "duplicate": (
        "An account already exists",
        "Sign in instead or use a different email address.",
    ),
    "pending": (
        "Verification is pending",
        "Enter the code from your most recent local Capterra message.",
    ),
    "rate-limited": (
        "Too many attempts",
        "Wait a moment before trying again.",
    ),
    "challenge": (
        "Enter your verification code",
        "Use the six-character code from local Capterra messages.",
    ),
    "locked": (
        "Verification temporarily locked",
        "Try again later or request a new code.",
    ),
    "stale": (
        "This code has expired",
        "Request a new code to continue.",
    ),
    "verified": (
        "Email verified",
        "Your account is ready.",
    ),
    "authenticated": (
        "You’re signed in",
        "Your account is ready to use.",
    ),
    "active": (
        "You’re signed in",
        "You can continue using your Capterra account.",
    ),
    "revoked": (
        "You’re signed out",
        "Sign in again whenever you’re ready.",
    ),
    "generic-response": (
        "Check local Capterra messages",
        "The same response is shown regardless of whether the account exists.",
    ),
    "complete": (
        "Password updated",
        "You can now sign in with your new password.",
    ),
    "messages": (
        "You have new messages",
        "Your latest account messages appear below.",
    ),
    "empty": (
        "Your inbox is empty",
        "New account messages will appear here.",
    ),
    "local-only": (
        "Message ready",
        "Open the message to continue.",
    ),
    "smtp-pending": (
        "Sending message",
        "Your message is being prepared.",
    ),
    "smtp-sent": (
        "Loopback delivery accepted",
        "This state does not claim that an external email was delivered.",
    ),
    "smtp-failed": (
        "Message not sent",
        "Try again in a moment.",
    ),
    "selection-empty": (
        "Choose software to compare",
        "Select at least two products to begin.",
    ),
    "comparison-ready": (
        "Your comparison is ready",
        "Review the selected products side by side.",
    ),
    "invalid-selection": (
        "That comparison cannot be created",
        "Choose two different products and try again.",
    ),
    "retry-selection": (
        "Try your selection again",
        "The workspace remains available after the validation failure.",
    ),
    "cleared-aftercare": (
        "Comparison cleared",
        "Choose products to start a new comparison.",
    ),
    "absent": (
        "Notion is not in your favorites",
        "Save it to find it quickly later.",
    ),
    "present": (
        "Notion is in your favorites",
        "You can compare or remove it at any time.",
    ),
    "removed": (
        "Notion was removed",
        "It is no longer in your favorites.",
    ),
}

REVIEW_AUTHORS = (
    ("Ankith T.", "Software Developer", "Information Technology and Services"),
    ("Jean O.", "Marketing Assistant", "Marketing and Advertising"),
    ("Maya C.", "Product Manager", "Computer Software"),
    ("Verified Reviewer", "Senior Lead Consultant", "Insurance"),
    ("Pupp R.", "Owner", "Events Services"),
    ("Derrick H.", "Operations Director", "Nonprofit Organization Management"),
    ("Priya S.", "Research Coordinator", "Higher Education"),
    ("Noah W.", "Creative Director", "Design"),
    ("Sofia L.", "People Operations Manager", "Human Resources"),
    ("Ethan B.", "Founder", "Professional Services"),
)
REVIEW_TITLES = (
    "One place for notes, tasks, and team work",
    "Flexible enough for the way our team actually works",
    "Powerful workspace with a real learning curve",
    "A dependable home for projects and documentation",
    "Our shared knowledge base finally stays current",
)
REVIEW_OVERALL = (
    "Notion has become the place our team checks first. Pages, project "
    "updates, meeting notes, and decisions stay connected without forcing "
    "every group into exactly the same workflow.",
    "The product is capable and pleasantly adaptable once the initial "
    "workspace structure is in place. It has reduced duplicate documents "
    "and made handoffs much easier to follow.",
    "We use it every day for planning and reference material. Larger pages "
    "can take a moment to load, but the benefit of keeping related work in "
    "one searchable space outweighs that inconvenience.",
)
REVIEW_PROS = (
    "Linked databases and reusable templates make recurring work easy to "
    "standardize without losing flexibility.",
    "Collaboration, comments, and a clear page history keep distributed "
    "teams aligned.",
    "Notes, tasks, and documentation can live together instead of being "
    "split across several tools.",
)
REVIEW_CONS = (
    "New teammates need guidance because the number of possible layouts can "
    "feel overwhelming at first.",
    "Very large pages and databases occasionally feel slower on mobile.",
    "Permissions require care when a workspace grows across several teams.",
)

# Current anonymous public-template families observed through the 2026-08-02
# Browserbase source freeze. These are presentation records only: every link
# stays within this site and every consequential vendor/email action remains
# behind the existing honest boundary controls.
PUBLIC_PAGE_DATA: dict[str, dict[str, object]] = {
    "categories-index": {
        "title": "Browse Our Software Categories",
        "eyebrow": "Software categories",
        "lede": "Explore business software by category and find products that fit the way your team works.",
        "cards": [
            ("Accounting", "Track finances, billing, expenses, and reporting."),
            ("Project Management", "Plan projects, coordinate work, and meet deadlines."),
            ("Human Resources", "Support recruiting, people operations, and engagement."),
            ("Customer Relationship Management", "Manage sales relationships and customer activity."),
            ("Construction Management", "Coordinate jobs, crews, estimates, and field work."),
            ("Marketing", "Reach customers and measure campaign performance."),
            ("Customer Service", "Resolve requests and support customers across channels."),
            ("IT Management", "Operate devices, services, security, and infrastructure."),
        ],
        "sections": [("Popular Categories", "Browse the categories software buyers visit most often.")],
    },
    "category-directory": {
        "title": "Best Accounting Software",
        "eyebrow": "Accounting software",
        "lede": "Compare accounting tools using ratings, reviews, features, and practical buying guidance.",
        "cards": [
            ("NetSuite", "Cloud financial management for growing organizations."),
            ("Xero", "Accounting, invoicing, bank reconciliation, and reporting."),
            ("Sage Intacct", "Financial management with automation and dimensional reporting."),
            ("Accounting Seed", "Accounting workflows built for connected business operations."),
            ("SBS Financials", "Financial reporting and accounting management."),
            ("Zoho Books", "Online accounting for invoices, expenses, and taxes."),
        ],
        "sections": [
            ("How to choose accounting software", "Start with the workflows you need, then compare ease of use, support, integrations, and total cost."),
            ("Accounting software buyers guide", "Use verified reviews and feature comparisons to build a confident shortlist."),
        ],
        "filters": ["Business size", "Pricing options", "Features", "Deployment", "User rating"],
    },
    "subcategory-directory": {
        "title": "Best Free Accounting Software in 2025",
        "eyebrow": "Free accounting software",
        "lede": "Review free and free-trial accounting options before choosing the right fit for your business.",
        "cards": [
            ("Ramp", "Expense automation with finance controls."),
            ("Wave", "Invoicing and accounting for small businesses."),
            ("Zoho Books", "Bookkeeping, billing, and expense tracking."),
            ("ProfitBooks", "Simple accounting and inventory workflows."),
            ("Odoo", "Modular business tools with accounting capabilities."),
            ("Xero", "Cloud accounting and bank reconciliation."),
            ("FreshBooks", "Invoices, expenses, time tracking, and reports."),
            ("QuickBooks Online", "Connected bookkeeping and business reporting."),
        ],
        "sections": [
            ("10 best free or free trial accounting software", "Compare available plans, core features, and upgrade paths."),
            ("How we picked the software on this list", "Products are organized around relevance, ratings, and the needs of accounting software buyers."),
        ],
        "filters": ["Free plan", "Free trial", "Business size", "Features"],
    },
    "product-alternatives": {
        "title": "Alternatives to Notion",
        "eyebrow": "Notion alternatives",
        "lede": "Compare highly rated alternatives using reviews, features, and pricing information.",
        "cards": [
            ("monday.com AI Work Platform", "Flexible work management with boards and dashboards."),
            ("Wrike", "Project planning and collaborative work management."),
            ("Airtable", "Connected workflows built around flexible data."),
            ("Connecteam", "Operations and communication for deskless teams."),
            ("Trello", "Visual task management with boards and cards."),
            ("Jira", "Issue tracking and project planning for software teams."),
            ("Asana", "Team projects, goals, and workflow coordination."),
            ("Todoist", "Straightforward task and project organization."),
        ],
        "sections": [("Top Notion Alternatives", "Evaluate the products buyers most often compare with Notion.")],
    },
    "product-pricing": {
        "title": "Pricing for Notion",
        "eyebrow": "Notion pricing",
        "lede": "Review available plans and compare how pricing changes with team needs.",
        "cards": [
            ("Free", "$0 · For individuals organizing personal projects."),
            ("Plus", "$12 per user, per month · For small teams and growing workspaces."),
            ("Business", "$24 per user, per month · For companies coordinating multiple teams."),
            ("Enterprise", "Custom pricing · For advanced controls, security, and support."),
        ],
        "sections": [
            ("Notion has 4 pricing plans", "Compare plan limits and choose the level that matches your team."),
            ("Popular alternatives to Notion", "Pricing is only one part of a complete software comparison."),
            ("How should I be thinking about software pricing?", "Consider implementation, support, integrations, and the cost of switching as well as the subscription."),
        ],
    },
    "compare-builder": {
        "title": "Start a comprehensive head to head product comparison",
        "eyebrow": "Compare software",
        "lede": "Select products to compare ratings, features, pricing, and verified reviews side by side.",
        "cards": [
            ("Celoxis", "Project portfolio management · 4.5"),
            ("Smartsheet", "Collaborative work management · 4.5"),
            ("monday.com AI Work Platform", "Flexible work management · 4.6"),
        ],
        "sections": [
            ("Popular Comparisons", "Begin with products buyers frequently evaluate together."),
            ("Compare software easily with Capterra’s comparison tool", "Build a focused list and compare the criteria that matter to your team."),
        ],
        "comparison_builder": True,
    },
    "compare-products": {
        "title": "CustomerHero vs SurveyMonkey Features and Cost Comparison",
        "eyebrow": "Side-by-side comparison",
        "lede": "See ratings, pricing, features, and review signals together.",
        "cards": [
            ("CustomerHero", "Survey and customer feedback software."),
            ("SurveyMonkey", "Online surveys, forms, and feedback analysis."),
        ],
        "sections": [
            ("Summary", "Compare the products at a glance before reviewing individual features."),
            ("User reviews", "Verified reviews add practical context to product claims."),
            ("Features", "Review survey design, distribution, reporting, and collaboration capabilities."),
            ("Pricing", "Confirm plan limits and current vendor pricing before making a final decision."),
        ],
        "comparison_table": True,
    },
    "shortlist": {
        "title": "2026 Capterra Shortlist for Project Management",
        "eyebrow": "Capterra Shortlist",
        "lede": "Get to a better list with verified ratings and reviews.",
        "cards": [
            ("Asana", "Projects, portfolios, goals, and team coordination."),
            ("Jira", "Planning and issue tracking for technical teams."),
            ("Notion", "Connected docs, projects, knowledge, and workflows."),
            ("Trello", "Visual project planning with boards and cards."),
            ("ClickUp", "Tasks, documents, goals, and reporting."),
            ("monday.com AI Work Platform", "Configurable work management for teams."),
        ],
        "sections": [
            ("Our Top 5 Picks 2026 Capterra Shortlist", "Products are positioned using ratings and popularity signals."),
            ("Explore the Full Project Management Shortlist", "Review the broader selection to find the best fit."),
        ],
    },
    "our-story": {
        "title": "The #1 destination to find software",
        "eyebrow": "About Capterra",
        "lede": "We connect software buyers with verified reviews, product information, and practical guidance.",
        "cards": [
            ("Software Researchers", "Evaluate markets, products, and buyer needs."),
            ("Review Moderators", "Support review quality and verification."),
            ("Content Analysts", "Turn research into useful buying guidance."),
            ("Software Advisors", "Help buyers clarify priorities and navigate options."),
        ],
        "sections": [
            ("Get to know the specialists behind your success", "Research, review, content, and advisory teams work together for software buyers."),
            ("We help software providers find their best customers", "Providers can present products while buyers retain access to independent comparison tools."),
            ("Contact us", "Choose the destination that best matches your question."),
        ],
    },
    "resources-index": {
        "title": "Blog & Research",
        "eyebrow": "Guides and insights",
        "lede": "Practical research for choosing, buying, and using business software.",
        "cards": [
            ("Accounting & Finance", "Accounting tools, automation, costs, and financial operations."),
            ("AI", "Artificial intelligence trends, tools, and adoption guidance."),
            ("Construction", "Technology for contractors, builders, and field teams."),
            ("Customer Service & Support", "Service operations, channels, and customer experience."),
            ("Human Resources", "Recruiting, engagement, payroll, and people operations."),
            ("Program & Project Management", "Planning, collaboration, delivery, and portfolio management."),
        ],
        "sections": [
            ("Most Recent", "Read the latest analysis and software buying guidance."),
            ("Explore Articles by Category", "Browse research by the business problem you are working on."),
        ],
    },
    "resource-policy-article": {
        "title": "How Capterra Collects and Verifies Reviews",
        "eyebrow": "Reviews verification",
        "lede": "Learn how reviewer identity, content checks, and quality controls support useful reviews.",
        "sections": [
            ("Our process of collecting user reviews", "Reviews come from software users who share their first-hand experiences."),
            ("Our process of verifying reviews", "Identity and content checks help reviews meet publication guidelines."),
            ("1. The reviewer’s identity is confirmed", "Reviewers provide information that supports identity verification."),
            ("2. The review content is verified", "Moderation checks relevance, originality, and compliance."),
            ("3. Fake reviews are actively combated", "Systems and reviewers look for suspicious patterns and abuse."),
        ],
    },
    "resources-news": {
        "title": "Capterra Newsroom",
        "eyebrow": "Press and company news",
        "lede": "Company background, announcements, media coverage, and press contacts.",
        "sections": [
            ("About Capterra", "Capterra helps organizations find the right software."),
            ("Contact us", "Media inquiries can be directed to the press team."),
            ("Press Releases", "Read recent company announcements."),
            ("In the News", "See selected media coverage and commentary."),
        ],
    },
    "legal-content": {
        "title": "GENERAL USER TERMS",
        "eyebrow": "Legal",
        "lede": "These terms explain the rules that apply when using Capterra services.",
        "sections": [
            ("1. Acceptance of terms", "Using the service is subject to the current terms and applicable policies."),
            ("2. Service information", "Product information and user content are provided to support software research."),
            ("3. User responsibilities", "Users must provide lawful content and use the service responsibly."),
            ("4. Intellectual property", "Site content and trademarks remain subject to their respective rights."),
            ("5. Disclaimers and limitations", "Review the complete terms for applicable limitations and notices."),
        ],
    },
    "resource-category": {
        "title": "Accounting & Finance Most Recent Posts",
        "eyebrow": "Accounting & Finance",
        "lede": "Advice and research for accounting teams and software buyers.",
        "cards": [
            ("6 Accounting Tasks That Can Be Fully Automated", "Where automation can save time in everyday accounting work."),
            ("Choose the Best Accounting Software", "Learn from buyers with first-hand product experience."),
            ("Accounting Software Pricing Report", "Compare costs and understand common pricing models."),
            ("Benefits of Accounting Software", "Consider the gains and tradeoffs of modern accounting tools."),
        ],
    },
    "resource-author": {
        "title": "Articles by David Jani",
        "eyebrow": "Author",
        "lede": "Research and practical guidance for business technology buyers.",
        "cards": [
            ("How to Create a Project Plan", "A practical framework for building a useful project plan."),
            ("Software Implementation Tips", "Habits that support smoother software adoption."),
            ("Project Management Software With Gantt Charts", "Compare planning tools with visual timelines."),
        ],
    },
    "resource-editorial-article": {
        "title": "6 Accounting Tasks That Can Be Fully Automated",
        "eyebrow": "Accounting automation",
        "lede": "Automating simple tasks can reap huge returns in accounting.",
        "sections": [
            ("What is accounting automation?", "Automation uses software to complete repeatable finance work with less manual handling."),
            ("1. Expense management", "Capture expenses, apply policies, and route approvals."),
            ("2. Payroll management", "Coordinate calculations, schedules, and records."),
            ("3. Bank reconciliation", "Match transactions and flag exceptions for review."),
            ("4. Accounts receivable", "Prepare invoices and follow payment status."),
            ("5. Accounts payable", "Process bills, approvals, and payment workflows."),
            ("6. Tax compliance and financial reporting", "Organize data and produce consistent reports."),
        ],
    },
    "resource-research-index": {
        "title": "Capterra’s Proprietary Data & Research Methodologies",
        "eyebrow": "Research methodology",
        "lede": "Understand the sources and methods used to create marketplace research.",
        "cards": [
            ("User-generated reviews", "Verified software-user perspectives."),
            ("Buyer interactions", "Aggregated signals from software research activity."),
            ("Market surveys", "Structured research with business decision-makers."),
            ("Analyst insights", "Interpretation from subject-matter specialists."),
            ("Vendor-sourced research", "Product details provided by software companies."),
        ],
        "sections": [
            ("Capterra data sources", "Research draws on several complementary kinds of evidence."),
            ("Approaches to methodology", "Methods are selected to fit the question and available data."),
            ("Capterra research types", "Editorial, algorithmic, and marketplace research serve different buyer needs."),
        ],
    },
    "resource-research-agenda": {
        "title": "Research Agenda",
        "eyebrow": "Upcoming research",
        "lede": "Explore the business technology topics scheduled for upcoming research.",
        "sections": [
            ("Q4 Research Agenda", "Software buying, finance operations, AI adoption, and customer experience."),
            ("Q1 Research Agenda", "Work management, security, marketing, and people operations."),
            ("Q2 Research Agenda", "Industry technology, analytics, service, and growth priorities."),
        ],
    },
    "not-found": {
        "title": "Page not found",
        "eyebrow": "404",
        "lede": "The page you were looking for doesn’t exist.",
        "sections": [("Keep exploring", "Browse software categories, compare products, or return to the home page.")],
        "not_found": True,
    },
}

templates = Jinja2Templates(directory=str(ROOT / "frontend" / "templates"))
templates.env.globals["public_registration_enabled"] = (
    PUBLIC_REGISTRATION_VERIFICATION is not None
)


def seed_auth_fixtures(auth_store: LocalAuthStore) -> None:
    auth_store.seed_account(
        subject_id=PRIMARY_ACCOUNT_SLUG,
        email=backend_db.PRIMARY_ACCOUNT[2],
        display_name=backend_db.PRIMARY_ACCOUNT[1],
        password="CapterraPass123!",
    )
    auth_store.seed_account(
        subject_id=SECONDARY_ACCOUNT_SLUG,
        email=backend_db.SECONDARY_ACCOUNT[2],
        display_name=backend_db.SECONDARY_ACCOUNT[1],
        password="CapterraPass456!",
    )


def auth_seed_accounts() -> list[dict[str, object]]:
    return [
        {
            "subject_id": PRIMARY_ACCOUNT_SLUG,
            "email": backend_db.PRIMARY_ACCOUNT[2],
            "display_name": backend_db.PRIMARY_ACCOUNT[1],
            "password": "CapterraPass123!",
        },
        {
            "subject_id": SECONDARY_ACCOUNT_SLUG,
            "email": backend_db.SECONDARY_ACCOUNT[2],
            "display_name": backend_db.SECONDARY_ACCOUNT[1],
            "password": "CapterraPass456!",
        },
    ]


def configured_mail_runtime() -> dict[str, object]:
    """Resolve one fail-closed, literal-loopback-only delivery boundary."""

    local_only: dict[str, object] = {
        "mode": MAIL_LOCAL_ONLY,
        "worker_token": None,
        "host": None,
        "port": None,
        "path": None,
    }
    mail_mode = (
        os.environ.get("WEBSITEBENCH_LOCAL_MAIL_MODE", "")
        or os.environ.get("CLAWBENCH_LOCAL_MAIL_MODE", "")
    )
    if mail_mode != MAIL_SMTP_PENDING:
        return local_only
    worker_token = (
        os.environ.get("WEBSITEBENCH_LOCAL_MAIL_WORKER_TOKEN", "")
        or os.environ.get("CLAWBENCH_LOCAL_MAIL_WORKER_TOKEN", "")
    )
    raw_url = (
        os.environ.get("WEBSITEBENCH_LOCAL_MAIL_LOOPBACK_URL", "")
        or os.environ.get("CLAWBENCH_LOCAL_MAIL_LOOPBACK_URL", "")
    )
    if len(worker_token) < 20:
        return local_only
    try:
        parsed = urlsplit(raw_url)
        host = parsed.hostname
        port = parsed.port
        address = ipaddress.ip_address(host or "")
    except (ValueError, TypeError):
        return local_only
    if (
        parsed.scheme != "http"
        or not address.is_loopback
        or parsed.username is not None
        or parsed.password is not None
        or port is None
        or not 1024 <= port <= 65535
        or parsed.path not in {
            "/__websitebench/mail-sink",
            "/__clawbench/mail-sink",
        }
        or parsed.query
        or parsed.fragment
    ):
        return local_only
    return {
        "mode": MAIL_SMTP_PENDING,
        "worker_token": worker_token,
        "host": str(address),
        "port": port,
        "path": parsed.path,
    }


@asynccontextmanager
async def lifespan(app: FastAPI):
    mail_runtime = configured_mail_runtime()
    site_backend, auth_store = open_site_services(
        mail_mode=str(mail_runtime["mode"]),
        mail_worker_token=(
            str(mail_runtime["worker_token"])
            if mail_runtime["worker_token"] is not None
            else None
        ),
        database_path=(
            backend_db.resolve_data_dir(None, ROOT) / backend_db.DB_FILENAME
        ),
    )
    if site_backend.config.site_id != SITE_ID:
        raise RuntimeError("Capterra backend runtime identity is inconsistent")
    if site_backend.session_cookie["name"] != AUTH_SESSION_COOKIE:
        raise RuntimeError("Capterra session cookie differs from runtime")
    database = backend_db.Database(
        site_backend.lifecycle.database_path.parent
    )
    if database.path != site_backend.lifecycle.database_path:
        raise RuntimeError("Capterra database path differs from runtime")
    database.prepare()
    seed_auth_fixtures(auth_store)
    auth_store.reconcile_mail(
        worker_token=(
            str(mail_runtime["worker_token"])
            if mail_runtime["mode"] == MAIL_SMTP_PENDING
            else None
        )
    )
    app.state.site_backend = site_backend
    app.state.db = database
    app.state.auth = auth_store
    app.state.mail_runtime = mail_runtime
    app.state.mail_delivery_ledger = []
    # The public eBook form is an acknowledgement-only boundary.  Keep only a
    # bounded digest set for idempotency; raw addresses are never persisted,
    # logged, or passed to a mail adapter.
    app.state.ebook_request_digests = set()
    try:
        yield
    finally:
        database.close()


app = FastAPI(
    title="Capterra R3 persistent backend",
    docs_url=None,
    redoc_url=None,
    openapi_url=None,
    lifespan=lifespan,
)


@app.get("/static/auth-verification.js", include_in_schema=False)
async def public_registration_verification_script() -> Response:
    return registration_script_response(PUBLIC_REGISTRATION_VERIFICATION)


@app.get("/favicon.ico", include_in_schema=False)
async def public_favicon() -> FileResponse:
    """Serve the frozen local brand icon referenced by source replays."""

    return FileResponse(
        ROOT
        / "static/assets/source-current/2026-07-25/shared/"
        "capterra-www-favicon.png",
        media_type="image/png",
    )


app.mount("/static", StaticFiles(directory=str(ROOT / "static")), name="static")


@app.middleware("http")
async def runtime_headers(request: Request, call_next):
    response = await call_next(request)
    style_policy = "style-src 'self'"
    if response.headers.get("X-WebsiteBench-Replay"):
        # Frozen source DOM contains inline layout declarations.  The builder
        # removes all source scripts and remote URLs before these read-only
        # pages are eligible for this narrowly scoped style exception.
        style_policy += " 'unsafe-inline'"
    response.headers["Content-Security-Policy"] = (
        f"default-src 'self'; img-src 'self' data:; {style_policy}; "
        "script-src 'self'; connect-src 'self'; font-src 'self'; "
        "object-src 'none'; frame-ancestors 'none'; base-uri 'self'"
    )
    response.headers["Referrer-Policy"] = "no-referrer"
    response.headers["X-Content-Type-Options"] = "nosniff"
    response.headers["X-ClawBench-Site"] = SITE_ID
    response.headers["X-ClawBench-Version"] = VERSION
    return response


def get_db(request: Request):
    return request.app.state.db


def get_auth(request: Request) -> LocalAuthStore:
    return request.app.state.auth


# Route families that keep the framework's JSON error shape on 404: admin and
# worker boundaries, JSON APIs, fixtures, legacy /local POST aliases, and
# static assets. Every other unmatched path gets the styled not-found replay.
JSON_404_PREFIXES = (
    "/__admin",
    "/__worker",
    "/api/",
    "/fixture",
    "/local/",
    "/static/",
)


@app.exception_handler(StarletteHTTPException)
async def styled_http_error(
    request: Request, exc: StarletteHTTPException
) -> Response:
    if exc.status_code == 404 and not request.url.path.startswith(
        JSON_404_PREFIXES
    ):
        return render_public_replay("not-found", status_code=404)
    return JSONResponse(
        {"detail": exc.detail if exc.detail else "Not Found"},
        status_code=exc.status_code,
        headers=getattr(exc, "headers", None),
    )


def dispatch_next_mail(app_instance: FastAPI) -> dict[str, object] | None:
    """Run one worker-authorized, no-redirect loopback dispatch.

    Public requests may create, queue, retry, and observe mail.  Only the
    private worker boundary calls this function and can reach the target.
    """

    runtime = app_instance.state.mail_runtime
    if runtime["mode"] != MAIL_SMTP_PENDING:
        return None
    worker_token = str(runtime["worker_token"])
    auth_store: LocalAuthStore = app_instance.state.auth
    claim = auth_store.claim_pending_mail(
        worker_token=worker_token,
    )
    if claim is None:
        return None
    mail_id = int(claim["mail_id"])
    claim_token = str(claim["claim_token"])
    request_id = str(claim["request_id"])
    purpose = str(claim["purpose"])
    target_request_count = 0
    accepted_request_count = 0
    response_status: int | None = None
    receipt_request_id: str | None = None
    receipt_accepted_effect_count: str | None = None
    error: str | None = None
    connection: http.client.HTTPConnection | None = None
    try:
        body = json.dumps(
            {
                "request_id": request_id,
                "purpose": purpose,
                "recipient": str(claim["recipient"]),
                "template": str(claim["template"]),
                "verification_code": str(claim["verification_code"]),
            },
            sort_keys=True,
            separators=(",", ":"),
        ).encode("utf-8")
        connection = http.client.HTTPConnection(
            str(runtime["host"]),
            int(runtime["port"]),
            timeout=2.0,
        )
        auth_store.reserve_mail_target_request(
            mail_id,
            claim_token,
            worker_token=worker_token,
        )
        target_request_count = 1
        connection.request(
            "POST",
            str(runtime["path"]),
            body=body,
            headers={
                "Content-Type": "application/json",
                "Content-Length": str(len(body)),
                "Idempotency-Key": request_id,
            },
        )
        response = connection.getresponse()
        response_status = int(response.status)
        receipt_request_id = response.getheader(
            "X-Clawbench-Mail-Request-Id"
        )
        receipt_accepted_effect_count = response.getheader(
            "X-Clawbench-Mail-Accepted-Effect-Count"
        )
        response.read(4096)
        if response_status != 202:
            error = f"loopback sink refused with HTTP {response_status}"
        elif (
            receipt_request_id != request_id
            or receipt_accepted_effect_count != "1"
        ):
            error = "loopback sink acceptance receipt is invalid"
        else:
            accepted_request_count = 1
    except (OSError, http.client.HTTPException, ValueError):
        error = MAIL_OUTCOME_UNKNOWN
    finally:
        if connection is not None:
            connection.close()
    auth_store.finish_mail_claim(
        mail_id,
        claim_token,
        sent=accepted_request_count == 1,
        target_request_count=target_request_count,
        accepted_request_count=accepted_request_count,
        error=error,
        worker_token=worker_token,
    )
    with auth_store.connect() as connection:
        durable_row = connection.execute(
            "SELECT delivery_state_version,target_request_count,"
            "accepted_effect_count,status FROM local_auth_mail_outbox "
            "WHERE mail_id=? AND session_digest=? AND purpose=?",
            (mail_id, claim["session_digest"], purpose),
        ).fetchone()
    if durable_row is None:
        raise RuntimeError("worker delivery lost its durable outbox row")
    event = {
        "request_id": request_id,
        "mail_id": mail_id,
        "purpose": purpose,
        "delivery_attempts": int(claim["delivery_attempts"]),
        "target": "literal-loopback",
        "target_request_count": target_request_count,
        "accepted_request_count": accepted_request_count,
        "response_status": response_status,
        "receipt_request_id": receipt_request_id,
        "receipt_accepted_effect_count": receipt_accepted_effect_count,
        "delivery_state_version": int(
            durable_row["delivery_state_version"]
        ),
        "durable_target_request_count": int(
            durable_row["target_request_count"]
        ),
        "durable_accepted_effect_count": int(
            durable_row["accepted_effect_count"]
        ),
        "status": str(durable_row["status"]),
        "production_request_count": 0,
        "production_effect_count": 0,
    }
    app_instance.state.mail_delivery_ledger.append(event)
    return event


def auth_csrf(session_token: str) -> str:
    return hmac.new(
        backend_db.session_secret(),
        f"auth-csrf:{session_token}".encode("utf-8"),
        hashlib.sha256,
    ).hexdigest()


def comparison_owner_id(request: Request, session_token: str) -> str:
    """Bind anonymous comparison state to one opaque server session."""

    return get_auth(request).session_owner_digest(session_token)


def ensure_auth_session(
    request: Request,
) -> tuple[str, dict[str, object], bool]:
    existing = request.cookies.get(AUTH_SESSION_COOKIE)
    token, session = get_auth(request).ensure_session(existing)
    return token, session, token != existing


def set_auth_cookie(response: HTMLResponse | RedirectResponse, token: str) -> None:
    cookie = dict(SITE_BACKEND_RUNTIME.cookie_options)
    response.set_cookie(
        AUTH_SESSION_COOKIE,
        token,
        httponly=bool(cookie["httponly"]),
        samesite=str(cookie["samesite"]),
        secure=bool(cookie["secure"]),
        path=str(cookie["path"]),
        max_age=30 * 24 * 60 * 60,
    )


def valid_auth_csrf(values: dict[str, str], token: str) -> bool:
    supplied = values.get("csrf", "")
    return bool(supplied) and secrets.compare_digest(
        supplied, auth_csrf(token)
    )


def admin_boundary_authorized(request: Request) -> bool:
    """Require both injected secret authority and a distinct admin origin."""

    expected_token = backend_db.admin_token()
    expected_host = backend_db.admin_host()
    request_host = request.headers.get("host", "").rsplit(":", 1)[0].casefold()
    supplied_token = (
        request.headers.get(ADMIN_TOKEN_HEADER, "")
        or request.headers.get(LEGACY_ADMIN_TOKEN_HEADER, "")
    )
    return bool(expected_token and expected_host) and secrets.compare_digest(
        supplied_token, expected_token
    ) and secrets.compare_digest(request_host, expected_host)


def fixture_boundary_authorized(request: Request) -> bool:
    del request
    return backend_db.test_fixtures_enabled()


def current_account(request: Request):
    """Resolve only opaque auth in public; legacy sessions are test-only."""

    session = get_auth(request).resolve_session(
        request.cookies.get(AUTH_SESSION_COOKIE)
    )
    if session and session.get("authenticated"):
        auth_account = session.get("account")
        if isinstance(auth_account, dict):
            subject_id = auth_account.get("subject_id")
            if isinstance(subject_id, str):
                account = get_db(request).account_by_slug(subject_id)
                if account is not None:
                    return account
    if backend_db.test_fixtures_enabled():
        return get_db(request).account_for_cookie(
            request.cookies.get(SESSION_COOKIE)
        )
    return None


def review_form_boundary(request: Request) -> tuple[str, str]:
    """Resolve the review submit surface and its anti-forgery token.

    Public review mutations are always bound to the opaque server session.
    The fixed token survives only on the explicitly test-only fixture route.
    """

    token = request.cookies.get(AUTH_SESSION_COOKIE, "")
    session = get_auth(request).resolve_session(token)
    if session and session.get("authenticated"):
        return "/local/reviews/notion", auth_csrf(token)
    if backend_db.test_fixtures_enabled() and get_db(request).account_for_cookie(
        request.cookies.get(SESSION_COOKIE)
    ):
        return "/fixture/reviews/notion", CSRF_VALUE
    return "/local/reviews/notion", ""


def fixture_context(request: Request, **values: object) -> dict[str, object]:
    account = current_account(request)
    opaque_session = request.cookies.get(AUTH_SESSION_COOKIE)
    reviewer_name = account["display_name"] if account else "Alex Green"
    reviewer_initials = "".join(
        part[0].upper() for part in reviewer_name.split() if part
    )[:2]
    context: dict[str, object] = {
        "request": request,
        "site_id": SITE_ID,
        "version": VERSION,
        "fixture_id": FIXTURE_ID,
        "frozen_clock": FROZEN_CLOCK,
        "product_id": PRODUCT_ID,
        "product_name": PRODUCT_NAME,
        "receipt_id": RECEIPT_ID,
        # Size and average of the local review corpus. Every template that
        # quotes a review count uses these, so no page can advertise a review
        # total this edition does not actually hold.
        "local_review_total": LOCAL_REVIEW_TOTAL,
        "local_review_average": LOCAL_REVIEW_AVERAGE,
        "signed_in": account is not None,
        "reviewer_name": reviewer_name,
        "reviewer_initials": reviewer_initials,
        "reviewer_email": (
            account["email"] if account else "alex.green@example.test"
        ),
        "fixture_accounts": [
            {
                "slug": backend_db.PRIMARY_ACCOUNT[0],
                "display_name": backend_db.PRIMARY_ACCOUNT[1],
                "email": backend_db.PRIMARY_ACCOUNT[2],
                "initials": "AG",
                "purpose": "primary review fixture",
            },
            {
                "slug": backend_db.SECONDARY_ACCOUNT[0],
                "display_name": backend_db.SECONDARY_ACCOUNT[1],
                "email": backend_db.SECONDARY_ACCOUNT[2],
                "initials": "JL",
                "purpose": "cross-account boundary probe",
            },
        ],
        "current_path": request.url.path,
        "assets_base": ASSETS_BASE,
        "csrf": CSRF_VALUE,
        "auth_csrf": (
            auth_csrf(opaque_session)
            if opaque_session
            and get_auth(request).resolve_session(opaque_session) is not None
            else None
        ),
    }
    context.update(values)
    return context


def exact_effect_coverage_id(
    route_id: str,
    affordance: dict[str, object],
    assertion: dict[str, object],
) -> str:
    """Return the immutable R1 coverage identity for one denied effect."""

    def coverage_slug(value: object) -> str:
        normalized = re.sub(
            r"[^a-z0-9]+", "-", str(value).lower()
        ).strip("-")
        return normalized or "control"

    return ".".join(
        (
            "exact",
            str(affordance["control_identity"]),
            coverage_slug(assertion["id"]),
            coverage_slug(route_id),
            coverage_slug(affordance["state_ids"][0]),
            coverage_slug(affordance["role_ids"][0]),
            coverage_slug(affordance["variant_ids"][0]),
            coverage_slug(affordance["viewports"][0]),
        )
    )


def scope_effect_affordances(
    route_id: str | None,
    state_ids: tuple[str, ...] | list[str] | None,
    role_ids: tuple[str, ...] | list[str] | None = None,
) -> list[dict[str, object]]:
    """Materialize every applicable source-visible external-action boundary."""

    if not route_id or route_id not in SCOPE_ROUTES:
        return []
    applicable_states = set(state_ids or [])
    applicable_roles = set(role_ids or [])
    rows: list[dict[str, object]] = []
    route = SCOPE_ROUTES[route_id]
    for affordance in route.get("affordances", []):
        assertions = affordance.get("effect_assertions", [])
        if not assertions:
            continue
        row_states = set(affordance.get("state_ids", []))
        if applicable_states and not (row_states & applicable_states):
            continue
        row_roles = set(affordance.get("role_ids", []))
        if applicable_roles and not (row_roles & applicable_roles):
            continue
        rendered_assertions = [
            {
                "id": str(assertion["id"]),
                "observable_effect": str(assertion["observable_effect"]),
                "required_truth": str(assertion["required_truth"]),
                "coverage_id": exact_effect_coverage_id(
                    route_id, affordance, assertion
                ),
            }
            for assertion in assertions
        ]
        rows.append(
            {
                "id": str(affordance["id"]),
                "control_identity": str(affordance["control_identity"]),
                "label": str(affordance["label"]),
                "semantic_destination": str(
                    affordance["semantic_destination"]
                ),
                "viewport": str(affordance["viewports"][0]),
                "state_id": str(affordance["state_ids"][0]),
                "effect_payload": json.dumps(
                    rendered_assertions,
                    ensure_ascii=False,
                    separators=(",", ":"),
                ),
            }
        )
    return rows


REVIEW_TENURES = ("6-12 months", "1-2 years", "2+ years")
REVIEW_COMPANY_SIZES = ("1-10", "11-50", "51-200", "201-500", "501+")
REVIEW_FREQUENCIES = ("daily", "weekly", "monthly")
REVIEW_DATES = (
    ("July 19, 2026", "2026-07-19"),
    ("June 30, 2026", "2026-06-30"),
    ("June 12, 2026", "2026-06-12"),
    ("May 3, 2026", "2026-05-03"),
    ("April 22, 2026", "2026-04-22"),
)

# Query value -> the card field value it selects.
LENGTH_OF_USE_VALUES = {"1-2-years": "1-2 years"}

REVIEW_AVATARS = (
    "notion-reviews/authorship-reviewer-1.jpg",
    "notion-reviews/authorship-reviewer-2.jpg",
    "notion-profile/placeholder-user.jpg",
)


def build_review_corpus() -> list[dict[str, object]]:
    """Build the whole deterministic local review set, independent of paging.

    These reviews are openly local test data, not captured remote reviews. Every
    displayed attribute is generated here, which is exactly why each filter
    control can select on one: company size and frequency of use are generated
    alongside rating and tenure rather than being rendered as controls with
    nothing behind them.
    """

    cards: list[dict[str, object]] = []
    for index in range(REVIEW_PAGE_SIZE * REVIEW_PAGE_COUNT):
        author, role, industry = REVIEW_AUTHORS[index % len(REVIEW_AUTHORS)]
        rating = (5, 4, 5, 3, 4)[index % 5]
        date_label, date_sort = REVIEW_DATES[index % len(REVIEW_DATES)]
        cards.append(
            {
                "author": author,
                "role": role,
                "industry": industry,
                # Mixed radix: 5 ratings x 3 tenures x 5 company sizes x 3
                # frequencies is exactly the 225-review corpus, so each
                # combination occurs and no two attributes are locked together.
                # Deriving two filters from one modulus would make some filter
                # combinations unsatisfiable for reasons that are an artefact of
                # generation rather than anything about the data.
                "tenure": REVIEW_TENURES[(index // 5) % len(REVIEW_TENURES)],
                "company_size": REVIEW_COMPANY_SIZES[
                    (index // 15) % len(REVIEW_COMPANY_SIZES)
                ],
                "frequency": REVIEW_FREQUENCIES[
                    (index // 75) % len(REVIEW_FREQUENCIES)
                ],
                "title": REVIEW_TITLES[index % len(REVIEW_TITLES)],
                "rating": rating,
                "rating_class": f"rating-{rating}",
                "date": date_label,
                "date_sort": date_sort,
                "overall": REVIEW_OVERALL[index % len(REVIEW_OVERALL)],
                "pros": REVIEW_PROS[index % len(REVIEW_PROS)],
                "cons": REVIEW_CONS[index % len(REVIEW_CONS)],
                "avatar": REVIEW_AVATARS[index % len(REVIEW_AVATARS)],
                "local_number": index + 1,
            }
        )
    return cards


REVIEW_CORPUS = build_review_corpus()
LOCAL_REVIEW_TOTAL = len(REVIEW_CORPUS)
LOCAL_REVIEW_AVERAGE = round(
    sum(int(card["rating"]) for card in REVIEW_CORPUS) / LOCAL_REVIEW_TOTAL, 1
)

# Product-neutral review copy for the catalog products. Same honesty rule as
# the corpus above: openly local test data, never captured remote reviews.
GENERIC_REVIEW_TITLES = (
    "Does the job our team needed",
    "Solid choice after comparing several options",
    "Capable product with a few rough edges",
    "Reliable day to day once configured",
    "Good value for the way we work",
)
GENERIC_REVIEW_OVERALL = (
    "{name} has settled into our daily routine. Setup took some planning, "
    "but the core workflows are dependable and the team rarely needs help.",
    "We evaluated a few competitors before choosing {name}. The deciding "
    "factors were the clean interface and how quickly new teammates became "
    "productive.",
    "{name} covers the essentials well. Some advanced options take time to "
    "discover, but the documentation filled the gaps for us.",
)
GENERIC_REVIEW_PROS = (
    "Straightforward onboarding and a layout that keeps everyday actions "
    "easy to find.",
    "Dependable performance, and updates have not disrupted our setup.",
    "Flexible configuration that adapted to our process instead of forcing "
    "a new one.",
)
GENERIC_REVIEW_CONS = (
    "Some settings sit a few menus deep and take time to locate.",
    "Reporting covers the basics but larger exports can feel slow.",
    "The pricing tiers took a careful read to match to our team size.",
)


def _generic_rating_sequence(count: int, rating_tenths: int) -> list[int]:
    """A rating multiset whose mean rounds to the displayed product rating."""

    low = min(5, max(1, rating_tenths // 10))
    extra = 0
    if low < 5:
        extra = round(count * (rating_tenths - low * 10) / 10)
        extra = min(max(extra, 0), count)
    ratings = [low + 1] * extra + [low] * (count - extra)
    # Mean-preserving spread: swap a (low, low+1) pair for (low-1, low+2)
    # occasionally so the histogram is not just two adjacent bars.
    for start in range(0, count - 40, 40):
        end = count - 1 - start
        if (
            low >= 2
            and low + 2 <= 5
            and ratings[start] == low + 1
            and ratings[end] == low
        ):
            ratings[start], ratings[end] = low + 2, low - 1
    # Interleave from both ends so pages mix ratings instead of clustering.
    ordered: list[int] = []
    front, back = 0, count - 1
    while front <= back:
        ordered.append(ratings[front])
        if front != back:
            ordered.append(ratings[back])
        front += 1
        back -= 1
    return ordered


@functools.lru_cache(maxsize=256)
def review_corpus_for(
    product_id: str,
    product_name: str,
    rating_tenths: int,
    count: int,
) -> list[dict[str, object]]:
    """The deterministic local review corpus for one catalog product.

    Notion keeps the original 225-review corpus byte for byte; every other
    product gets a corpus seeded on its id, sized to the local review count
    the catalog advertises for it, with a mean matching its displayed rating.
    """

    if product_id == backend_db.PRODUCT_ID:
        return REVIEW_CORPUS
    base = int(
        hashlib.sha256(
            f"capterra-review-corpus:{product_id}".encode("utf-8")
        ).hexdigest()[:8],
        16,
    )
    ratings = _generic_rating_sequence(count, rating_tenths)
    cards: list[dict[str, object]] = []
    for index in range(count):
        author, role, industry = REVIEW_AUTHORS[(index + base) % len(REVIEW_AUTHORS)]
        rating = ratings[index]
        date_label, date_sort = REVIEW_DATES[(index + base) % len(REVIEW_DATES)]
        cards.append(
            {
                "author": author,
                "role": role,
                "industry": industry,
                # Small co-prime radices so every tenure/size/frequency value
                # (and therefore every filter control) is satisfiable even for
                # the smallest 25-review corpora.
                "tenure": REVIEW_TENURES[index % len(REVIEW_TENURES)],
                "company_size": REVIEW_COMPANY_SIZES[
                    (index // 3) % len(REVIEW_COMPANY_SIZES)
                ],
                "frequency": REVIEW_FREQUENCIES[
                    (index // 5) % len(REVIEW_FREQUENCIES)
                ],
                "title": GENERIC_REVIEW_TITLES[
                    (index + base) % len(GENERIC_REVIEW_TITLES)
                ],
                "rating": rating,
                "rating_class": f"rating-{rating}",
                "date": date_label,
                "date_sort": date_sort,
                "overall": GENERIC_REVIEW_OVERALL[
                    (index + base) % len(GENERIC_REVIEW_OVERALL)
                ].format(name=product_name),
                "pros": GENERIC_REVIEW_PROS[
                    (index + base) % len(GENERIC_REVIEW_PROS)
                ],
                "cons": GENERIC_REVIEW_CONS[
                    (index + base) % len(GENERIC_REVIEW_CONS)
                ],
                "avatar": REVIEW_AVATARS[(index + base) % len(REVIEW_AVATARS)],
                "local_number": index + 1,
            }
        )
    return cards


def product_review_corpus(product: Mapping[str, object]) -> list[dict[str, object]]:
    return review_corpus_for(
        str(product["id"]),
        str(product["name"]),
        int(round(float(product["rating"] or 4.2) * 10)),
        int(product["local_review_count"] or 25),
    )


def profile_sub_ratings(product: Mapping[str, object]) -> dict[str, float]:
    """Captured sub-ratings when the card carried them, else seeded near the
    overall rating (and labelled derived by the catalog's derived_fields)."""

    captured = product.get("sub_ratings") or {}
    rating = float(product.get("rating") or 4.2)
    base = int(
        hashlib.sha256(
            f"capterra-sub-ratings:{product['id']}".encode("utf-8")
        ).hexdigest()[:8],
        16,
    )

    def near(shift: int) -> float:
        return max(1.0, min(5.0, round(rating + ((base >> shift) % 5 - 2) / 10, 1)))

    return {
        "overall": captured.get("overall", round(rating, 1)),
        "ease_of_use": captured.get("ease_of_use", near(0)),
        "customer_service": captured.get("customer_service", near(3)),
        "features": captured.get("features", near(6)),
        "value_for_money": captured.get("value_for_money", near(9)),
    }


def select_reviews(
    filter_values: Mapping[str, str] | None = None,
    corpus: list[dict[str, object]] | None = None,
) -> list[dict[str, object]]:
    """Apply the review filter controls to the local corpus."""

    rows = list(REVIEW_CORPUS if corpus is None else corpus)
    if not filter_values:
        return rows

    rating = filter_values.get("rating", "all")
    if rating != "all":
        rows = [row for row in rows if str(row["rating"]) == rating]

    company_size = filter_values.get("company_size", "all")
    if company_size != "all":
        rows = [row for row in rows if row["company_size"] == company_size]

    role = filter_values.get("role", "all")
    if role != "all":
        # The control offers "Manager"; reviewer roles are job titles, so match
        # any title carrying that word (Product Manager, People Ops Manager...).
        rows = [row for row in rows if role in str(row["role"]).casefold()]

    length_of_use = filter_values.get("length_of_use", "all")
    if length_of_use != "all":
        wanted = LENGTH_OF_USE_VALUES.get(length_of_use)
        rows = [row for row in rows if row["tenure"] == wanted]

    frequency = filter_values.get("frequency", "all")
    if frequency != "all":
        rows = [row for row in rows if row["frequency"] == frequency]

    if filter_values.get("sort") == "newest":
        rows.sort(key=lambda row: str(row["date_sort"]), reverse=True)

    return rows


def review_cards(
    page: int,
    filter_values: Mapping[str, str] | None = None,
    corpus: list[dict[str, object]] | None = None,
) -> list[dict[str, object]]:
    """One page of reviews, after the active filters have been applied."""

    rows = select_reviews(filter_values, corpus)
    start = (page - 1) * REVIEW_PAGE_SIZE
    return rows[start : start + REVIEW_PAGE_SIZE]


def render(
    request: Request,
    template: str,
    *,
    status_code: int = 200,
    **values: object,
) -> HTMLResponse:
    return templates.TemplateResponse(
        request=request,
        name=template,
        context=fixture_context(request, **values),
        status_code=status_code,
    )


def render_public_template(
    request: Request,
    template_id: str,
    *,
    status_code: int = 200,
) -> HTMLResponse:
    """Render one hash-bound anonymous source-template family."""

    page = dict(PUBLIC_PAGE_DATA[template_id])
    page["template_id"] = template_id
    return render(
        request,
        "public_template.html",
        status_code=status_code,
        page_title=str(page["title"]),
        body_class=f"public-template-page template-{template_id}",
        page=page,
    )


def render_public_replay(
    page_id: str,
    *,
    status_code: int = 200,
) -> HTMLResponse:
    """Serve one source-derived, script-stripped public template offline."""

    if not re.fullmatch(r"[a-z0-9-]+", page_id):
        raise RuntimeError("invalid public replay page id")
    page_path = PUBLIC_REPLAY_ROOT / f"{page_id}.html"
    if not page_path.is_file():
        raise RuntimeError(f"missing public replay page: {page_id}")
    return HTMLResponse(
        page_path.read_text(encoding="utf-8"),
        status_code=status_code,
        headers={"X-WebsiteBench-Replay": page_id},
    )


async def urlencoded_form(request: Request) -> dict[str, str]:
    content_type = request.headers.get("content-type", "")
    if "application/x-www-form-urlencoded" not in content_type:
        return {}
    raw = (await request.body()).decode("utf-8", errors="replace")
    parsed = parse_qs(raw, keep_blank_values=True, strict_parsing=False)
    return {key: values[-1] for key, values in parsed.items() if values}


def normalize_review_text(value: str) -> tuple[str, list[str]]:
    """Return the canonical local review text and finite validation errors."""
    normalized = unicodedata.normalize(
        "NFC", value.replace("\r\n", "\n").replace("\r", "\n")
    ).strip()
    errors: list[str] = []
    if not normalized:
        errors.append("Review text is required.")
        return normalized, errors
    if len(normalized) > REVIEW_TEXT_MAX_CODEPOINTS:
        errors.append(
            "Review text must be 2,000 Unicode code points or fewer."
        )
    if any(
        unicodedata.category(character) in {"Cc", "Cf"}
        and character not in {"\n", "\t"}
        for character in normalized
    ):
        errors.append(
            "Review text cannot contain control or format characters; "
            "tabs and line breaks are allowed."
        )
    return normalized, errors


SAFE_NEXT_PATHS = frozenset(
    {
        "/",
        "/compare",
        f"/favorites/software/{PRODUCT_ID}",
        "/reviews/notion/write",
        "/reviews/search/",
        "/p/186596/Notion/",
        "/p/186596/Notion/reviews/",
        "/workspace/",
        "/workspace/saved/products/",
        "/workspace/profile/",
    }
)
LEGACY_NEXT_PATHS = {
    "/local/software/comparison": "/compare",
    "/local/software/favorites": f"/favorites/software/{PRODUCT_ID}",
}


# Same-origin catalog surfaces are also safe redirect targets: product pages,
# category directories, per-product favorites, and per-product review forms.
SAFE_NEXT_RE = re.compile(
    r"^(?:"
    r"/p/\d+/[A-Za-z0-9\-]+/(?:reviews/)?"
    r"|/[a-z0-9][a-z0-9-]*-software/"
    r"|/favorites/software/[A-Za-z0-9.\-]+"
    r"|/reviews/[a-z0-9][a-z0-9.\-]*/write"
    r")$"
)


def safe_next(value: str | None) -> str:
    if value in LEGACY_NEXT_PATHS:
        return LEGACY_NEXT_PATHS[value]
    if value in SAFE_NEXT_PATHS:
        return str(value)
    if value and SAFE_NEXT_RE.match(value):
        return str(value)
    return "/reviews/notion/write"


def safe_registration_next(value: str | None) -> str:
    return safe_next(value)


def render_r2_contract_state(
    request: Request,
    *,
    route_id: str,
    requested_state: str,
    status_code: int = 200,
    canonicalize_state: bool = True,
    **extra: object,
) -> HTMLResponse:
    """Render one exact frozen R2 route/state without inventing source truth."""

    route = SCOPE_ROUTES[route_id]
    declared_states = [
        str(value) for value in route.get("states", []) if isinstance(value, str)
    ]
    if not declared_states:
        raise RuntimeError(f"{route_id} has no frozen states")
    state = (
        requested_state
        if requested_state in declared_states
        else declared_states[0]
    )
    state_heading, state_summary = R2_STATE_COPY[state]
    token, session, created = ensure_auth_session(request)
    context: dict[str, object] = {
        "auth_csrf": auth_csrf(token),
        "auth_session": session,
        "local_mail": None,
        "favorite_state": None,
        "comparison_state": None,
        "product_options": (
            (PRODUCT_ID, "Notion"),
            ("asana-101", "Asana"),
            ("monday-102", "monday.com"),
        ),
        "comparison_products": (
            {
                "id": PRODUCT_ID,
                "name": "Notion",
                "rating": "4.7 / 5",
                "price": "$12 per user/month",
                "features": "Docs, wikis, databases, and project work",
            },
            {
                "id": "asana-101",
                "name": "Asana",
                "rating": "4.5 / 5",
                "price": "$10.99 per user/month",
                "features": "Projects, goals, portfolios, and workflows",
            },
            {
                "id": "monday-102",
                "name": "monday.com",
                "rating": "4.6 / 5",
                "price": "$9 per seat/month",
                "features": "Boards, dashboards, automations, and forms",
            },
        ),
    }
    account = current_account(request)
    if route_id == "auth-local-inbox":
        purpose = request.query_params.get("purpose", "registration")
        if purpose not in {"registration", "password-reset"}:
            purpose = "registration"
        context["local_mail"] = get_auth(request).local_mail_for_session(
            token, purpose=purpose
        )
        context["mail_delivery"] = get_auth(request).session_mail_state(
            token, purpose=purpose
        )
        context["mail_purpose"] = purpose
    elif account is not None and route_id == "software-favorites":
        context["favorite_state"] = get_db(request).favorite_state(
            int(account["id"])
        )
    elif route_id == "local-comparison":
        context["comparison_state"] = get_db(
            request
        ).anonymous_comparison_state(
            comparison_owner_id(request, token)
        )
    context.update(extra)
    canonical_public_route = request.url.path in set(R2_ROUTE_PATHS.values())
    if canonicalize_state and request.method == "GET" and (
        canonical_public_route or not backend_db.test_fixtures_enabled()
    ):
        if route_id == "auth-register":
            flow = get_auth(request).session_flow_status(
                token, purpose="registration"
            )
            state = "entry" if flow["state"] == "missing" else "pending"
        elif route_id == "auth-register-verify":
            flow = get_auth(request).session_flow_status(
                token, purpose="registration"
            )
            owner_session_id = get_auth(request).session_owner_digest(token)
            if get_db(request).has_auth_transition(
                owner_session_id, "registration-verified"
            ):
                state = "verified"
            else:
                state = str(flow["state"])
                if state not in {"challenge", "locked", "stale"}:
                    state = "stale"
        elif route_id == "auth-login":
            state = "authenticated" if account is not None else "entry"
        elif route_id == "auth-logout":
            state = "active" if account is not None else "revoked"
        elif route_id == "auth-password-forgot":
            flow = get_auth(request).session_flow_status(
                token, purpose="password-reset"
            )
            state = (
                "generic-response"
                if flow["state"] != "missing"
                else "entry"
            )
        elif route_id == "auth-password-verify":
            flow = get_auth(request).session_flow_status(
                token, purpose="password-reset"
            )
            state = str(flow["state"])
            if state not in {"challenge", "locked", "stale", "verified"}:
                state = "stale"
        elif route_id == "auth-password-reset":
            flow = get_auth(request).session_flow_status(
                token, purpose="password-reset"
            )
            owner_session_id = get_auth(request).session_owner_digest(token)
            if get_db(request).has_auth_transition(
                owner_session_id, "password-reset-complete"
            ):
                state = "complete"
            elif flow["state"] == "verified":
                state = "verified"
            else:
                state = "stale"
        elif route_id == "auth-local-inbox":
            status = get_auth(request).session_mail_status(
                token, purpose=str(context.get("mail_purpose", "registration"))
            )
            state = (
                status.casefold().replace("_", "-")
                if status is not None
                else "empty"
            )
            if (
                request.query_params.get("view") == "messages"
                and context.get("local_mail") is not None
            ):
                state = "messages"
        elif route_id == "software-favorites":
            favorite = context.get("favorite_state")
            state = (
                "present"
                if isinstance(favorite, dict) and favorite.get("present")
                else "removed"
                if isinstance(favorite, dict)
                and int(favorite.get("version", 0)) > 0
                else "absent"
            )
        elif route_id == "local-comparison":
            comparison = context.get("comparison_state")
            state = (
                "comparison-ready"
                if isinstance(comparison, dict)
                and comparison.get("product_ids")
                else "cleared-aftercare"
                if isinstance(comparison, dict)
                and int(comparison.get("version", 0)) > 0
                else "selection-empty"
            )
        state_heading, state_summary = R2_STATE_COPY[state]
    response = render(
        request,
        "r2_contract_state.html",
        status_code=status_code,
        page_title=str(R2_ROUTE_UI[route_id]["title"]),
        route_id=route_id,
        route_path=R2_ROUTE_PATHS[route_id],
        route_ui=R2_ROUTE_UI[route_id],
        state=state,
        state_heading=state_heading,
        state_summary=state_summary,
        declared_states=declared_states,
        scope_route_id=route_id,
        scope_state_ids=(state,),
        **context,
    )
    if created:
        set_auth_cookie(response, token)
    return response


@app.get("/healthz")
async def healthz(request: Request) -> JSONResponse:
    database = get_db(request)
    return JSONResponse(
        {
            "status": "ok",
            "ok": True,
            "site_id": SITE_ID,
            "stage": "backend",
            "version": VERSION,
            "fixture_id": FIXTURE_ID,
            "frozen_clock": FROZEN_CLOCK,
            "persistent_backend": True,
            "db": {
                "path": str(database.path),
                "migration_head": database.migration_head(),
            },
        },
        headers={
            "X-WebsiteBench-Container-Build-ID": os.environ.get(
                "DEPLOYMENT_BUILD_ID", os.environ.get("SOURCE_REF", "")
            )
        },
    )


@app.post("/__admin/reset")
async def admin_reset(request: Request) -> JSONResponse:
    """Admin-only reset. Never linked from any UI template."""
    if not admin_boundary_authorized(request):
        return JSONResponse({"detail": "Not found"}, status_code=404)
    database = get_db(request)
    auth_store = get_auth(request)
    auth_store.reset_site_state(
        site_reset=database.reset_in_transaction,
        seed_accounts=auth_seed_accounts(),
    )
    return JSONResponse(
        {
            "ok": True,
            "reset": True,
            "reseeded": True,
            "migration_head": database.migration_head(),
            "auth_counts": auth_store.counts(),
        }
    )


@app.post("/__admin/mail/seed-failed", include_in_schema=False)
async def admin_seed_failed_mail(request: Request) -> JSONResponse:
    """Seed one session-owned failed row for a public retry probe."""

    if not admin_boundary_authorized(request):
        return JSONResponse({"detail": "Not found"}, status_code=404)
    values = await urlencoded_form(request)
    purpose = values.get("purpose", "registration")
    if purpose not in {"registration", "password-reset"}:
        return JSONResponse({"detail": "Invalid purpose"}, status_code=422)
    try:
        delivery_attempts = int(values.get("attempts", "2"))
    except ValueError:
        return JSONResponse({"detail": "Invalid attempts"}, status_code=422)
    if delivery_attempts not in {2, 3}:
        return JSONResponse({"detail": "Invalid attempts"}, status_code=422)
    token = request.cookies.get(AUTH_SESSION_COOKIE, "")
    auth_store = get_auth(request)
    if auth_store.resolve_session(token) is None:
        return JSONResponse(
            {"detail": "Current session has no mail flow"},
            status_code=409,
        )
    session_digest = auth_store.session_owner_digest(token)
    now = int(time.time())
    flow_table, flow_id_column = (
        ("local_auth_registration_flows", "pending_id")
        if purpose == "registration"
        else ("local_auth_password_reset_flows", "reset_id")
    )
    with auth_store.connect() as connection:
        connection.execute("BEGIN IMMEDIATE")
        try:
            changed = connection.execute(
                "UPDATE local_auth_mail_outbox SET status='SMTP_FAILED',"
                "is_simulation=0,delivery_attempts=?,claim_token=NULL,"
                "last_error='producer retry probe',attempted_at=?,sent_at=NULL "
                "WHERE mail_id=("
                "SELECT mail_id FROM local_auth_mail_outbox "
                "WHERE session_digest=? AND purpose=? "
                "ORDER BY mail_id DESC LIMIT 1"
                ") AND session_digest=? AND purpose=? "
                "AND status='LOCAL_ONLY' AND is_simulation=1 "
                "AND delivery_attempts=0 AND claim_token IS NULL "
                "AND attempted_at IS NULL AND sent_at IS NULL "
                f"AND flow_id=(SELECT {flow_id_column} FROM {flow_table} "
                "WHERE session_digest=? AND verified_at IS NULL "
                "AND attempts=0 AND expires_at>?)",
                (
                    delivery_attempts,
                    now,
                    session_digest,
                    purpose,
                    session_digest,
                    purpose,
                    session_digest,
                    now,
                ),
            ).rowcount
            if changed != 1:
                connection.rollback()
                return JSONResponse(
                    {"detail": "Current session has no mail flow"},
                    status_code=409,
                )
            row = connection.execute(
                "SELECT mail_id,flow_id,session_digest,status,is_simulation,"
                "delivery_attempts,claim_token,attempted_at,sent_at "
                "FROM local_auth_mail_outbox "
                "WHERE session_digest=? AND purpose=? "
                "ORDER BY mail_id DESC LIMIT 1",
                (session_digest, purpose),
            ).fetchone()
            if (
                row is None
                or str(row["session_digest"]) != session_digest
                or str(row["status"]) != "SMTP_FAILED"
                or int(row["is_simulation"]) != 0
                or int(row["delivery_attempts"]) != delivery_attempts
                or row["claim_token"] is not None
                or row["attempted_at"] != now
                or row["sent_at"] is not None
            ):
                connection.rollback()
                return JSONResponse(
                    {"detail": "Failed mail setup postcondition failed"},
                    status_code=409,
                )
            connection.commit()
        except BaseException:
            connection.rollback()
            raise
    assert row is not None
    return JSONResponse(
        {
            "ok": True,
            "mail_id": int(row["mail_id"]),
            "status": str(row["status"]),
            "delivery_attempts": int(row["delivery_attempts"]),
            "claim_token": row["claim_token"],
            "attempted_at": row["attempted_at"],
            "sent_at": row["sent_at"],
        }
    )


@app.post("/__admin/auth/setup", include_in_schema=False)
async def admin_auth_setup(request: Request) -> JSONResponse:
    """Expire one current session-owned flow for a Producer state probe."""

    if not admin_boundary_authorized(request):
        return JSONResponse({"detail": "Not found"}, status_code=404)
    values = await urlencoded_form(request)
    scenario = values.get("scenario", "")
    scenarios = {
        "registration-expired": (
            "local_auth_registration_flows",
            "pending_id",
        ),
        "password-reset-expired": (
            "local_auth_password_reset_flows",
            "reset_id",
        ),
    }
    target = scenarios.get(scenario)
    if target is None:
        return JSONResponse({"detail": "Invalid scenario"}, status_code=422)
    table, flow_id_column = target
    token = request.cookies.get(AUTH_SESSION_COOKIE, "")
    auth_store = get_auth(request)
    if auth_store.resolve_session(token) is None:
        return JSONResponse(
            {"detail": "Current session has no auth flow"},
            status_code=409,
        )
    session_digest = auth_store.session_owner_digest(token)
    now = int(time.time())
    with auth_store.connect() as connection:
        connection.execute("BEGIN IMMEDIATE")
        try:
            changed = connection.execute(
                f"UPDATE {table} SET expires_at=?,updated_at=? "
                "WHERE session_digest=? AND verified_at IS NULL "
                "AND attempts=0 AND expires_at>?",
                (now - 1, now, session_digest, now),
            ).rowcount
            if changed != 1:
                connection.rollback()
                return JSONResponse(
                    {"detail": "Current session has no auth flow"},
                    status_code=409,
                )
            row = connection.execute(
                f"SELECT {flow_id_column},session_digest,expires_at,attempts,"
                f"verified_at,updated_at FROM {table} "
                "WHERE session_digest=?",
                (session_digest,),
            ).fetchone()
            if (
                row is None
                or str(row["session_digest"]) != session_digest
                or int(row["expires_at"]) > now
                or int(row["attempts"]) != 0
                or row["verified_at"] is not None
                or int(row["updated_at"]) != now
            ):
                connection.rollback()
                return JSONResponse(
                    {"detail": "Auth setup postcondition failed"},
                    status_code=409,
                )
            connection.commit()
        except BaseException:
            connection.rollback()
            raise
    return JSONResponse({"ok": True, "scenario": scenario})


@app.get("/__admin/mail/state", include_in_schema=False)
async def admin_mail_state(request: Request) -> JSONResponse:
    """Read one session-owned mail row for a Producer activation probe."""

    if not admin_boundary_authorized(request):
        return JSONResponse({"detail": "Not found"}, status_code=404)
    purpose = request.query_params.get("purpose", "registration")
    if purpose not in {"registration", "password-reset"}:
        return JSONResponse({"detail": "Invalid purpose"}, status_code=422)
    token = request.cookies.get(AUTH_SESSION_COOKIE, "")
    state = get_auth(request).session_mail_state(token, purpose=purpose)
    if state is None:
        return JSONResponse(
            {"detail": "Current session has no mail flow"},
            status_code=409,
        )
    return JSONResponse(
        {
            "ok": True,
            "mail_id": int(state["mail_id"]),
            "status": str(state["status"]),
            "delivery_attempts": int(state["delivery_attempts"]),
            "claim_token": state["claim_token"],
            "attempted_at": state["attempted_at"],
            "sent_at": state["sent_at"],
            "retryable": bool(state["retryable"]),
        }
    )


@app.post("/__worker/mail/dispatch", include_in_schema=False)
async def private_mail_worker_dispatch(request: Request) -> JSONResponse:
    """Dispatch at most one queued message across the private worker boundary."""

    runtime = request.app.state.mail_runtime
    expected = (
        str(runtime["worker_token"])
        if runtime["mode"] == MAIL_SMTP_PENDING
        else ""
    )
    supplied = request.headers.get("X-Clawbench-Mail-Worker-Token", "")
    if (
        not expected
        or not supplied
        or not secrets.compare_digest(supplied, expected)
    ):
        return JSONResponse({"detail": "Not found"}, status_code=404)
    event = dispatch_next_mail(request.app)
    return JSONResponse(
        {
            "ok": True,
            "dispatched": event is not None,
            "status": event["status"] if event is not None else None,
            "target_request_count": (
                event["target_request_count"] if event is not None else 0
            ),
            "accepted_effect_count": (
                event["durable_accepted_effect_count"]
                if event is not None
                else 0
            ),
            "production_request_count": 0,
            "production_effect_count": 0,
        }
    )


@app.get(
    "/__admin/contract-audit/{route_id}",
    response_class=HTMLResponse,
    include_in_schema=False,
)
async def admin_contract_audit(
    request: Request,
    route_id: str,
    state: str,
) -> Response:
    if not admin_boundary_authorized(request):
        return JSONResponse({"detail": "Not found"}, status_code=404)
    route = SCOPE_ROUTES.get(route_id)
    if route is None or state not in route.get("states", []):
        return JSONResponse(
            {"detail": "Unknown contract route or state"},
            status_code=404,
        )
    return render(
        request,
        "contract_audit.html",
        page_title="Contract audit",
        body_class="contract-audit-page",
        audit_route_id=route_id,
        audit_state_id=state,
        scope_effect_affordances=scope_effect_affordances(
            route_id,
            [state],
        ),
    )


@app.get("/", response_class=HTMLResponse)
async def home(request: Request) -> HTMLResponse:
    account = current_account(request)
    if account is None:
        return render_public_replay("home")
    return render(
        request,
        "home.html",
        page_title="Find the right software",
        body_class="home-page",
        scope_route_id="home",
        scope_state_ids=(
            ("authenticated",)
            if account is not None
            else ("loaded", "search-focused")
        ),
    )


@app.get("/workspace/", response_class=HTMLResponse)
async def workspace_dashboard(request: Request) -> HTMLResponse:
    """Render the source-observed buyer workspace in local account state."""

    return render(
        request,
        "workspace.html",
        page_title="My Account",
        body_class="workspace-page",
        workspace_view="dashboard",
        scope_route_id="workspace-dashboard",
        favorite_state=None,
    )


@app.get("/workspace/saved/products/", response_class=HTMLResponse)
async def workspace_saved_products(request: Request) -> HTMLResponse:
    account = current_account(request)
    favorite_state = (
        get_db(request).favorite_state(int(account["id"]))
        if account is not None
        else None
    )
    saved_products = (
        get_db(request).list_favorite_products(int(account["id"]))
        if account is not None
        else []
    )
    return render(
        request,
        "workspace.html",
        page_title="Saved Products",
        body_class="workspace-page workspace-saved-products-page",
        workspace_view="saved-products",
        scope_route_id="workspace-saved-products",
        favorite_state=favorite_state,
        saved_products=saved_products,
    )


@app.get("/workspace/profile/", response_class=HTMLResponse)
async def workspace_profile(request: Request) -> HTMLResponse:
    account = current_account(request)
    profile_stats = None
    if account is not None:
        database = get_db(request)
        profile_stats = {
            "member_since": FROZEN_CLOCK.split("T")[0],
            "favorite_count": database.count_favorites(int(account["id"])),
            "review_count": database.count_submissions(int(account["id"])),
        }
    return render(
        request,
        "workspace.html",
        page_title="My Profile",
        body_class="workspace-page workspace-profile-page",
        workspace_view="profile",
        scope_route_id="workspace-profile",
        favorite_state=None,
        profile_stats=profile_stats,
    )


@app.get("/software/search", response_class=HTMLResponse)
async def software_search(
    request: Request, q: str = "", state: str = "results"
) -> HTMLResponse:
    normalized = state if state in {"results", "loading", "empty", "error"} else "results"
    results: list[dict] = []
    similar_products: list[dict] = []
    if normalized == "results":
        database = get_db(request)
        results = (
            database.top_products(20)
            if not q.strip()
            else database.search_products(q, limit=25)
        )
        if results:
            similar_products = database.alternatives_for(
                str(results[0]["id"]), limit=4
            )
    return render(
        request,
        "search.html",
        page_title="Software search",
        body_class="software-search-page",
        query=q,
        state=normalized,
        has_results=bool(results),
        results=results,
        similar_products=similar_products,
        scope_route_id=(
            "software-search"
            if normalized == "results"
            else "software-search-recovery-simulation"
        ),
        scope_state_ids=(normalized,),
    )


@app.get("/search/", response_class=HTMLResponse)
async def public_search(
    request: Request,
    query: str = "",
    state: str = "results",
) -> HTMLResponse:
    """Preserve the current public search URL while sharing local results."""

    if state == "results" and query.casefold() == "notion":
        return render_public_replay("software-search")
    return await software_search(request, q=query, state=state)


@app.get("/categories/", response_class=HTMLResponse)
async def categories_index(request: Request) -> HTMLResponse:
    return render_public_replay("categories-index")


@app.get("/accounting-software/", response_class=HTMLResponse)
async def accounting_software(request: Request) -> HTMLResponse:
    return render_public_replay("category-directory")


@app.get("/accounting-software/s/free/", response_class=HTMLResponse)
async def free_accounting_software(request: Request) -> HTMLResponse:
    return render_public_replay("subcategory-directory")


CATEGORY_PAGE_SIZE = 25
CATEGORY_SORTS = ("recommended", "rating", "reviews")
CATEGORY_FACETS = {
    "free": "Free",
    "mac": "Mac",
    "small-businesses": "Small Businesses",
}


def sorted_category_listing(products: list[dict], sort: str) -> list[dict]:
    if sort == "rating":
        return sorted(products, key=lambda p: (-(p["rating"] or 0), p["id"]))
    if sort == "reviews":
        return sorted(
            products, key=lambda p: (-(p["local_review_count"] or 0), p["id"])
        )
    return products


def related_category_links(category_slug: str) -> list[dict[str, str]]:
    index = category_index()
    slugs = sorted(index)
    position = slugs.index(category_slug)
    related = []
    for offset in (-2, -1, 1, 2, 3):
        neighbor = slugs[(position + offset) % len(slugs)]
        if neighbor != category_slug:
            related.append({"slug": neighbor, "label": index[neighbor]})
    return related[:5]


def render_category_listing(
    request: Request,
    *,
    category_slug: str,
    category_name: str,
    products: list[dict],
    listing_provenance: str,
    page: int,
    sort: str,
    facets: list[dict[str, str]] | None,
    search_term: str = "",
) -> HTMLResponse:
    if search_term:
        needle = search_term.casefold()
        products = [
            product
            for product in products
            if needle in str(product["name"]).casefold()
        ]
    feature_counts: dict[str, int] = {}
    for product in products:
        for feature in product.get("features") or []:
            feature_counts[feature] = feature_counts.get(feature, 0) + 1
    rail_features = [
        feature
        for feature, _ in sorted(
            feature_counts.items(), key=lambda item: (-item[1], item[0])
        )[:10]
    ]
    page_count = max(
        1, (len(products) + CATEGORY_PAGE_SIZE - 1) // CATEGORY_PAGE_SIZE
    )
    page = min(max(page, 1), page_count)
    start = (page - 1) * CATEGORY_PAGE_SIZE
    return render(
        request,
        "category_directory.html",
        page_title=f"Best {category_name} Software 2026 Reviews",
        body_class="category-directory-page",
        category_slug=category_slug,
        category_name=category_name,
        products=products[start : start + CATEGORY_PAGE_SIZE],
        total_count=len(products),
        listing_provenance=listing_provenance,
        page=page,
        page_count=page_count,
        sort=sort,
        facets=facets,
        search_term=search_term,
        rail_features=rail_features,
        related_categories=related_category_links(category_slug),
    )


# Registered after the literal /accounting-software/ routes above so those keep
# serving their frozen captures; Starlette matches routes in registration order.
@app.get("/{category_slug}-software/", response_class=HTMLResponse)
async def category_directory(
    request: Request,
    category_slug: str,
    page: int = 1,
    sort: str = "recommended",
    search: str = "",
) -> Response:
    """Resolve one of the 1001 category routes named by the frozen directory.

    A slug the frozen directory never listed stays a 404 -- inventing categories
    would misrepresent the source. A listed slug renders its catalog-backed
    directory; listings whose membership was assembled locally rather than
    captured say so via the rendered provenance disclosure.
    """

    label = category_label(category_slug)
    if label is None:
        return render_public_replay("not-found", status_code=404)
    db = get_db(request)
    products = sorted_category_listing(
        db.products_for_category(category_slug),
        sort if sort in CATEGORY_SORTS else "recommended",
    )
    return render_category_listing(
        request,
        category_slug=category_slug,
        category_name=label,
        products=products,
        listing_provenance=db.category_listing_provenance(category_slug)
        or "derived",
        page=page,
        sort=sort if sort in CATEGORY_SORTS else "recommended",
        facets=[
            {"slug": slug, "label": f"{name} {label}"}
            for slug, name in CATEGORY_FACETS.items()
        ],
        search_term=" ".join(search.split())[:80],
    )


@app.get("/p/186596/Notion/", response_class=HTMLResponse)
async def notion_profile(request: Request) -> HTMLResponse:
    if current_account(request) is None:
        return render_public_replay("product-profile")
    return render(
        request,
        "profile.html",
        page_title="Notion software",
        body_class="notion-profile-page",
        profile_reviews=review_cards(1)[:10],
        scope_route_id="notion-profile",
        scope_state_ids=("profile", "review-summary"),
    )


@app.get("/p/186596/Notion/reviews/", response_class=HTMLResponse)
async def notion_reviews(
    request: Request,
    page: int = 1,
    state: str = "review-summary",
    sort: str = "most-helpful",
    rating: str = "all",
    company_size: str = "all",
    role: str = "all",
    length_of_use: str = "all",
    frequency: str = "all",
) -> HTMLResponse:
    if current_account(request) is None and not request.url.query:
        return render_public_replay("product-reviews")
    current_page = min(max(page, 1), REVIEW_PAGE_COUNT)
    review_state = (
        state
        if state in {"review-summary", "filter-display"}
        else "review-summary"
    )
    filter_values = {
        "sort": (
            sort
            if sort in {"most-helpful", "newest"}
            else "most-helpful"
        ),
        "rating": rating if rating in {"all", "5"} else "all",
        "company_size": (
            company_size
            if company_size in {"all", "1-10"}
            else "all"
        ),
        "role": role if role in {"all", "manager"} else "all",
        "length_of_use": (
            length_of_use
            if length_of_use in {"all", "1-2-years"}
            else "all"
        ),
        "frequency": (
            frequency if frequency in {"all", "daily"} else "all"
        ),
    }
    # Page over the filtered set, not the whole corpus, so the counter and the
    # pager describe the reviews actually on screen.
    matching_reviews = select_reviews(filter_values)
    matching_total = len(matching_reviews)
    page_count = max(
        1, (matching_total + REVIEW_PAGE_SIZE - 1) // REVIEW_PAGE_SIZE
    )
    current_page = min(current_page, page_count)
    visible = matching_reviews[
        (current_page - 1) * REVIEW_PAGE_SIZE : current_page * REVIEW_PAGE_SIZE
    ]
    first_review = (current_page - 1) * REVIEW_PAGE_SIZE + 1 if visible else 0
    last_review = (current_page - 1) * REVIEW_PAGE_SIZE + len(visible)
    return render(
        request,
        "reviews.html",
        page_title="Notion reviews",
        body_class="notion-reviews-page",
        review_cards=visible,
        review_pages=range(1, page_count + 1),
        current_page=current_page,
        review_state=review_state,
        review_filters=filter_values,
        first_review=first_review,
        last_review=last_review,
        local_review_total=LOCAL_REVIEW_TOTAL,
        local_review_average=LOCAL_REVIEW_AVERAGE,
        matching_review_total=matching_total,
        filters_active=any(
            value != "all"
            for key, value in filter_values.items()
            if key != "sort"
        ),
        scope_route_id="notion-reviews",
        scope_state_ids=(review_state,),
    )


@app.get("/p/186596/Notion/alternatives/", response_class=HTMLResponse)
async def notion_alternatives(request: Request) -> HTMLResponse:
    return render_public_replay("product-alternatives")


@app.get("/p/186596/Notion/pricing/", response_class=HTMLResponse)
async def notion_pricing(request: Request) -> HTMLResponse:
    return render_public_replay("product-pricing")


def resolve_catalog_product(
    request: Request, product_id: str, product_slug: str, subpage: str = ""
) -> dict | Response:
    """The catalog product for a /p/ URL, or the 404/308 response instead."""

    product = get_db(request).get_product(product_id)
    if product is None or not product.get("url_slug"):
        return render_public_replay("not-found", status_code=404)
    if product_slug != product["url_slug"]:
        return RedirectResponse(
            f"/p/{product_id}/{product['url_slug']}/{subpage}", status_code=308
        )
    return product


def product_primary_category(
    request: Request, product: Mapping[str, object]
) -> dict[str, str] | None:
    for slug in get_db(request).categories_for_product(str(product["id"])):
        label = category_label(slug)
        if label:
            return {"slug": slug, "label": label}
    return None


# Registered after the literal Notion routes above, which keep serving their
# frozen captures; every other catalog product renders the template family.
@app.get("/p/{product_id}/{product_slug}/", response_class=HTMLResponse)
async def product_profile_page(
    request: Request, product_id: str, product_slug: str
) -> Response:
    product = resolve_catalog_product(request, product_id, product_slug)
    if isinstance(product, Response):
        return product
    corpus = product_review_corpus(product)
    category_chips = [
        {"slug": slug, "label": category_label(slug)}
        for slug in get_db(request).categories_for_product(product_id)[:5]
        if category_label(slug)
    ]
    return render(
        request,
        "product_profile.html",
        page_title=f"{product['name']} Software Reviews, Pros and Cons",
        body_class="product-profile-page",
        product=product,
        sub_ratings=profile_sub_ratings(product),
        primary_category=(category_chips[0] if category_chips else None),
        category_chips=category_chips,
        top_reviews=corpus[:3],
        alternatives=get_db(request).alternatives_for(product_id, limit=8),
    )


@app.get("/p/{product_id}/{product_slug}/reviews/", response_class=HTMLResponse)
async def product_reviews_page(
    request: Request,
    product_id: str,
    product_slug: str,
    page: int = 1,
    sort: str = "most-helpful",
    rating: str = "all",
    company_size: str = "all",
    role: str = "all",
    length_of_use: str = "all",
    frequency: str = "all",
) -> Response:
    product = resolve_catalog_product(
        request, product_id, product_slug, subpage="reviews/"
    )
    if isinstance(product, Response):
        return product
    corpus = product_review_corpus(product)
    filter_values = {
        "sort": sort if sort in ("most-helpful", "newest") else "most-helpful",
        "rating": rating,
        "company_size": company_size,
        "role": role,
        "length_of_use": length_of_use,
        "frequency": frequency,
    }
    submitted = [
        {
            "author": row["display_name"],
            "role": "Verified member",
            "industry": "Submitted on this edition",
            "tenure": "6-12 months",
            "company_size": "1-10",
            "frequency": "daily",
            "title": "Member review",
            "rating": int(row["rating"]),
            "rating_class": f"rating-{int(row['rating'])}",
            "date": "August 2, 2026",
            "date_sort": "2026-08-02",
            "overall": row["review_text"],
            "pros": "",
            "cons": "",
            "avatar": REVIEW_AVATARS[0],
            "local_number": 0,
        }
        for row in get_db(request).submissions_for_product(product_id)
    ]
    filtered = select_reviews(filter_values, corpus)
    rows = submitted + filtered if page == 1 and not request.url.query else filtered
    page_count = max(1, (len(rows) + REVIEW_PAGE_SIZE - 1) // REVIEW_PAGE_SIZE)
    current_page = min(max(page, 1), page_count)
    start = (current_page - 1) * REVIEW_PAGE_SIZE
    histogram = [
        (star, sum(1 for card in corpus if card["rating"] == star))
        for star in (5, 4, 3, 2, 1)
    ]
    return render(
        request,
        "product_reviews.html",
        page_title=f"{product['name']} Reviews 2026",
        body_class="product-reviews-page",
        product=product,
        overall_rating=round(float(product["rating"] or 4.2), 1),
        total_reviews=len(corpus),
        histogram=histogram,
        review_filters=filter_values,
        page_reviews=rows[start : start + REVIEW_PAGE_SIZE],
        page_count=page_count,
        current_page=current_page,
        alternatives=get_db(request).alternatives_for(product_id, limit=4),
    )


@app.get(
    "/p/{product_id}/{product_slug}/alternatives/", response_class=HTMLResponse
)
async def product_alternatives_page(
    request: Request, product_id: str, product_slug: str
) -> Response:
    product = resolve_catalog_product(
        request, product_id, product_slug, subpage="alternatives/"
    )
    if isinstance(product, Response):
        return product
    return render(
        request,
        "product_alternatives.html",
        page_title=f"Top {product['name']} Alternatives 2026",
        body_class="product-alternatives-page",
        product=product,
        primary_category=product_primary_category(request, product),
        alternatives=get_db(request).alternatives_for(product_id, limit=10),
    )


@app.get("/p/{product_id}/{product_slug}/pricing/", response_class=HTMLResponse)
async def product_pricing_page(
    request: Request, product_id: str, product_slug: str
) -> Response:
    product = resolve_catalog_product(
        request, product_id, product_slug, subpage="pricing/"
    )
    if isinstance(product, Response):
        return product
    starting = product.get("pricing") or "Contact vendor"
    pricing_tiers = [
        {
            "name": "Starter",
            "price": starting,
            "cadence": "per user",
            "points": [
                "Core features for small teams",
                "Standard support and updates",
                "Cancel any time",
            ],
            "highlight": False,
        },
        {
            "name": "Business",
            "price": "Contact vendor",
            "cadence": "",
            "points": [
                "Everything in Starter",
                "Advanced controls and reporting",
                "Priority support",
            ],
            "highlight": True,
        },
        {
            "name": "Enterprise",
            "price": "Contact vendor",
            "cadence": "",
            "points": [
                "Custom deployment options",
                "Security and compliance reviews",
                "Dedicated onboarding",
            ],
            "highlight": False,
        },
    ]
    return render(
        request,
        "product_pricing.html",
        page_title=f"{product['name']} Pricing 2026",
        body_class="product-pricing-page",
        product=product,
        pricing_tiers=pricing_tiers,
    )


@app.get("/compare/", response_class=HTMLResponse)
async def public_compare_builder(request: Request) -> HTMLResponse:
    return render_public_replay("compare-empty")


@app.get("/compare/selected", response_class=HTMLResponse)
async def selected_product_comparison(request: Request, products: str = "") -> Response:
    """Render the two-to-four products chosen in the public comparison builder."""

    product_ids = list(
        dict.fromkeys(
            part.strip() for part in products.split(",") if part.strip()
        )
    )
    if not 2 <= len(product_ids) <= 4 or any(
        not part.isdigit() for part in product_ids
    ):
        return JSONResponse(
            {"detail": "Choose between two and four products to compare."},
            status_code=400,
        )
    database = get_db(request)
    selected_products = [
        database.get_product(product_id) for product_id in product_ids
    ]
    if any(product is None for product in selected_products):
        return JSONResponse(
            {"detail": "One or more products were not found."},
            status_code=404,
        )
    return render(
        request,
        "compare_selected.html",
        page_title="Compare selected software",
        body_class="comparison-selected-page",
        products=selected_products,
    )


@app.get(
    "/compare/153472-253516/Startquestion-vs-SurveyMonkey",
    response_class=HTMLResponse,
)
@app.get(
    "/compare/186596-147657/Notion-vs-monday-com",
    response_class=HTMLResponse,
)
async def public_product_comparison(request: Request) -> HTMLResponse:
    return render_public_replay("compare-products")


# Registered after the two frozen pair literals above; any other catalog pair
# renders the data-driven comparison template.
@app.get("/compare/{pair_ids}/{pair_names}", response_class=HTMLResponse)
async def catalog_product_comparison(
    request: Request, pair_ids: str, pair_names: str
) -> Response:
    parts = pair_ids.split("-")
    if len(parts) != 2 or parts[0] == parts[1]:
        return render_public_replay("not-found", status_code=404)
    database = get_db(request)
    product_a = database.get_product(parts[0])
    product_b = database.get_product(parts[1])
    if (
        product_a is None
        or product_b is None
        or not product_a.get("url_slug")
        or not product_b.get("url_slug")
    ):
        return render_public_replay("not-found", status_code=404)
    canonical_ids = "-".join(sorted(parts))
    if pair_ids != canonical_ids:
        product_a, product_b = (
            (product_a, product_b)
            if canonical_ids.startswith(str(product_a["id"]))
            else (product_b, product_a)
        )
    first, second = sorted((product_a, product_b), key=lambda p: str(p["id"]))
    canonical_names = f"{first['url_slug']}-vs-{second['url_slug']}"
    if pair_ids != canonical_ids or pair_names != canonical_names:
        return RedirectResponse(
            f"/compare/{canonical_ids}/{canonical_names}", status_code=308
        )
    swap_options = [
        option
        for option in database.alternatives_for(str(first["id"]), limit=6)
        if str(option["id"]) != str(second["id"])
    ][:4]
    return render(
        request,
        "compare_pair.html",
        page_title=f"{first['name']} vs {second['name']} 2026 Comparison",
        body_class="comparison-pair-page",
        product_a=first,
        product_b=second,
        swap_options=swap_options,
    )


@app.get(
    "/project-management-software/shortlist/",
    response_class=HTMLResponse,
)
async def project_management_shortlist(request: Request) -> HTMLResponse:
    return render_public_replay("shortlist")


# Registered after the literal frozen shortlist route above so that capture
# keeps serving byte-identical; every other category gets its catalog listing.
@app.get("/{category_slug}-software/shortlist/", response_class=HTMLResponse)
async def category_shortlist(request: Request, category_slug: str) -> Response:
    label = category_label(category_slug)
    if label is None:
        return render_public_replay("not-found", status_code=404)
    db = get_db(request)
    products = sorted_category_listing(
        db.products_for_category(category_slug), "rating"
    )[:10]
    return render(
        request,
        "category_shortlist.html",
        page_title=f"2026 Capterra Shortlist for {label}",
        body_class="category-shortlist-page",
        category_slug=category_slug,
        category_name=label,
        products=products,
        listing_provenance=db.category_listing_provenance(category_slug)
        or "derived",
    )


@app.get("/{category_slug}-software/s/{facet}/", response_class=HTMLResponse)
async def category_facet(
    request: Request,
    category_slug: str,
    facet: str,
    page: int = 1,
    sort: str = "recommended",
) -> Response:
    label = category_label(category_slug)
    facet_name = CATEGORY_FACETS.get(facet)
    if label is None or facet_name is None:
        return render_public_replay("not-found", status_code=404)
    db = get_db(request)
    listing = db.products_for_category(category_slug)
    subset = [
        product
        for product in listing
        if int(
            hashlib.sha256(
                f"capterra-facet:{facet}:{product['id']}".encode("utf-8")
            ).hexdigest()[:8],
            16,
        )
        % 5
        < 3
    ] or listing[: max(1, len(listing) // 2)]
    return render_category_listing(
        request,
        category_slug=category_slug,
        category_name=f"{facet_name} {label}",
        products=sorted_category_listing(
            subset, sort if sort in CATEGORY_SORTS else "recommended"
        ),
        listing_provenance="derived",
        page=page,
        sort=sort if sort in CATEGORY_SORTS else "recommended",
        facets=None,
    )


@app.get("/reviews/search/", response_class=HTMLResponse)
async def review_search(request: Request) -> HTMLResponse:
    if current_account(request) is None:
        return render_public_replay("review-search")
    return render(
        request,
        "review_search.html",
        page_title="Write a software review",
        body_class="review-search-page",
        scope_route_id="review-search",
        scope_state_ids=(
            "product-search",
            "industry-selection",
            "disabled-next",
        ),
    )


@app.get("/our-story/", response_class=HTMLResponse)
async def our_story(request: Request) -> HTMLResponse:
    return render_public_replay("our-story")


@app.get("/careers", response_class=HTMLResponse, include_in_schema=False)
async def careers(request: Request) -> HTMLResponse:
    """Describe the local careers boundary without inventing live vacancies."""

    return render(
        request,
        "careers.html",
        page_title="Careers at Capterra demo",
        body_class="careers-page",
    )


@app.get("/resources/", response_class=HTMLResponse)
async def resources_index(request: Request) -> HTMLResponse:
    return render_public_replay("resources-index")


@app.post("/api/ebook/request")
async def request_ebook(request: Request) -> JSONResponse:
    """Acknowledge the public guide request without external mail side effects."""

    values = await urlencoded_form(request)
    email = (
        unicodedata.normalize("NFC", values.get("emailAddress", ""))
        .strip()
        .casefold()
    )
    if (
        len(email) > 254
        or re.fullmatch(r"[^\s@]+@[^\s@]+\.[^\s@]+", email) is None
    ):
        return JSONResponse(
            {"detail": "Please enter a valid email address."},
            status_code=400,
        )
    digest = hashlib.sha256(email.encode("utf-8")).hexdigest()
    digests: set[str] = request.app.state.ebook_request_digests
    duplicate = digest in digests
    if not duplicate:
        if len(digests) >= 1000:
            digests.clear()
        digests.add(digest)
    return JSONResponse(
        {
            "ok": True,
            "duplicate": duplicate,
            "message": (
                "Request already received. No email was sent by this WebsiteBench demo."
                if duplicate
                else "Request received. No email was sent by this WebsiteBench demo."
            ),
        }
    )


@app.get("/glossary/", include_in_schema=False)
async def glossary_alias() -> RedirectResponse:
    return RedirectResponse("/resources/", status_code=308)


@app.get("/resources/how-we-verify-reviews/", response_class=HTMLResponse)
async def review_verification_policy(request: Request) -> HTMLResponse:
    return render_public_replay("resource-article")


@app.get("/resources/news/", response_class=HTMLResponse)
async def resources_news(request: Request) -> HTMLResponse:
    return render_public_replay("resources-news")


@app.get("/legal/terms-of-use/", response_class=HTMLResponse)
async def terms_of_use(request: Request) -> HTMLResponse:
    return render_public_replay("legal-terms")


LEGAL_POLICY_SECTIONS: dict[str, tuple[str, list[dict[str, str]]]] = {
    "privacy": (
        "Privacy Policy",
        [
            {"title": "Scope", "body": "This policy explains how the Capterra WebsiteBench demo handles information while you browse local pages and use local account features."},
            {"title": "Personal Information We Collect", "body": "The demo collects only the information required for the local feature you choose. It does not import production Capterra accounts or vendor data."},
            {"title": "How We Use Personal Information", "body": "Information is used to provide local sessions, reviews, saved products, and other explicitly requested demo features."},
            {"title": "Reviews and User-Generated Content", "body": "Submitted local reviews are displayed within this isolated site and remain separate from production Capterra services."},
            {"title": "How We Disclose Personal Information", "body": "The demo does not sell personal information or send it to advertising partners."},
            {"title": "Legal Bases for Processing", "body": "Processing is limited to providing requested local functionality and protecting the integrity of the demo."},
            {"title": "Cookies and Similar Technologies", "body": "Essential local cookies maintain sessions and security boundaries. Third-party advertising scripts are not required."},
            {"title": "Marketing Choices", "body": "This demo does not enroll visitors in production marketing programs."},
            {"title": "Data Retention", "body": "Local demo data follows the deployment retention and isolation settings."},
            {"title": "International Data Transfers", "body": "No production cross-border transfer is created by browsing this local replica."},
        ],
    ),
    "vendor": (
        "General Vendor Terms",
        [
            {"title": "Scope", "body": "These terms describe the boundary between this buyer-facing demo and external G2 Digital Markets vendor services."},
            {"title": "Vendor Accounts", "body": "Vendor accounts, product claims, lead programs, and commercial listings are provided only by the external vendor portal."},
            {"title": "Product Information", "body": "Product information shown here is a local benchmark catalog and does not update a production listing."},
            {"title": "Reviews", "body": "Local review fixtures do not create, modify, or moderate reviews on production Capterra."},
            {"title": "Commercial Programs", "body": "No advertising purchase, lead order, or paid placement can be created in this deployment."},
        ],
    ),
    "user": (
        "General User Terms",
        [
            {"title": "Using the Site", "body": "Use this replica to browse software, compare products, and exercise the local review workflow."},
            {"title": "Accounts", "body": "Accounts created here are isolated local accounts and are not production Capterra credentials."},
            {"title": "Acceptable Use", "body": "Do not attempt to submit unlawful content, interfere with the service, or misrepresent local benchmark data as production data."},
            {"title": "User Content", "body": "You remain responsible for local content you choose to submit."},
            {"title": "Availability", "body": "The benchmark deployment may change or reset as part of testing and evaluation."},
        ],
    ),
    "transfer": (
        "Data Transfer Addendum",
        [
            {"title": "Purpose", "body": "This addendum documents that the local WebsiteBench deployment does not connect to production Capterra customer or vendor databases."},
            {"title": "Data Isolation", "body": "Each site has distinct storage and session identity. Data is not shared with other WebsiteBench sites."},
            {"title": "Security", "body": "Access controls, scoped cookies, and local runtime validation protect demo data."},
            {"title": "Subprocessors", "body": "Only services declared by the active deployment runtime may process local demo data."},
            {"title": "Deletion", "body": "Local data can be removed according to the benchmark environment lifecycle."},
        ],
    ),
}


def render_legal_policy(request: Request, policy_id: str) -> HTMLResponse:
    title, sections = LEGAL_POLICY_SECTIONS[policy_id]
    return render(
        request,
        "legal_policy.html",
        page_title=title,
        body_class="legal-policy-page",
        policy_id=policy_id,
        policy_title=title,
        policy_sections=sections,
    )


@app.get("/legal/privacy-policy/", response_class=HTMLResponse)
async def privacy_policy(request: Request) -> HTMLResponse:
    return render_legal_policy(request, "privacy")


@app.get("/legal/general-vendor-terms/", response_class=HTMLResponse)
async def general_vendor_terms(request: Request) -> HTMLResponse:
    return render_legal_policy(request, "vendor")


@app.get("/legal/general-user-terms/", response_class=HTMLResponse)
async def general_user_terms(request: Request) -> HTMLResponse:
    return render_legal_policy(request, "user")


@app.get("/legal/data-transfer-addendum/", response_class=HTMLResponse)
async def data_transfer_addendum(request: Request) -> HTMLResponse:
    return render_legal_policy(request, "transfer")


@app.get(
    "/resources/category/accounting-and-finance/",
    response_class=HTMLResponse,
)
async def accounting_resources(request: Request) -> HTMLResponse:
    return render_public_replay("resource-category")


@app.get("/resources/author/david-jani/", response_class=HTMLResponse)
async def resource_author(request: Request) -> HTMLResponse:
    return render_public_replay("resource-author")


@app.get("/resources/accounting-automation/", response_class=HTMLResponse)
async def accounting_automation(request: Request) -> HTMLResponse:
    return render_public_replay("resource-editorial-article")


@app.get(
    "/resources/proprietary-data-research/",
    response_class=HTMLResponse,
)
async def proprietary_data_research(request: Request) -> HTMLResponse:
    return render_public_replay("resource-research-index")


@app.get("/resources/research-agenda/", response_class=HTMLResponse)
async def research_agenda(request: Request) -> HTMLResponse:
    return render_public_replay("resource-research-agenda")


@app.get("/_websitebench-missing-page/", response_class=HTMLResponse)
@app.get("/faq", response_class=HTMLResponse)
@app.get("/faq/", response_class=HTMLResponse)
@app.get("/services", response_class=HTMLResponse)
@app.get("/services/", response_class=HTMLResponse)
@app.get("/faq/faqs-verification/", response_class=HTMLResponse)
async def public_not_found(request: Request) -> HTMLResponse:
    replay_id = {
        "/faq": "faq",
        "/faq/": "faq",
        "/services": "services",
        "/services/": "services",
        "/faq/faqs-verification/": "faq-verification",
    }.get(request.url.path, "not-found")
    return render_public_replay(replay_id, status_code=404)


@app.get("/vendors/", response_class=HTMLResponse)
async def vendor_boundary(
    request: Request,
    capability: str = "commercial",
) -> HTMLResponse:
    if capability == "commercial" and "capability" not in request.query_params:
        response = render(
            request,
            "vendors_current.html",
            page_title="Capterra for Vendors",
            body_class="vendors-current-page",
        )
        response.headers["X-WebsiteBench-Replay"] = "vendors"
        return response
    normalized_capability = (
        capability
        if capability in {"commercial", "listing", "login"}
        else "commercial"
    )
    boundary_state = (
        "offline-boundary"
        if normalized_capability == "commercial"
        else "unavailable-capability"
    )
    return render(
        request,
        "vendor_boundary.html",
        page_title="For software vendors",
        vendor_capability=normalized_capability,
        scope_route_id="vendor-boundary",
        scope_state_ids=(boundary_state, "return"),
    )


# ---------------------------------------------------------------------------
# Honest destinations for controls whose real target is off this site
#
# Source evidence: materials/capterra/artifacts/parity/auth/signin/desktop/.
# The header's "Join or Log in" opens an overlay offering CONTINUE WITH GOOGLE
# and CONTINUE WITH LINKEDIN above a "Continue with email" fallback.  Neither
# provider can be honoured locally, and a provider button that silently does
# nothing — or that quietly signs someone in — is the failure this boundary
# exists to prevent.  Each one is a real link to a page that names the
# destination and says plainly it is not part of this edition; none of them
# touches the session.
# ---------------------------------------------------------------------------

EXTERNAL_DESTINATIONS: dict[str, dict[str, str]] = {
    "google-auth": {
        "label": "Continue with Google",
        "description": (
            "Signing in with a Google account is handled by Google and is not "
            "reproduced in this edition."
        ),
        "return_path": "/auth/login",
        "return_label": "Back to sign in",
    },
    "linkedin-auth": {
        "label": "Continue with LinkedIn",
        "description": (
            "Signing in with a LinkedIn account is handled by LinkedIn and is "
            "not reproduced in this edition."
        ),
        "return_path": "/auth/login",
        "return_label": "Back to sign in",
    },
    "privacy-policy": {
        "label": "Privacy Policy",
        "description": (
            "The Privacy Policy is published outside this edition and is not "
            "reproduced here. The Terms of Use are available locally."
        ),
        "return_path": "/legal/terms-of-use/",
        "return_label": "Read the Terms of Use",
    },
}


EXTERNAL_REDIRECTS: dict[str, str] = {
    "careers": "https://company.g2.com/careers",
    "g2-get-listed": "https://app.g2digitalmarkets.com/get-listed/start",
    "g2-vendor-login": "https://app.g2digitalmarkets.com/",
    "g2-marketing": "https://www.g2digitalmarkets.com/",
    "linkedin": "https://www.linkedin.com/company/capterra",
    "x": "https://x.com/capterra",
    "facebook": "https://www.facebook.com/Capterra/",
    "instagram": "https://www.instagram.com/capterra/",
    "youtube": "https://www.youtube.com/user/CapterraTV",
}


@app.get("/out/external/{destination}")
async def external_redirect(destination: str) -> RedirectResponse:
    """Redirect audited public links to their verified external destinations."""

    target = EXTERNAL_REDIRECTS.get(destination)
    if target is None:
        return RedirectResponse(url="/", status_code=303)
    return RedirectResponse(url=target, status_code=307)


@app.get("/out/vendor-site/{product_id}", response_class=HTMLResponse)
async def vendor_site_boundary(
    request: Request, product_id: str
) -> HTMLResponse:
    """Every product 'Visit Website' CTA lands on this same-origin boundary."""

    product = get_db(request).get_product(product_id)
    if product is None or not product.get("url_slug"):
        return render_public_replay("not-found", status_code=404)
    return render(
        request,
        "vendor_site_boundary.html",
        page_title=f"Visit {product['name']}",
        body_class="vendor-site-boundary-page",
        product=product,
    )


@app.get("/out/{destination}", response_class=HTMLResponse)
async def external_boundary(request: Request, destination: str) -> HTMLResponse:
    value = EXTERNAL_DESTINATIONS.get(destination)
    if value is None:
        return render(
            request,
            "boundary.html",
            page_title="Page not found",
            destination=None,
            status_code=404,
        )
    return render(
        request,
        "boundary.html",
        page_title=str(value["label"]),
        destination=value,
    )


@app.post("/api/auth/send-code", include_in_schema=False)
async def public_registration_send_code(request: Request) -> JSONResponse:
    return await send_registration_code(
        request,
        verification=PUBLIC_REGISTRATION_VERIFICATION,
        store=get_auth(request),
        session_token=request.cookies.get(AUTH_SESSION_COOKIE, ""),
    )


@app.post("/api/auth/verify-code", include_in_schema=False)
async def public_registration_verify_code(request: Request) -> JSONResponse:
    return await verify_registration_code(
        request,
        verification=PUBLIC_REGISTRATION_VERIFICATION,
        store=get_auth(request),
        session_token=request.cookies.get(AUTH_SESSION_COOKIE, ""),
    )


# ---------------------------------------------------------------------------
# One canonical account route family
#
# This site grew two names for the same handlers: `/auth/*` and
# `/local/account/*`.  `/auth/*` is canonical — every template links to it and
# every redirect these handlers emit already targets it (`/auth/logout?state=
# revoked`, `/auth/register/verify?...`).  `/local/account/*` was a second set
# of decorators on the same functions, so two URLs served one page with no
# relationship between them.
#
# Navigating to an alias now lands on the canonical URL with a 308, query string
# intact.  The POST endpoints stay mounted at both names deliberately: the suite
# asserts the PRG contract directly against the alias
# (`test_fullstack_backend.py` posts to `/local/account/password/{forgot,verify,
# reset}` with `follow_redirects=False` and requires 303), and answering 308
# there would replace the 303 those tests check with a redirect *to* the thing
# they check — narrowing live coverage rather than adding to it.  Every one of
# them already ends on a canonical `/auth/*` location, so no alias URL survives
# a completed flow.
# ---------------------------------------------------------------------------

CANONICAL_ACCOUNT_ROUTES: dict[str, str] = {
    "/local/account/register": "/auth/register",
    "/local/account/register/verify": "/auth/register/verify",
    "/local/account/sign-in": "/auth/login",
    "/local/account/sign-out": "/auth/logout",
    "/local/account/password/forgot": "/auth/password/forgot",
    "/local/account/password/verify": "/auth/password/verify",
    "/local/account/password/reset": "/auth/password/reset",
    "/local/account/inbox": "/auth/local-inbox",
}


@app.get("/local/account/{alias_path:path}", include_in_schema=False)
async def canonical_account_redirect(
    request: Request, alias_path: str
) -> Response:
    target = CANONICAL_ACCOUNT_ROUTES.get(
        "/local/account/" + alias_path.rstrip("/")
    )
    if target is None:
        return render_public_replay("not-found", status_code=404)
    query = request.url.query
    return RedirectResponse(f"{target}?{query}" if query else target, 308)


@app.get("/auth/register", response_class=HTMLResponse)
async def local_account_register(
    request: Request,
    state: str = "entry",
    next: str | None = None,
    restart: bool = False,
) -> HTMLResponse:
    return render_r2_contract_state(
        request,
        route_id="auth-register",
        requested_state="entry" if restart else state,
        canonicalize_state=not restart,
        next_path=safe_registration_next(next),
        restart_flow=restart,
    )


@app.post("/auth/register", response_class=HTMLResponse)
@app.post("/local/account/register", response_class=HTMLResponse)
async def local_account_register_submit(request: Request) -> HTMLResponse:
    values = await urlencoded_form(request)
    token, _, created = ensure_auth_session(request)
    next_path = safe_registration_next(values.get("next"))
    if not valid_auth_csrf(values, token):
        response = render_r2_contract_state(
            request,
            route_id="auth-register",
            requested_state="invalid",
            status_code=403,
            form_error="Your request expired. Reload the page and try again.",
        )
        if created:
            set_auth_cookie(response, token)
        return response
    if PUBLIC_REGISTRATION_VERIFICATION is not None:
        auth_store = get_auth(request)
        database = get_db(request)
        try:
            auth_store.validate_registration_details(
                email=values.get("email", ""),
                display_name=values.get("display_name", ""),
                password=values.get("password", ""),
            )
            ticket = consume_registration_ticket(
                verification=PUBLIC_REGISTRATION_VERIFICATION,
                store=auth_store,
                session_token=token,
                email=values.get("email", ""),
            )
            if not ticket:
                return render_r2_contract_state(
                    request,
                    route_id="auth-register",
                    requested_state="invalid",
                    status_code=422,
                    form_error="Verify this email address before creating the account.",
                )
            completed = auth_store.complete_externally_verified_registration(
                token,
                email=values.get("email", ""),
                display_name=values.get("display_name", ""),
                password=values.get("password", ""),
                subject_factory=lambda connection, account: (
                    database.create_account_subject(
                        connection,
                        account_id=str(account["account_id"]),
                        display_name=str(account["display_name"]),
                        email=str(account["email"]),
                    )
                ),
                session_rotation_callback=(
                    database.transfer_anonymous_comparison_in_transaction
                ),
            )
        except VerificationUnavailable:
            return render_r2_contract_state(
                request,
                route_id="auth-register",
                requested_state="invalid",
                status_code=503,
                form_error="Email verification is temporarily unavailable.",
            )
        except AuthError as error:
            return render_r2_contract_state(
                request,
                route_id="auth-register",
                requested_state="invalid",
                status_code=422,
                form_error=str(error),
            )
        new_token = str(completed["session_token"])
        database.record_auth_transition(
            auth_store.session_owner_digest(new_token),
            "registration-verified",
        )
        response = RedirectResponse(next_path, status_code=303)
        set_auth_cookie(response, new_token)
        return response
    try:
        get_auth(request).start_registration(
            token,
            email=values.get("email", ""),
            display_name=values.get("display_name", ""),
            password=values.get("password", ""),
            restart_invalid_flow=values.get("restart") == "1",
        )
    except AuthRateLimited as error:
        return render_r2_contract_state(
            request,
            route_id="auth-register",
            requested_state="rate-limited",
            status_code=429,
            form_error=str(error),
        )
    except AuthConflict as error:
        return render_r2_contract_state(
            request,
            route_id="auth-register",
            requested_state="duplicate",
            status_code=409,
            form_error=str(error),
        )
    except AuthError as error:
        return render_r2_contract_state(
            request,
            route_id="auth-register",
            requested_state="invalid",
            status_code=422,
            form_error=str(error),
        )
    response = RedirectResponse(
        "/auth/register/verify?"
        + urlencode({"next": next_path}),
        status_code=303,
    )
    if created:
        set_auth_cookie(response, token)
    return response


@app.get("/auth/register/verify", response_class=HTMLResponse)
async def local_account_register_verify(
    request: Request, state: str = "challenge", next: str | None = None
) -> HTMLResponse:
    return render_r2_contract_state(
        request,
        route_id="auth-register-verify",
        requested_state=state,
        next_path=safe_registration_next(next),
    )


@app.post("/auth/register/verify", response_class=HTMLResponse)
@app.post("/local/account/register/verify", response_class=HTMLResponse)
async def local_account_register_verify_submit(
    request: Request,
) -> HTMLResponse:
    values = await urlencoded_form(request)
    token, _, _ = ensure_auth_session(request)
    if not valid_auth_csrf(values, token):
        return render_r2_contract_state(
            request,
            route_id="auth-register-verify",
            requested_state="challenge",
            status_code=403,
            form_error="Your request expired. Reload the page and try again.",
        )
    try:
        auth_store = get_auth(request)
        auth_store.verify_registration_code(token, values.get("code", ""))
        database = get_db(request)
        completed = auth_store.complete_registration(
            token,
            subject_factory=lambda connection, account: (
                database.create_account_subject(
                    connection,
                    account_id=str(account["account_id"]),
                    display_name=str(account["display_name"]),
                    email=str(account["email"]),
                )
            ),
            session_rotation_callback=(
                database.transfer_anonymous_comparison_in_transaction
            ),
        )
    except AuthError as error:
        if isinstance(error, AuthLocked):
            state = "locked"
        elif isinstance(error, (AuthValidationError, AuthRejected)):
            state = "invalid"
        else:
            state = "stale"
        return render_r2_contract_state(
            request,
            route_id="auth-register-verify",
            requested_state=state,
            status_code=422,
            form_error=str(error),
        )
    response = RedirectResponse(
        "/auth/register/verify?"
        + urlencode({"next": safe_registration_next(values.get("next"))}),
        status_code=303,
    )
    new_token = str(completed["session_token"])
    get_db(request).record_auth_transition(
        get_auth(request).session_owner_digest(new_token),
        "registration-verified",
    )
    set_auth_cookie(response, new_token)
    return response


@app.get("/auth/login", response_class=HTMLResponse)
async def local_account_sign_in(
    request: Request, state: str = "entry", next: str | None = None
) -> HTMLResponse:
    return render_r2_contract_state(
        request,
        route_id="auth-login",
        requested_state=state,
        next_path=safe_next(next),
    )


@app.post("/auth/login", response_class=HTMLResponse)
@app.post("/local/account/sign-in", response_class=HTMLResponse)
async def local_account_sign_in_submit(request: Request) -> HTMLResponse:
    values = await urlencoded_form(request)
    token, _, _ = ensure_auth_session(request)
    if not valid_auth_csrf(values, token):
        return render_r2_contract_state(
            request,
            route_id="auth-login",
            requested_state="invalid",
            status_code=403,
            form_error="Your request expired. Reload the page and try again.",
        )
    try:
        signed_in = get_auth(request).sign_in(
            token,
            email=values.get("email", ""),
            password=values.get("password", ""),
            session_rotation_callback=(
                get_db(request).transfer_anonymous_comparison_in_transaction
            ),
        )
    except AuthError:
        return render_r2_contract_state(
            request,
            route_id="auth-login",
            requested_state="invalid",
            status_code=401,
            form_error="The email or password is incorrect.",
        )
    response = RedirectResponse(safe_next(values.get("next")), status_code=303)
    set_auth_cookie(response, str(signed_in["session_token"]))
    return response


@app.get("/auth/logout", response_class=HTMLResponse)
async def local_account_sign_out(
    request: Request, state: str = "active"
) -> HTMLResponse:
    return render_r2_contract_state(
        request, route_id="auth-logout", requested_state=state
    )


@app.post("/auth/logout", response_class=HTMLResponse)
@app.post("/local/account/sign-out", response_class=HTMLResponse)
async def local_account_sign_out_submit(request: Request) -> HTMLResponse:
    values = await urlencoded_form(request)
    token = request.cookies.get(AUTH_SESSION_COOKIE, "")
    if not token or not valid_auth_csrf(values, token):
        return render_r2_contract_state(
            request,
            route_id="auth-logout",
            requested_state="active",
            status_code=403,
            form_error="Your request expired. Reload the page and try again.",
        )
    get_auth(request).sign_out(token)
    get_db(request).delete_session_for_cookie(
        request.cookies.get(SESSION_COOKIE)
    )
    response = RedirectResponse("/auth/logout?state=revoked", 303)
    response.delete_cookie(AUTH_SESSION_COOKIE, path="/")
    response.delete_cookie(SESSION_COOKIE, path="/")
    return response


@app.get("/auth/password/forgot", response_class=HTMLResponse)
async def local_password_forgot(
    request: Request, state: str = "entry", restart: bool = False
) -> HTMLResponse:
    return render_r2_contract_state(
        request,
        route_id="auth-password-forgot",
        requested_state="entry" if restart else state,
        canonicalize_state=not restart,
        restart_flow=restart,
    )


@app.post("/auth/password/forgot", response_class=HTMLResponse)
@app.post("/local/account/password/forgot", response_class=HTMLResponse)
async def local_password_forgot_submit(request: Request) -> HTMLResponse:
    values = await urlencoded_form(request)
    token, _, created = ensure_auth_session(request)
    if not valid_auth_csrf(values, token):
        return render_r2_contract_state(
            request,
            route_id="auth-password-forgot",
            requested_state="entry",
            status_code=403,
            form_error="Your request expired. Reload the page and try again.",
        )
    try:
        get_auth(request).start_password_reset(
            token,
            email=values.get("email", ""),
            restart_invalid_flow=values.get("restart") == "1",
        )
    except AuthRateLimited as error:
        return render_r2_contract_state(
            request,
            route_id="auth-password-forgot",
            requested_state="rate-limited",
            status_code=429,
            form_error=str(error),
        )
    except AuthValidationError as error:
        return render_r2_contract_state(
            request,
            route_id="auth-password-forgot",
            requested_state="entry",
            status_code=422,
            form_error=str(error),
        )
    response = RedirectResponse(
        "/auth/password/forgot?state=generic-response", 303
    )
    if created:
        set_auth_cookie(response, token)
    return response


@app.get("/auth/password/verify", response_class=HTMLResponse)
async def local_password_verify(
    request: Request, state: str = "challenge"
) -> HTMLResponse:
    return render_r2_contract_state(
        request, route_id="auth-password-verify", requested_state=state
    )


@app.post("/auth/password/verify", response_class=HTMLResponse)
@app.post("/local/account/password/verify", response_class=HTMLResponse)
async def local_password_verify_submit(request: Request) -> HTMLResponse:
    values = await urlencoded_form(request)
    token, _, _ = ensure_auth_session(request)
    if not valid_auth_csrf(values, token):
        return render_r2_contract_state(
            request,
            route_id="auth-password-verify",
            requested_state="challenge",
            status_code=403,
            form_error="Your request expired. Reload the page and try again.",
        )
    try:
        get_auth(request).verify_password_reset_code(
            token, values.get("code", "")
        )
    except AuthError as error:
        if isinstance(error, AuthLocked):
            state = "locked"
        elif isinstance(error, (AuthValidationError, AuthRejected)):
            state = "invalid"
        else:
            state = "stale"
        return render_r2_contract_state(
            request,
            route_id="auth-password-verify",
            requested_state=state,
            status_code=422,
            form_error=str(error),
        )
    return RedirectResponse("/auth/password/reset?state=verified", 303)


@app.get("/auth/password/reset", response_class=HTMLResponse)
async def local_password_reset(
    request: Request, state: str = "verified"
) -> HTMLResponse:
    return render_r2_contract_state(
        request, route_id="auth-password-reset", requested_state=state
    )


@app.post("/auth/password/reset", response_class=HTMLResponse)
@app.post("/local/account/password/reset", response_class=HTMLResponse)
async def local_password_reset_submit(request: Request) -> HTMLResponse:
    values = await urlencoded_form(request)
    token, _, _ = ensure_auth_session(request)
    if not valid_auth_csrf(values, token):
        return render_r2_contract_state(
            request,
            route_id="auth-password-reset",
            requested_state="verified",
            status_code=403,
            form_error="Your request expired. Reload the page and try again.",
        )
    try:
        new_token = get_auth(request).complete_password_reset(
            token,
            new_password=values.get("password", ""),
            session_rotation_callback=(
                get_db(request).transfer_anonymous_comparison_in_transaction
            ),
        )
    except AuthError as error:
        state = (
            "invalid"
            if isinstance(error, (AuthValidationError, AuthRejected))
            else "verified"
        )
        return render_r2_contract_state(
            request,
            route_id="auth-password-reset",
            requested_state=state,
            status_code=422,
            form_error=str(error),
        )
    response = RedirectResponse(
        "/auth/password/reset?state=complete", 303
    )
    get_db(request).record_auth_transition(
        get_auth(request).session_owner_digest(new_token),
        "password-reset-complete",
    )
    set_auth_cookie(response, new_token)
    return response


@app.get("/auth/local-inbox", response_class=HTMLResponse)
async def local_account_inbox(
    request: Request, state: str | None = None, next: str | None = None
) -> HTMLResponse:
    token, _, _ = ensure_auth_session(request)
    purpose = request.query_params.get("purpose", "registration")
    if purpose not in {"registration", "password-reset"}:
        purpose = "registration"
    mail = get_auth(request).local_mail_for_session(token, purpose=purpose)
    return render_r2_contract_state(
        request,
        route_id="auth-local-inbox",
        requested_state=state or ("local-only" if mail else "empty"),
        local_mail=mail,
        mail_purpose=purpose,
        next_path=safe_registration_next(next),
    )


@app.post("/auth/local-inbox/retry", response_class=HTMLResponse)
@app.post("/local/account/inbox/retry", response_class=HTMLResponse)
async def local_account_inbox_retry(request: Request) -> HTMLResponse:
    values = await urlencoded_form(request)
    token, _, created = ensure_auth_session(request)
    purpose = values.get("purpose", "registration")
    if purpose not in {"registration", "password-reset"}:
        purpose = "registration"
    if not valid_auth_csrf(values, token):
        response = render_r2_contract_state(
            request,
            route_id="auth-local-inbox",
            requested_state="smtp-failed",
            status_code=403,
            mail_purpose=purpose,
            form_error="Your request expired. Reload the page and try again.",
        )
        if created:
            set_auth_cookie(response, token)
        return response
    queued = get_auth(request).retry_failed_mail_for_session(
        token, purpose=purpose
    )
    if not queued:
        response = render_r2_contract_state(
            request,
            route_id="auth-local-inbox",
            requested_state="smtp-failed",
            status_code=409,
            mail_purpose=purpose,
            form_error="This message cannot be retried.",
        )
        if created:
            set_auth_cookie(response, token)
        return response
    response = RedirectResponse(
        "/auth/local-inbox?" + urlencode({"purpose": purpose}),
        status_code=303,
    )
    if created:
        set_auth_cookie(response, token)
    return response


@app.get("/compare", response_class=HTMLResponse)
@app.get("/local/software/comparison", response_class=HTMLResponse)
async def local_software_comparison(
    request: Request, state: str | None = None, restart: bool = False
) -> HTMLResponse:
    existing_token = request.cookies.get(AUTH_SESSION_COOKIE)
    actual = (
        get_db(request).anonymous_comparison_state(
            comparison_owner_id(request, existing_token)
        )
        if existing_token
        and get_auth(request).resolve_session(existing_token) is not None
        else {"product_ids": [], "version": 0}
    )
    return render_r2_contract_state(
        request,
        route_id="local-comparison",
        requested_state=(
            "selection-empty"
            if restart
            else state
            or (
                "comparison-ready"
                if actual["product_ids"]
                else "cleared-aftercare"
                if int(actual["version"]) > 0
                else "selection-empty"
            )
        ),
        canonicalize_state=not restart,
        comparison_state=(
            {"product_ids": [], "version": actual["version"]}
            if restart
            else actual
        ),
    )


@app.post("/compare", response_class=HTMLResponse)
@app.post("/local/software/comparison", response_class=HTMLResponse)
async def local_software_comparison_submit(request: Request) -> HTMLResponse:
    values = await urlencoded_form(request)
    token, _, created = ensure_auth_session(request)
    if not token or not valid_auth_csrf(values, token):
        response = render_r2_contract_state(
            request,
            route_id="local-comparison",
            requested_state="retry-selection",
            status_code=403,
            form_error="Your request expired. Reload the page and try again.",
        )
        if created:
            set_auth_cookie(response, token)
        return response
    selected = [
        product_id
        for key, product_id in (
            ("product_notion", PRODUCT_ID),
            ("product_asana", "asana-101"),
            ("product_monday", "monday-102"),
        )
        if values.get(key) == "on"
    ]
    owner_session_id = comparison_owner_id(request, token)

    def retry_comparison_state() -> dict[str, object]:
        current = get_db(request).anonymous_comparison_state(owner_session_id)
        return {
            "product_ids": selected,
            "version": int(current["version"]),
        }

    try:
        result = get_db(request).update_anonymous_comparison(
            owner_session_id=owner_session_id,
            product_ids=selected,
            expected_version=int(values.get("expected_version", "-1")),
            idempotency_key=values.get("idempotency_key", ""),
        )
    except (ValueError, backend_db.IdempotencyConflict) as error:
        return render_r2_contract_state(
            request,
            route_id="local-comparison",
            requested_state="invalid-selection",
            status_code=422,
            form_error=str(error),
            comparison_state=retry_comparison_state(),
        )
    except backend_db.StaleVersionError as error:
        return render_r2_contract_state(
            request,
            route_id="local-comparison",
            requested_state="retry-selection",
            status_code=409,
            form_error=str(error),
            comparison_state=retry_comparison_state(),
        )
    response = RedirectResponse(
        "/compare?state="
        + (
            "comparison-ready"
            if result["product_ids"]
            else "cleared-aftercare"
        ),
        303,
    )
    if created:
        set_auth_cookie(response, token)
    return response


def render_catalog_favorite_page(
    request: Request,
    product_id: str,
    next_value: str | None,
    *,
    status_code: int = 200,
    form_error: str = "",
) -> HTMLResponse:
    """The save/unsave page for any catalog product other than Notion."""

    product = get_db(request).get_product(product_id)
    if product is None or not product.get("url_slug"):
        return render_public_replay("not-found", status_code=404)
    account = current_account(request)
    favorite_state = (
        get_db(request).favorite_state(int(account["id"]), product_id)
        if account is not None
        else {"product_id": product_id, "present": False, "version": 0}
    )
    next_path = ""
    if next_value:
        resolved = safe_next(next_value)
        next_path = resolved if resolved == next_value else ""
    return render(
        request,
        "product_favorite.html",
        status_code=status_code,
        page_title=f"Save {product['name']}",
        body_class="product-favorite-page",
        product=product,
        favorite_state=favorite_state,
        favorite_display_state=(
            "present" if favorite_state["present"] else "absent"
        ),
        next_path=next_path,
        form_error=form_error,
    )


async def submit_catalog_favorite(
    request: Request, product_id: str
) -> HTMLResponse:
    product = get_db(request).get_product(product_id)
    if product is None or not product.get("url_slug"):
        return render_public_replay("not-found", status_code=404)
    account = current_account(request)
    if account is None:
        return RedirectResponse(
            f"/auth/login?next=/favorites/software/{product_id}",
            status_code=303,
        )
    values = await urlencoded_form(request)
    next_value = values.get("next") or None
    token = request.cookies.get(AUTH_SESSION_COOKIE, "")
    if not token or not valid_auth_csrf(values, token):
        return render_catalog_favorite_page(
            request,
            product_id,
            next_value,
            status_code=403,
            form_error="Your request expired. Reload the page and try again.",
        )
    try:
        get_db(request).update_favorite(
            account_id=int(account["id"]),
            product_id=product_id,
            present=values.get("action") == "add",
            expected_version=int(values.get("expected_version", "-1")),
            idempotency_key=values.get("idempotency_key", ""),
        )
    except (
        ValueError,
        backend_db.IdempotencyConflict,
        backend_db.StaleVersionError,
    ) as error:
        return render_catalog_favorite_page(
            request,
            product_id,
            next_value,
            status_code=409,
            form_error=str(error),
        )
    return RedirectResponse(
        f"/favorites/software/{product_id}"
        + (f"?next={quote(next_value)}" if next_value else ""),
        status_code=303,
    )


@app.get("/favorites/software/{product_id}", response_class=HTMLResponse)
@app.get("/local/software/favorites", response_class=HTMLResponse)
async def local_software_favorites(
    request: Request,
    state: str | None = None,
    product_id: str = PRODUCT_ID,
    next: str | None = None,
) -> HTMLResponse:
    if product_id != PRODUCT_ID:
        return render_catalog_favorite_page(request, product_id, next)
    account = current_account(request)
    actual = (
        get_db(request).favorite_state(int(account["id"]))
        if account is not None
        else {"product_id": PRODUCT_ID, "present": False, "version": 0}
    )
    return render_r2_contract_state(
        request,
        route_id="software-favorites",
        requested_state=state
        or (
            "present"
            if actual["present"]
            else "removed"
            if int(actual["version"]) > 0
            else "absent"
        ),
        favorite_state=actual,
    )


@app.post("/favorites/software/{product_id}", response_class=HTMLResponse)
@app.post("/local/software/favorites", response_class=HTMLResponse)
async def local_software_favorites_submit(
    request: Request, product_id: str = PRODUCT_ID
) -> HTMLResponse:
    if product_id != PRODUCT_ID:
        return await submit_catalog_favorite(request, product_id)
    account = current_account(request)
    if account is None:
        return RedirectResponse(
            f"/auth/login?next=/favorites/software/{PRODUCT_ID}",
            status_code=303,
        )
    values = await urlencoded_form(request)
    token = request.cookies.get(AUTH_SESSION_COOKIE, "")
    if not token or not valid_auth_csrf(values, token):
        return render_r2_contract_state(
            request,
            route_id="software-favorites",
            requested_state="absent",
            status_code=403,
            form_error="Your request expired. Reload the page and try again.",
        )
    desired = values.get("action") == "add"
    try:
        result = get_db(request).update_favorite(
            account_id=int(account["id"]),
            product_id=values.get("product_id", PRODUCT_ID),
            present=desired,
            expected_version=int(values.get("expected_version", "-1")),
            idempotency_key=values.get("idempotency_key", ""),
        )
    except (ValueError, backend_db.IdempotencyConflict) as error:
        actual = get_db(request).favorite_state(int(account["id"]))
        return render_r2_contract_state(
            request,
            route_id="software-favorites",
            requested_state="invalid",
            status_code=422,
            canonicalize_state=False,
            form_error=str(error),
            favorite_state=actual,
        )
    except backend_db.StaleVersionError as error:
        actual = get_db(request).favorite_state(int(account["id"]))
        return render_r2_contract_state(
            request,
            route_id="software-favorites",
            requested_state="invalid",
            status_code=409,
            canonicalize_state=False,
            form_error=str(error),
            favorite_state=actual,
        )
    return RedirectResponse(
        f"/favorites/software/{PRODUCT_ID}?state="
        + ("present" if result["present"] else "removed"),
        303,
    )


@app.post("/fixture/session")
async def fixture_session(request: Request):
    if not fixture_boundary_authorized(request):
        return JSONResponse({"detail": "Not found"}, status_code=404)
    values = await urlencoded_form(request)
    if values.get("csrf") != CSRF_VALUE:
        return render(
            request,
            "auth.html",
            page_title="Sign in to Capterra",
            next_path=safe_next(values.get("next")),
            csrf=CSRF_VALUE,
            auth_error="Your sign-in request expired. Please try again.",
            status_code=403,
        )
    account_slug = values.get("account", PRIMARY_ACCOUNT_SLUG)
    if account_slug not in KNOWN_ACCOUNT_SLUGS:
        account_slug = PRIMARY_ACCOUNT_SLUG
    database = get_db(request)
    session_id = database.create_session(account_slug)
    response = RedirectResponse(safe_next(values.get("next")), status_code=303)
    response.set_cookie(
        SESSION_COOKIE,
        database.cookie_value(session_id),
        httponly=True,
        samesite="lax",
        secure=False,
        path="/",
        max_age=3600,
    )
    return response


@app.post("/fixture/sign-out")
async def fixture_sign_out(request: Request) -> Response:
    if not fixture_boundary_authorized(request):
        return JSONResponse({"detail": "Not found"}, status_code=404)
    get_db(request).delete_session_for_cookie(
        request.cookies.get(SESSION_COOKIE)
    )
    response = RedirectResponse("/", status_code=303)
    response.delete_cookie(SESSION_COOKIE, path="/")
    return response


@app.get("/reviews/notion/write", response_class=HTMLResponse)
async def review_form(request: Request, state: str = "ready") -> HTMLResponse:
    account = current_account(request)
    if account is None:
        return render(
            request,
            "auth.html",
            page_title="Sign in to Capterra",
            next_path="/reviews/notion/write",
            csrf=CSRF_VALUE,
            unauthorized=True,
            status_code=401,
        )
    draft = get_db(request).get_or_create_open_draft(account["id"])
    normalized = (
        state
        if state in {"ready", "fixture-error", "submitting", "no-submission"}
        else "ready"
    )
    return render(
        request,
        "review_form.html",
        page_title="Review Notion",
        state=normalized,
        form_action=review_form_boundary(request)[0],
        csrf=review_form_boundary(request)[1],
        form_rating="",
        form_text="",
        focus_rating=False,
        draft_id=draft["id"],
        draft_version=draft["version"],
        errors=[],
    )


def _render_form_error(
    request: Request,
    *,
    status_code: int,
    errors: list[str],
    rating: str,
    text: str,
    draft,
) -> HTMLResponse:
    focus_rating = any(
        error == "Choose a whole-star rating between 1 and 5."
        for error in errors
    )
    return render(
        request,
        "review_form.html",
        page_title="Review Notion",
        state="validation",
        form_action=review_form_boundary(request)[0],
        csrf=review_form_boundary(request)[1],
        form_rating=rating,
        form_text=text,
        focus_rating=focus_rating,
        draft_id=draft["id"] if draft is not None else "",
        draft_version=draft["version"] if draft is not None else 1,
        errors=errors,
        status_code=status_code,
    )


@app.post("/local/reviews/notion")
@app.post("/fixture/reviews/notion", include_in_schema=False)
async def submit_fixture_review(request: Request):
    fixture_request = request.url.path.startswith("/fixture/")
    if fixture_request and not fixture_boundary_authorized(request):
        return JSONResponse({"detail": "Not found"}, status_code=404)
    auth_token = request.cookies.get(AUTH_SESSION_COOKIE, "")
    auth_session = get_auth(request).resolve_session(auth_token)
    if fixture_request:
        account = current_account(request)
    else:
        account = (
            current_account(request)
            if auth_session and auth_session.get("authenticated")
            else None
        )
    if account is None:
        return RedirectResponse(
            "/auth/login?next=/reviews/notion/write", status_code=303
        )
    database = get_db(request)
    values = await urlencoded_form(request)
    rating = values.get("rating", "")
    text = values.get("review_text", "")

    csrf_valid = (
        secrets.compare_digest(values.get("csrf", ""), CSRF_VALUE)
        if fixture_request
        else valid_auth_csrf(values, auth_token)
    )
    if not csrf_valid:
        draft = database.get_or_create_open_draft(account["id"])
        return _render_form_error(
            request,
            status_code=422,
            errors=["The local form expired. Reload and try again."],
            rating=rating,
            text=text,
            draft=draft,
        )

    # Draft resolution: an explicit draft_id must exist and belong to the
    # session account; otherwise the account's open draft is used (created
    # on first POST when the form was never opened).
    draft_id = values.get("draft_id", "").strip()
    if draft_id:
        draft = database.get_draft(draft_id)
        if draft is None:
            return JSONResponse(
                {"ok": False, "error": "unknown draft"}, status_code=404
            )
        if draft["account_id"] != account["id"]:
            return JSONResponse(
                {"ok": False, "error": "draft belongs to another account"},
                status_code=403,
            )
    else:
        draft = database.get_or_create_open_draft(account["id"])

    # Duplicate submission of the same draft is idempotent: reuse the row.
    existing = database.submission_for_draft(draft["id"])
    if existing is not None:
        return RedirectResponse(
            f"/reviews/fixture-receipt/{RECEIPT_ID}", status_code=303
        )

    # Optimistic concurrency: a stale declared version conflicts.
    declared_version = values.get("draft_version", "").strip()
    if declared_version:
        try:
            declared = int(declared_version)
        except ValueError:
            declared = -1
        if declared != int(draft["version"]):
            return _render_form_error(
                request,
                status_code=409,
                errors=[
                    "This draft changed in another tab (version conflict). "
                    "Reload the form to continue from the latest draft."
                ],
                rating=rating,
                text=text,
                draft=draft,
            )

    # Generic finite validation: any whole-star rating between 1 and 5 and
    # any text satisfying normalize_review_text is accepted. Benchmark seed
    # values are ordinary valid inputs, never a special case.
    errors: list[str] = []
    try:
        rating_value: int | None = int(rating.strip())
    except (AttributeError, ValueError):
        rating_value = None
    if rating_value is None or not 1 <= rating_value <= 5:
        errors.append("Choose a whole-star rating between 1 and 5.")
    normalized_text, text_errors = normalize_review_text(text)
    errors.extend(text_errors)

    # Every authorized, non-stale attempt is recorded as a draft revision
    # and bumps the draft version.
    database.record_revision(draft["id"], rating, text)

    if errors:
        refreshed = database.get_draft(draft["id"])
        return _render_form_error(
            request,
            status_code=422,
            errors=errors,
            rating=rating,
            text=text,
            draft=refreshed,
        )

    # One review per (reviewer, product): resubmitting the SAME finalized
    # draft stays idempotent (short-circuited above); an attempt to write
    # a second DISTINCT review for the same product is rejected with an
    # on-page conflict, mirroring the source site's one-review-per-product
    # rule. The DB backs this with UNIQUE(account_id, product_id)
    # (migration 4); DuplicateReviewError below is the constraint backstop.
    conflict_errors = [
        "You have already reviewed this product. Capterra keeps "
        "one review per reviewer per product; your existing "
        "review is unchanged."
    ]
    if database.submission_for_pair(
        account["id"], draft["product_id"]
    ) is not None:
        return _render_form_error(
            request,
            status_code=409,
            errors=conflict_errors,
            rating=rating,
            text=text,
            draft=database.get_draft(draft["id"]),
        )

    draft = database.get_draft(draft["id"])
    try:
        database.create_submission(draft, rating_value, normalized_text)
    except backend_db.DuplicateReviewError:
        # Backstop: the UNIQUE (account, product) constraint fired (e.g. a
        # concurrent submit landed first). Same on-page conflict message.
        return _render_form_error(
            request,
            status_code=409,
            errors=conflict_errors,
            rating=rating,
            text=text,
            draft=database.get_draft(draft["id"]),
        )
    return RedirectResponse(
        f"/reviews/fixture-receipt/{RECEIPT_ID}", status_code=303
    )


@app.get(
    "/reviews/fixture-receipt/{receipt_code}", response_class=HTMLResponse
)
async def fixture_receipt(
    request: Request, receipt_code: str
) -> HTMLResponse:
    account = current_account(request)
    if account is None:
        return RedirectResponse(
            "/auth/login?next=/reviews/notion/write", status_code=303
        )
    database = get_db(request)
    if receipt_code == RECEIPT_ID:
        own_submission = database.submission_for_pair(
            account["id"], PRODUCT_ID
        )
        if own_submission is None:
            return RedirectResponse(
                "/reviews/notion/write?state=no-submission", status_code=303
            )
        return RedirectResponse(
            "/reviews/fixture-receipt/"
            f"{own_submission['receipt_code']}",
            status_code=303,
        )
    submission = database.submission_for_receipt(
        account["id"], PRODUCT_ID, receipt_code
    )
    if submission is None:
        return render(
            request,
            "receipt_unavailable.html",
            page_title="Receipt unavailable",
            status_code=404,
        )
    return render(
        request,
        "receipt.html",
        page_title="Review submitted",
        submission_id=submission["id"],
        receipt_id=submission["receipt_code"],
        receipt_rating=int(submission["rating"]),
        receipt_text=submission["review_text"],
    )


# -- catalog-wide review writing ------------------------------------------
# Registered after the literal notion routes above; "notion" as a slug or
# "186596" as a product id therefore never reaches these handlers.


def _render_product_form_error(
    request: Request,
    *,
    product: Mapping[str, object],
    status_code: int,
    errors: list[str],
    rating: str,
    text: str,
    draft,
) -> HTMLResponse:
    token = request.cookies.get(AUTH_SESSION_COOKIE, "")
    return render(
        request,
        "product_review_form.html",
        status_code=status_code,
        page_title=f"Review {product['name']}",
        body_class="review-form-page",
        product=product,
        state="ready",
        form_action=f"/local/reviews/{product['id']}",
        csrf=auth_csrf(token) if token else "",
        form_rating=rating,
        form_text=text,
        focus_rating=any(
            error == "Choose a whole-star rating between 1 and 5."
            for error in errors
        ),
        draft_id=draft["id"] if draft is not None else "",
        draft_version=draft["version"] if draft is not None else 1,
        errors=errors,
    )


@app.get("/reviews/{product_slug}/write", response_class=HTMLResponse)
async def product_review_form(
    request: Request, product_slug: str, state: str = "ready"
) -> Response:
    product = get_db(request).get_product_by_slug(product_slug)
    if product is None or not product.get("url_slug"):
        return render_public_replay("not-found", status_code=404)
    account = current_account(request)
    if account is None:
        return render(
            request,
            "auth.html",
            page_title="Sign in to Capterra",
            next_path=f"/reviews/{product_slug}/write",
            csrf=CSRF_VALUE,
            unauthorized=True,
            status_code=401,
        )
    draft = get_db(request).get_or_create_open_draft(
        account["id"], str(product["id"])
    )
    token = request.cookies.get(AUTH_SESSION_COOKIE, "")
    return render(
        request,
        "product_review_form.html",
        page_title=f"Review {product['name']}",
        body_class="review-form-page",
        product=product,
        state=state if state in {"ready", "no-submission"} else "ready",
        form_action=f"/local/reviews/{product['id']}",
        csrf=auth_csrf(token) if token else "",
        form_rating="",
        form_text="",
        focus_rating=False,
        draft_id=draft["id"],
        draft_version=draft["version"],
        errors=[],
    )


@app.post("/local/reviews/{product_id}")
async def submit_product_review(request: Request, product_id: str) -> Response:
    product = get_db(request).get_product(product_id)
    if product is None or not product.get("url_slug"):
        return JSONResponse({"detail": "Not Found"}, status_code=404)
    write_path = f"/reviews/{product['slug']}/write"
    auth_token = request.cookies.get(AUTH_SESSION_COOKIE, "")
    auth_session = get_auth(request).resolve_session(auth_token)
    account = (
        current_account(request)
        if auth_session and auth_session.get("authenticated")
        else None
    )
    if account is None:
        return RedirectResponse(
            f"/auth/login?next={write_path}", status_code=303
        )
    database = get_db(request)
    values = await urlencoded_form(request)
    rating = values.get("rating", "")
    text = values.get("review_text", "")

    if not valid_auth_csrf(values, auth_token):
        draft = database.get_or_create_open_draft(account["id"], product_id)
        return _render_product_form_error(
            request,
            product=product,
            status_code=422,
            errors=["The local form expired. Reload and try again."],
            rating=rating,
            text=text,
            draft=draft,
        )

    draft_id = values.get("draft_id", "").strip()
    if draft_id:
        draft = database.get_draft(draft_id)
        if draft is None:
            return JSONResponse(
                {"ok": False, "error": "unknown draft"}, status_code=404
            )
        if draft["account_id"] != account["id"]:
            return JSONResponse(
                {"ok": False, "error": "draft belongs to another account"},
                status_code=403,
            )
        if draft["product_id"] != product_id:
            return JSONResponse(
                {"ok": False, "error": "draft belongs to another product"},
                status_code=409,
            )
    else:
        draft = database.get_or_create_open_draft(account["id"], product_id)

    existing = database.submission_for_draft(draft["id"])
    if existing is not None:
        return RedirectResponse(
            f"/reviews/{product['slug']}/receipt/{existing['receipt_code']}",
            status_code=303,
        )

    declared_version = values.get("draft_version", "").strip()
    if declared_version:
        try:
            declared = int(declared_version)
        except ValueError:
            declared = -1
        if declared != int(draft["version"]):
            return _render_product_form_error(
                request,
                product=product,
                status_code=409,
                errors=[
                    "This draft changed in another tab (version conflict). "
                    "Reload the form to continue from the latest draft."
                ],
                rating=rating,
                text=text,
                draft=draft,
            )

    errors: list[str] = []
    try:
        rating_value: int | None = int(rating.strip())
    except (AttributeError, ValueError):
        rating_value = None
    if rating_value is None or not 1 <= rating_value <= 5:
        errors.append("Choose a whole-star rating between 1 and 5.")
    normalized_text, text_errors = normalize_review_text(text)
    errors.extend(text_errors)

    database.record_revision(draft["id"], rating, text)

    if errors:
        return _render_product_form_error(
            request,
            product=product,
            status_code=422,
            errors=errors,
            rating=rating,
            text=text,
            draft=database.get_draft(draft["id"]),
        )

    conflict_errors = [
        "You have already reviewed this product. Capterra keeps "
        "one review per reviewer per product; your existing "
        "review is unchanged."
    ]
    if database.submission_for_pair(account["id"], product_id) is not None:
        return _render_product_form_error(
            request,
            product=product,
            status_code=409,
            errors=conflict_errors,
            rating=rating,
            text=text,
            draft=database.get_draft(draft["id"]),
        )

    draft = database.get_draft(draft["id"])
    try:
        submission = database.create_submission(
            draft, rating_value, normalized_text
        )
    except backend_db.DuplicateReviewError:
        return _render_product_form_error(
            request,
            product=product,
            status_code=409,
            errors=conflict_errors,
            rating=rating,
            text=text,
            draft=database.get_draft(draft["id"]),
        )
    return RedirectResponse(
        f"/reviews/{product['slug']}/receipt/{submission['receipt_code']}",
        status_code=303,
    )


@app.get(
    "/reviews/{product_slug}/receipt/{receipt_code}",
    response_class=HTMLResponse,
)
async def product_review_receipt(
    request: Request, product_slug: str, receipt_code: str
) -> Response:
    product = get_db(request).get_product_by_slug(product_slug)
    if product is None or not product.get("url_slug"):
        return render_public_replay("not-found", status_code=404)
    account = current_account(request)
    write_path = f"/reviews/{product_slug}/write"
    if account is None:
        return RedirectResponse(
            f"/auth/login?next={write_path}", status_code=303
        )
    submission = get_db(request).submission_for_receipt(
        account["id"], str(product["id"]), receipt_code
    )
    if submission is None:
        return render(
            request,
            "receipt_unavailable.html",
            page_title="Receipt unavailable",
            status_code=404,
        )
    return render(
        request,
        "receipt.html",
        page_title="Review submitted",
        product_name=product["name"],
        product_id=product["id"],
        write_path=write_path,
        reviews_path=f"/p/{product['id']}/{product['url_slug']}/reviews/",
        submission_id=submission["id"],
        receipt_id=submission["receipt_code"],
        receipt_rating=int(submission["rating"]),
        receipt_text=submission["review_text"],
    )


def main() -> None:
    inherited_fd = (
        os.environ.get("WEBSITEBENCH_LISTEN_FD")
        or os.environ.get("CLAWBENCH_LISTEN_FD")
    )
    if inherited_fd is not None:
        uvicorn.run(app, fd=int(inherited_fd), access_log=True)
        return
    port = int(os.environ.get("PORT", "8421"))
    uvicorn.run(app, host="127.0.0.1", port=port, access_log=True)


if __name__ == "__main__":
    main()