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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
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
"""Change.org offline clone — persistent backend (stage: backend, R3).

Server-authoritative FastAPI app over the sqlite3/WAL persistence layer in
``clone/backend/db.py``: durable accounts, persisted sessions, petitions
(open/victory/closed with a derived signature-goal ladder), one-per-account
signatures, sign-before-comment comments, and creator-bound supporter
updates.  The database lives under CLAWBENCH_DATA_DIR (default
``materials/change/data`` — outside clone/).  No production GraphQL proxy
ships; nothing here reaches production Change.org.
"""

from __future__ import annotations

import asyncio
import base64
import hashlib
import hmac
import importlib.util
import os
import re
import sqlite3
import sys
import unicodedata
import json
import time
import urllib.error
import urllib.parse
import urllib.request
from contextlib import closing
from decimal import Decimal, InvalidOperation, ROUND_HALF_UP
from pathlib import Path
from urllib.parse import parse_qs, quote

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

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

from websitebench.local_clone_auth import (  # noqa: E402
    AuthConflict,
    AuthError,
    AuthExpired,
    AuthLocked,
    AuthRateLimited,
    AuthValidationError,
    LocalAuthStore,
    RESET_PUBLIC_MESSAGE,
)
from websitebench.public_clone_auth import (  # noqa: E402
    VerificationUnavailable,
    load_public_clone_registration_verification,
)
from websitebench.public_clone_auth.fastapi import (  # noqa: E402
    consume_registration_ticket,
    registration_script_response,
    send_registration_code,
    verify_registration_code,
)
from websitebench.site_backend import (  # noqa: E402
    PaymentConflict,
    PaymentError,
    PaymentRejected,
    SiteBackend,
)
from websitebench.site_backend.transport import (  # noqa: E402
    TransportDeliveryFailure,
    TransportError,
    resolve_transport,
)
from websitebench_site_backend_migration import (  # noqa: E402
    migrate_legacy_namespace_copy,
)

_DB_MODULE_NAME = "change_backend_db"
if _DB_MODULE_NAME in sys.modules:
    db = sys.modules[_DB_MODULE_NAME]
else:
    _db_spec = importlib.util.spec_from_file_location(
        _DB_MODULE_NAME, ROOT / "backend" / "db.py"
    )
    assert _db_spec is not None and _db_spec.loader is not None
    db = importlib.util.module_from_spec(_db_spec)
    sys.modules[_DB_MODULE_NAME] = db
    _db_spec.loader.exec_module(db)

from backend.repository import (  # noqa: E402
    RepositoryError,
    build_repository,
)

SITE_ID = "change"
PUBLIC_REGISTRATION_VERIFICATION = load_public_clone_registration_verification()
VERSION = "change-fullstack-2026-07-29.1"
FIXTURE_ID = "change-v3-fullstack-candidate"
STAGE = "fullstack-candidate"
FROZEN_CLOCK = "2026-07-25T12:00:00-04:00"
FROZEN_DATE = "2026-07-25"

SESSION_COOKIE = "__Host-websitebench-change-session"
SHARE_ATTRIBUTION_COOKIE = "websitebench_change_share"
CSRF_VALUE = "change-r2-fixture-csrf"
OWNER_NAME = "Taylor Brooks"
OWNER_EMAIL = "taylor.brooks@example.test"
OWNER_PASSWORD = "ChangePass123!"
FIXTURE_PASSWORD = "ChangePass456!"

# Benchmark-owned fixture secret.  Intentionally public fixture value
# (never a production credential); env var allows harness overrides.
ADMIN_TOKEN = os.environ.get(
    "WEBSITEBENCH_ADMIN_TOKEN", "change-admin-dev-token"
)
ADMIN_TOKEN_HEADER = "X-WebsiteBench-Admin-Token"

DRAFT_VERSION = "1"
TITLE_MIN = 1
TITLE_MAX = 150
TARGET_MIN = 1
TARGET_MAX = 120
BODY_MIN = 1
BODY_MAX = 5000
UPDATE_MIN = 1
UPDATE_MAX = 2000
IDEMPOTENCY_KEY_MAX = 120
DISPLAY_NAME_MAX = 100
REASON_MAX = 1000
COMMENT_MAX = 1000

HELPER_DISCLOSURE = "Create a strong first draft in a few simple steps"
LOCAL_ONLY_LABEL = "LOCAL-ONLY"
PUBLISH_IDEMPOTENCY_KEY = "publish-form-v1"

# Non-secret, process-local presentation state for the local auth inbox. Keys
# are one-way session digests; values never contain addresses, codes, tokens,
# provider errors, or message bodies.
AUTH_UI_STATES: dict[tuple[str, str], str] = {}

TOPIC_MIN = 1
TOPIC_MAX = 120
LOCATION_MIN = 1
LOCATION_MAX = 120

FROZEN_SEARCH_QUERY = "bus routes"
FROZEN_SEARCH_COUNT = "1,814"
FROZEN_SEARCH_RESULTS = [
    {
        "title": "SAVE THE 149 BUS ROUTE!!!",
        "excerpt": "Protect a vital public-transport connection for residents who rely on this route every day.",
        "signatures": "388",
        "location": "London, United Kingdom",
        "started": "Started July 25, 2026",
        "image": "/static/assets/source-current/2026-07-25/search-transit/"
        "result-qFXdkQNhseeEuJC-fullsize.jpg",
    },
    {
        "title": "Bus route between Fenham, Gosforth and Jesmond",
        "excerpt": "A safer, more connected transport option for families, students, and local businesses.",
        "signatures": "376",
        "location": "Newcastle upon Tyne, United Kingdom",
        "started": "Started April 21, 2026",
        "image": "/static/assets/source-current/2026-07-25/search-transit/"
        "result-wfBHOypPUprXDGi-fullsize.jpg",
    },
    {
        "title": "Save the 96, 428, and 492 bus routes 💔",
        "excerpt": "Keep essential routes serving work, school, healthcare, and community connections.",
        "signatures": "1,606",
        "location": "United Kingdom",
        "started": "Started June 9, 2026",
        "image": "/static/assets/source-current/2026-07-25/search-transit/"
        "result-XoOXMPbsQXOyfRE-fullsize.jpg",
    },
    {
        "title": "Reinstate Original Bus Routes for Yanchep/Two Rocks, Australia",
        "excerpt": "Restore direct services and reduce long school journeys for the local community.",
        "signatures": "1,586",
        "location": "Yanchep, Australia",
        "started": "Started July 20, 2024",
        "image": "/static/assets/source-current/2026-07-25/search-transit/"
        "result-qFXdkQNhseeEuJC-fullsize.jpg",
    },
    {
        "title": "Save rural bus routes in Dover district",
        "excerpt": "Protect rural links used by young people, older residents, and village communities.",
        "signatures": "1,502",
        "location": "United Kingdom",
        "started": "Started August 1, 2022",
        "image": "/static/assets/source-current/2026-07-25/search-transit/"
        "result-wfBHOypPUprXDGi-fullsize.jpg",
    },
    {
        "title": "Stop the removal of Dublin City Centre bus route no. 26",
        "excerpt": "Keep an accessible city connection for commuters, students, and older residents.",
        "signatures": "1,058",
        "location": "Dublin, Ireland",
        "started": "Started October 3, 2025",
        "image": "/static/assets/source-current/2026-07-25/search-transit/"
        "result-XoOXMPbsQXOyfRE-fullsize.jpg",
    },
    {
        "title": "Restore the Old X6 Bus Route",
        "excerpt": "Bring back a route used for school, sport, work, and time with family and friends.",
        "signatures": "994",
        "location": "United Kingdom",
        "started": "Started March 4, 2025",
        "image": "/static/assets/source-current/2026-07-25/search-transit/"
        "result-qFXdkQNhseeEuJC-fullsize.jpg",
    },
    {
        "title": "Save the 85/84 School bus route from Chipping Sodbury to Wotton-under-Edge",
        "excerpt": "Help schoolchildren retain a practical route to their classes and back home.",
        "signatures": "772",
        "location": "Wotton-under-Edge, United Kingdom",
        "started": "Started January 26, 2023",
        "image": "/static/assets/source-current/2026-07-25/search-transit/"
        "result-wfBHOypPUprXDGi-fullsize.jpg",
    },
]


# The topic facets offered beside search results. search.html carried this list
# inline and rendered all thirty for every query, so most of them led to an
# empty result set -- roughly 800 of the dead ends a crawl finds on this site
# are these chips. available_search_topics() below keeps only the ones that
# actually return something for the query in hand.
SEARCH_TOPIC_FACETS = [
    "Government and Politics", "Environmental Issues", "Climate Change",
    "Global Warming", "Animal Rights and Conservation", "Health and Well-Being",
    "Public Safety", "Business and Economy", "Education",
    "Wildlife Conservation", "Local Government", "Wildlife Biodiversity",
    "National Government", "Air Pollution", "Deforestation",
    "Global Social Justice Issues", "Water Pollution", "Plant Biodiversity",
    "Child and Family Well-Being", "Animal Welfare", "Public Health",
    "Technology", "Waste Management", "Ethnic and Racial Minorities",
    "Education Reform", "Student Issues", "Economic Justice",
    "Criminal Justice", "Corruption", "Animal Rights",
]


async def available_search_topics(
    query: str,
    *,
    location: str,
    organization: str,
    filter_status: str,
    page_already_has_results: bool,
) -> list[str]:
    """Return only the topic facets that lead to a non-empty page.

    A chip that always lands on "No search results" is a control that goes
    nowhere, which is the thing AS-1 is supposed to catch. When the page
    carries frozen source results the facet cannot empty it, so every facet is
    offered; otherwise each one is checked against the local index.
    """

    if page_already_has_results:
        return list(SEARCH_TOPIC_FACETS)

    available: list[str] = []
    for facet in SEARCH_TOPIC_FACETS:
        try:
            probe = await repository.execute(
                "search.petitions",
                {
                    "query": query,
                    "topic": facet,
                    "location": location,
                    "organization": organization,
                    "status": filter_status,
                    "limit": 1,
                },
            )
        except Exception:  # a probe must never break the page it decorates
            continue
        if probe["items"]:
            available.append(facet)
    return available



def impact_tail_petitions() -> list[dict[str, str]]:
    """Petitions for the "these need your help" tiles on /impact.

    The tiles named four petitions only change.org carries and linked each
    through a search; three of those searches returned nothing. These are the
    petitions this edition holds that are still open -- a victory or a closed
    petition does not need help winning -- linked straight to the petition.
    """

    open_slugs = {
        str(row["slug"])
        for row in db.SEED_PETITIONS
        if row["status"] == "open" and int(row["created_seq"]) >= 0
    }
    return [
        card
        for card in HOME_LOCAL_CARDS
        if card["href"].removeprefix("/p/").split("?", 1)[0] in open_slugs
    ][:4]


def curated_topic_links() -> list[dict[str, str]]:
    """Resolve each curated topic name to the topic page that carries it.

    These were rendered as /search?q=<name>. Twenty-five of the twenty-seven
    returned no results, because the curated names are topic labels and the
    search index has no topic to match them against. A name that matches a
    directory topic now links to that topic page; one that does not is dropped
    rather than shipped as a link that goes nowhere.
    """

    by_title = {
        str(topic["title"]).casefold(): str(topic["slug"])
        for topic in SOURCE_TOPIC_PAGES
    }
    links: list[dict[str, str]] = []
    for name in CURATED_TOPICS:
        slug = by_title.get(name.casefold())
        if slug is not None:
            links.append({"title": name, "href": f"/topic/{slug}"})
    return links


def _victory_petition_path() -> str:
    """Path of the one petition this edition seeds with a victory status.

    Resolved from seed data so no seed slug is written into runtime code
    (tests/test_backend.py::test_no_petition_id_branching_in_runtime_code).
    """

    victories = [row for row in db.SEED_PETITIONS if row["status"] == "victory"]
    if len(victories) != 1:
        raise RuntimeError(
            f"expected exactly one seeded victory petition, found {len(victories)}"
        )
    return f"/p/{victories[0]['slug']}"


TRENDING_STORIES = [
    {
        "badge": "Trending!",
        "signatures": "770,047 signatures",
        "title": "Justice for the children poisoned by one of America's "
        "worst nuclear disasters",
        "href": "/impact",
        "image": "/static/assets/source-current/2026-08-02-rebuild-01/"
        "public/home/melissa-bumstead-toxic.webp",
    },
    {
        "badge": "Trending!",
        "signatures": "100,358 signatures",
        "title": "One woman takes on retail giants to save children's lives",
        "href": "/impact",
        "image": "/static/assets/source-current/2026-08-02-rebuild-01/"
        "public/home/ashley-haugen-water-beads.webp",
    },
    {
        "badge": "Victory!",
        "signatures": "97,274 signatures",
        "title": "A child's tragedy sparks a state's crusade against bullying",
        "href": "/impact",
        "image": "/static/assets/source-current/2026-08-02-rebuild-01/"
        "public/home/becky-claypool-bullying.webp",
    },
    {
        "badge": "Victory!",
        "signatures": "46,994 signatures",
        "title": "Her daughter was killed by a driver—so she fought to "
        "change the law",
        "href": "/impact",
        "image": "/static/assets/source-current/2026-08-02-rebuild-01/"
        "public/home/dangerous-cars.webp",
    },
    {
        "badge": "Victory!",
        "signatures": "610,811 signatures",
        "title": "How a community group freed an indigenous teen facing "
        "life in prison",
        # This story is the petition this edition seeds as a victory; resolve it
        # from seed data rather than naming the slug here.
        "href": _victory_petition_path(),
        "image": "/static/assets/source-current/2026-08-02-rebuild-01/"
        "public/home/release-virgilio.webp",
    },
]

HOME_CHIPS = [
    {
        "label": "Ethnic and Racial Minorities",
        "href": "/topic/ethnic-and-racial-minorities-en-ca?source_location=homepage",
    },
    {
        "label": "Health",
        "href": "/topic/health?source_location=homepage",
    },
    {
        "label": "Animals",
        "href": "/topic/animals-14?source_location=homepage",
    },
    {
        "label": "Government and Politics",
        "href": "/topic/government-and-politics-en-ca?source_location=homepage",
    },
    {
        "label": "Human Rights",
        "href": "/topic/human-rights-12?source_location=homepage",
    },
    {
        "label": "Environment",
        "href": "/topic/environment?source_location=homepage",
    },
]

# Cards whose photos were not frozen in the capture use the captured
# default petition tile instead; no photos are fabricated.
DEFAULT_PETITION_TILE = (
    "/static/assets/source-current/2026-07-25/search-transit/"
    "default-petition-darker.gif"
)

PETITION_HERO_IMAGES = (
    DEFAULT_PETITION_TILE,
    (
        "/static/assets/source-current/2026-07-25/home/"
        "petition-photo-efGHEMqcbpudkDi-1600x900.jpg"
    ),
    (
        "/static/assets/source-current/2026-07-25/home/"
        "petition-photo-iytDwgQgaIWkewT-1600x900.jpg"
    ),
    (
        "/static/assets/source-current/2026-07-25/home/"
        "petition-photo-VKpAaJTNAsulQEV-1600x900.jpg"
    ),
    (
        "/static/assets/source-current/2026-07-25/home/hero-release-virgilio.jpg"
    ),
    (
        "/static/assets/source-current/2026-07-25/home/"
        "petition-photo-WFABodBuPNKpuRl-1600x900.jpg"
    ),
    (
        "/static/assets/source-current/2026-08-02-rebuild-01/"
        "public/search/VpavwMMkFVQyMtV-fullsize.jpg"
    ),
)

CURRENT_CLOSED_PETITION = {
    "slug": "urge-belift-and-hybe-to-bring-back-heeseung-to-enhypen",
    "title": "Urge Belift and Hybe to bring back Heeseung to Enhypen",
    "target": "Belift Lab and HYBE",
    "body": (
        "Supporters are asking Belift Lab and HYBE to bring Heeseung back "
        "to Enhypen."
    ),
    "owner": "current-source-checkpoint-owner",
    "owner_name": "Controlled petition starter",
    "status": "closed",
    "signatures": 132_903,
    "next_goal": 150_000,
    "row_version": 1,
    "created_seq": 4,
    "comments": [],
    "updates": [],
    "hero_image": (
        "/static/assets/source-current/2026-08-02-rebuild-03/current-direct/"
        "public-petition-detail-closed-hero.webp"
    ),
    "closed_share_count": "119,282",
    "closed_comment_count": "4,421",
    "closed_topic": "Entertainment & Media",
}

# Local petition tiles. The capture's own tiles named seven petitions from the
# source site that this edition does not carry, so every tile 404'd -- on the
# homepage and, through topic_page below, on every topic page. The tiles are now
# derived from the petitions this edition actually seeds, so they cannot drift
# out of sync with the seed set again. Slugs deliberately are not written out
# here: seed slugs belong to seed data, never to runtime branch logic
# (tests/test_backend.py::test_no_petition_id_branching_in_runtime_code).
#
# Photos are the captured local-petition tiles, assigned by position exactly as
# PETITION_HERO_IMAGES already assigns captured hero photos to petitions. They
# are generic petition imagery here, not a claim about any one petition.
LOCAL_PETITION_TILES = (
    "/static/assets/source-current/2026-08-02-rebuild-01/public/home/"
    "local-petitions/JagBEigmFPtNJgk.webp",
    "/static/assets/source-current/2026-08-02-rebuild-01/public/home/"
    "local-petitions/UOAAWGpuJrmNCdR.webp",
    "/static/assets/source-current/2026-08-02-rebuild-01/public/home/"
    "local-petitions/lwUhBOFpePChHHd.webp",
    "/static/assets/source-current/2026-08-02-rebuild-01/public/home/"
    "local-petitions/wVWpXgTclrCMaUM.webp",
    "/static/assets/source-current/2026-08-02-rebuild-01/public/home/"
    "local-petitions/yyKSLrseNBfDAkP.webp",
    "/static/assets/source-current/2026-08-02-rebuild-01/public/home/"
    "local-petitions/BMqKCmwHKPEdQxp.webp",
    "/static/assets/source-current/2026-08-02-rebuild-01/public/home/"
    "local-petitions/ctHJriSkmjIwUqP.webp",
)

LOCAL_PETITION_TILE_BACKGROUNDS = (
    "#73675e",
    "#6f735d",
    "#5d6f73",
    "#737264",
    "#5e7366",
    "#6b735e",
    "#545e73",
)


def _build_home_local_cards() -> list[dict[str, str]]:
    """Render one tile per seeded petition, most-signed first.

    ``created_seq`` below zero marks the controlled test fixture, which is not
    homepage material.
    """

    petitions = sorted(
        (row for row in db.SEED_PETITIONS if int(row["created_seq"]) >= 0),
        key=lambda row: -int(row["baseline_signatures"]),
    )
    cards: list[dict[str, str]] = []
    for index, petition in enumerate(petitions):
        signatures = int(petition["baseline_signatures"])
        cards.append(
            {
                "title": str(petition["title"]),
                "signatures": f"{signatures:,} signatures",
                "image": LOCAL_PETITION_TILES[index % len(LOCAL_PETITION_TILES)],
                "href": (
                    f"/p/{petition['slug']}?source_location=homepage"
                ),
                "background": LOCAL_PETITION_TILE_BACKGROUNDS[
                    index % len(LOCAL_PETITION_TILE_BACKGROUNDS)
                ],
            }
        )
    return cards


HOME_LOCAL_CARDS = _build_home_local_cards()

BROWSE_CARDS = [
    {
        "title": "Oppose the data center in Allen Township",
        "promoted_by": "24 supporters",
        "meta": "Northampton, PA, USA · 1,776 signatures",
        "image": "/static/assets/source-current/2026-07-25/browse-petitions/"
        "card-SOKwQzkzGiDBvxV-400x225.jpg",
    },
    {
        "title": "He was His Mother's Only Child-Justice for Roderick Gallon",
        "promoted_by": "51 supporters",
        "meta": "692 signatures",
        "image": "/static/assets/source-current/2026-07-25/browse-petitions/"
        "card-nXdwuCqUPjcfxfT-400x225.jpg",
    },
    {
        "title": "Implement rent control in Massachusetts",
        "promoted_by": "1 supporter",
        "meta": "Massachusetts, USA · 5 signatures",
        "image": "/static/assets/source-current/2026-07-25/browse-petitions/"
        "card-HYVlWklMvvdyKWQ-400x225.jpg",
    },
    {
        "title": "Release New Jersey's SFY 2025 Childhood Lead "
                 "Poisoning Report",
        "promoted_by": "3 supporters",
        "meta": "New Jersey, USA · 26 signatures",
        "image": "/static/assets/source-current/2026-07-25/browse-petitions/"
        "card-KLhNkyKCcNifEdt-400x225.jpg",
    },
    {
        "title": "Remove Flock cameras from the streets of Pennsylvania",
        "promoted_by": "1 supporter",
        "meta": "Pennsylvania, USA · 58 signatures",
        "image": "/static/assets/source-current/2026-07-25/browse-petitions/"
        "card-AxfcSTTaPMfTRAA-400x225.jpg",
    },
    {
        "title": "Stop the Noise Pollution from Pickleball on Marco Island",
        "promoted_by": "24 supporters",
        "meta": "Marco Island, Florida, USA · 310 signatures",
        "image": "/static/assets/source-current/2026-07-25/browse-petitions/"
        "card-ACEYIFNKGQmSFbt-400x225.jpg",
    },
    {
        "title": "Rebuild Beulah",
        "promoted_by": "66 supporters",
        "meta": "Pueblo County, CO, USA · 885 signatures",
        "image": "/static/assets/source-current/2026-07-25/browse-petitions/"
        "card-tjkHguNWNXeguDT-400x225.jpg",
    },
    {
        "title": "Stop the Dollar General development at Camino Loma Alta "
                 "in Vail, AZ",
        "promoted_by": "23 supporters",
        "meta": "Vail, AZ, USA · 377 signatures",
        "image": "/static/assets/source-current/2026-07-25/browse-petitions/"
        "card-uucBeZNUfoinmyG-400x225.jpg",
    },
]

CLIMATE_SEARCH_QUERY = "climate"
CLIMATE_SEARCH_COUNT = "11,974"
CLIMATE_SEARCH_RESULTS = [
    {
        "title": "Demand climate justice for a greener and fairer future",
        "excerpt": (
            "Climate change is not just an abstract issue; it's personal, it's "
            "tangible, and it's happening right now. As someone who deeply "
            "cares about the environment, I am passionately driven to raise "
            "awareness about the climate crisis."
        ),
        "signatures": "1,828",
        "location": "Philippines",
        "started": "Started June 23, 2026",
        "image": (
            "/static/assets/source-current/2026-08-02-rebuild-01/public/search/"
            "VpavwMMkFVQyMtV-fullsize.jpg"
        ),
    },
    {
        "title": (
            "Petition: for an ambitious, climate adapted Schuman Square, "
            "with a central canopy"
        ),
        "excerpt": (
            "The Schuman Square in Brussels has become a vast, hard expanse "
            "of concrete that does not invite people to linger or rest. In "
            "summer it is scorching hot, in winter it is harsh, windy and "
            "exposed."
        ),
        "signatures": "2,105",
        "location": "Belgium",
        "started": "Started June 29, 2026",
        "image": (
            "/static/assets/source-current/2026-08-02-rebuild-01/public/search/"
            "NWyoFaJadyFOjJF-fullsize.jpg"
        ),
    },
    {
        "title": "Protect animals from climate change and humans",
        "excerpt": (
            "Living in a world where animals are constantly under threat from "
            "both the devastating impacts of climate change and human "
            "activities is heartbreaking. I have always loved animals and "
            "believe they deserve to live in a world where they can thrive."
        ),
        "signatures": "65",
        "location": "United States",
        "started": "Started July 25, 2026",
        "image": (
            "/static/assets/source-current/2026-08-02-rebuild-01/public/search/"
            "srCGaznnbeZMoYW-fullsize.jpg"
        ),
    },
    {
        "title": (
            "Preserve 30-50% of Tengah forest to protect biodiversity and "
            "tackle climate emergency"
        ),
        "excerpt": (
            "We are writing on behalf of many concerned citizens and "
            "residents who are raising concerns about the continuing threat "
            "that Tengah Forest is facing from ongoing development."
        ),
        "signatures": "10,948",
        "location": "Singapore",
        "started": "Started June 8, 2021",
        "image": (
            "/static/assets/source-current/2026-08-02-rebuild-01/public/search/"
            "UOAAWGpuJrmNCdR-fullsize.jpg"
        ),
    },
    {
        "title": (
            "Mandate functioning climate control on special needs school "
            "buses in NYC"
        ),
        "excerpt": (
            "My son Ronald is five years old and diagnosed with autism. "
            "Recently, he endured a bus ride of over two hours in sweltering "
            "heat because his school bus had no working air conditioning."
        ),
        "signatures": "150",
        "location": "United States",
        "started": "Started July 20, 2026",
        "image": (
            "/static/assets/source-current/2026-08-02-rebuild-01/public/search/"
            "LysoAWNRtduDiPR-fullsize.jpg"
        ),
    },
    {
        "title": (
            "Petition by kids, asking for climate change to be a bigger part "
            "of the BC education"
        ),
        "excerpt": (
            "We’re here to talk to you about the impacts of climate change on "
            "our Earth. Climate change is having terrible consequences on our "
            "planet, and that’s why we need to learn more about it in school."
        ),
        "signatures": "342",
        "location": "Brentwood Bay, Canada",
        "started": "Started April 11, 2026",
        "image": (
            "/static/assets/source-current/2026-08-02-rebuild-01/public/search/"
            "cTfpGLHmlLIVPmu-fullsize.jpg"
        ),
    },
    {
        "title": "The Survival Crisis of Animals And Humans Under Extreme Climate",
        "excerpt": (
            "Extreme climate events like heatwaves, floods, and droughts are "
            "becoming more frequent and threaten animal survival by "
            "destroying habitats and food sources."
        ),
        "signatures": "49",
        "location": "Taiwan",
        "started": "Started June 21, 2026",
        "image": "/static/assets/source-current/2026-07-25/search-transit/"
        "default-petition-darker.gif",
    },
    {
        "title": (
            "Say No to Nuclear-Powered AI in Idaho Without Strong Climate "
            "and Safety Protections"
        ),
        "excerpt": (
            "A private company is proposing the first-ever nuclear-powered AI "
            "data center campus—and they want to build it in Idaho. But the "
            "public hasn’t been asked what we think."
        ),
        "signatures": "210",
        "location": "United States",
        "started": "Started December 4, 2025",
        "image": (
            "/static/assets/source-current/2026-08-02-rebuild-01/public/search/"
            "cnZoOosdXQoHVei-fullsize.jpg"
        ),
    },
]

TOPICS = [
    {
        "letter": "A",
        "slug": "animal-rights",
        "title": "Animal Rights",
        "signatures": "74,820,614",
        "description": "Take action for the welfare and protection of animals.",
    },
    {
        "letter": "B",
        "slug": "business",
        "title": "Business",
        "signatures": "21,148,906",
        "description": "Ask businesses to improve products, policies, and workplaces.",
    },
    {
        "letter": "C",
        "slug": "civil-rights",
        "title": "Civil Rights",
        "signatures": "98,763,206",
        "description": "Stand up for equal rights, dignity, and fair treatment.",
    },
    {
        "letter": "C",
        "slug": "consumer-rights",
        "title": "Consumer Rights",
        "signatures": "18,309,401",
        "description": "Help consumers demand safe products and fair practices.",
    },
    {
        "letter": "D",
        "slug": "disability-rights",
        "title": "Disability Rights",
        "signatures": "22,661,954",
        "description": "Create more accessible and inclusive communities.",
    },
    {
        "letter": "E",
        "slug": "education",
        "title": "Education",
        "signatures": "82,493,885",
        "description": "Improve schools and expand access to quality education.",
    },
    {
        "letter": "E",
        "slug": "environment",
        "title": "Environment",
        "signatures": "91,728,516",
        "description": "Protect the climate, natural spaces, and clean water.",
    },
    {
        "letter": "F",
        "slug": "family",
        "title": "Family",
        "signatures": "37,108,922",
        "description": "Support families and the services they rely on.",
    },
    {
        "letter": "G",
        "slug": "government-politics",
        "title": "Government & Politics",
        "signatures": "129,409,274",
        "description": "Call on public officials to listen and act.",
    },
    {
        "letter": "H",
        "slug": "health",
        "title": "Health",
        "signatures": "107,385,704",
        "description": "Advocate for better care, research, and public health.",
    },
    {
        "letter": "H",
        "slug": "human-rights",
        "title": "Human Rights",
        "signatures": "116,840,519",
        "description": "Defend the rights and freedoms of people everywhere.",
    },
    {
        "letter": "I",
        "slug": "immigration",
        "title": "Immigration",
        "signatures": "30,764,182",
        "description": "Build fairer and more humane immigration systems.",
    },
    {
        "letter": "J",
        "slug": "justice",
        "title": "Justice",
        "signatures": "86,591,723",
        "description": "Seek accountability and a fair justice system.",
    },
    {
        "letter": "L",
        "slug": "lgbtq-rights",
        "title": "LGBTQ+ Rights",
        "signatures": "42,300,945",
        "description": "Advance safety, equality, and belonging for LGBTQ+ people.",
    },
    {
        "letter": "M",
        "slug": "media-entertainment",
        "title": "Media & Entertainment",
        "signatures": "55,970,337",
        "description": "Shape the stories, culture, and entertainment people share.",
    },
    {
        "letter": "P",
        "slug": "public-safety",
        "title": "Public Safety",
        "signatures": "69,220,416",
        "description": "Make neighbourhoods, roads, and public spaces safer.",
    },
    {
        "letter": "S",
        "slug": "sports",
        "title": "Sports",
        "signatures": "32,896,745",
        "description": "Create fairer, safer, and more inclusive sports.",
    },
    {
        "letter": "T",
        "slug": "technology",
        "title": "Technology",
        "signatures": "16,901,204",
        "description": "Ask technology leaders to build responsibly.",
    },
    {
        "letter": "W",
        "slug": "womens-rights",
        "title": "Women’s Rights",
        "signatures": "77,884,610",
        "description": "Advance equality, safety, and opportunity for women.",
    },
    {
        "letter": "W",
        "slug": "workers-rights",
        "title": "Workers’ Rights",
        "signatures": "48,506,712",
        "description": "Support safe workplaces, fair pay, and worker dignity.",
    },
]
CURATED_TOPICS = [
    "Human Rights",
    "Education",
    "Government and Politics",
    "Entertainment",
    "Criminal Justice",
    "Health and Well-being",
    "Child and Family Well-being",
    "Economic Justice",
    "Health",
    "Public Safety",
    "Politics",
    "Animals",
    "Business and Economy",
    "Environment",
    "Racial Justice",
    "Entertainment & Media",
    "Women's Rights",
    "Technology",
    "Environmental Issues",
    "Sports",
    "Food",
    "Animal Rights and Conservation",
    "Ethnic and Racial Minorities",
    "Family",
    "Health and Safety",
    "Disability",
    "LGBTQ",
]

SEARCH_LANDING_TOPICS = [
    "Government and Politics",
    "Public Safety",
    "Health and Well-Being",
    "Education",
    "Business and Economy",
    "Child and Family Well-Being",
    "Criminal Justice",
    "Local Government",
    "Entertainment & Media",
    "Environmental Issues",
    "Student Issues",
    "Technology",
    "Animal Rights and Conservation",
    "National Government",
    "Global Social Justice Issues",
    "Education Reform",
    "Women's Rights",
    "Children's Rights",
    "Animal Welfare",
    "Public Health",
    "Ethnic and Racial Minorities",
    "Climate Change",
    "Economic Justice",
    "Immigration",
    "Disability Rights",
]

# The topic directory captured from the source site. topics.html used to carry
# this list inline while topic_page resolved slugs from SOURCE_TOPIC_DIRECTORY
# and TOPICS instead, so 44 of the 60 links the directory rendered were 404s.
# Both the page and the route read this now, so a topic the directory lists is
# a topic the site can open, by construction.
SOURCE_TOPIC_PAGES = [
    {"letter": "G", "title": "Government and Politics", "slug": "government-and-politics", "signatures": "106,843,667"},
    {"letter": "H", "title": "Human Rights", "slug": "human-rights", "signatures": "80,635,234"},
    {"letter": "C", "title": "Criminal Justice", "slug": "criminal-justice", "signatures": "55,935,359"},
    {"letter": "P", "title": "Politics", "slug": "politics", "signatures": "53,224,218"},
    {"letter": "H", "title": "Health and Well-being", "slug": "health-and-well-being", "signatures": "51,673,755"},
    {"letter": "A", "title": "Animals", "slug": "animals", "signatures": "50,786,366"},
    {"letter": "P", "title": "Public Safety", "slug": "public-safety", "signatures": "46,285,009"},
    {"letter": "H", "title": "Health", "slug": "health", "signatures": "46,097,675"},
    {"letter": "N", "title": "National Government", "slug": "national-government", "signatures": "33,455,860"},
    {"letter": "W", "title": "Women's Rights", "slug": "womens-rights", "signatures": "33,270,766"},
    {"letter": "E", "title": "Environment", "slug": "environment", "signatures": "32,306,527"},
    {"letter": "E", "title": "Economic Justice", "slug": "economic-justice", "signatures": "30,889,788"},
    {"letter": "E", "title": "Education", "slug": "education-17"},
    {"letter": "A", "title": "Animal Welfare", "slug": "animal-welfare-8"},
    {"letter": "C", "title": "Child and Family Well-Being", "slug": "child-and-family-well-being-en-ca"},
    {"letter": "B", "title": "Business and Economy", "slug": "business-and-economy-en-ca"},
    {"letter": "A", "title": "Animal Rights", "slug": "animal-rights-8"},
    {"letter": "L", "title": "Local Government", "slug": "local-government-en-ca"},
    {"letter": "G", "title": "Global Social Justice Issues", "slug": "global-social-justice-issues-en-ca"},
    {"letter": "E", "title": "Environmental Issues", "slug": "environmental-issues-en-ca"},
    {"letter": "A", "title": "Animal Rights and Conservation", "slug": "animal-rights-and-conservation-en-ca"},
    {"letter": "E", "title": "entertainment", "slug": "entertainment-12"},
    {"letter": "E", "title": "Ethnic and Racial Minorities", "slug": "ethnic-and-racial-minorities-en-ca"},
    {"letter": "C", "title": "COVID-19", "slug": "covid-19-en-ca"},
    {"letter": "C", "title": "Coronavirus Pandemic", "slug": "coronavirus-pandemic-en-ca"},
    {"letter": "A", "title": "Animal Cruelty", "slug": "animal-cruelty-8"},
    {"letter": "I", "title": "Indigenous Rights", "slug": "indigenous-rights-3"},
    {"letter": "C", "title": "Coronavirus", "slug": "coronavirus-en-ca"},
    {"letter": "D", "title": "Due Process", "slug": "due-process"},
    {"letter": "R", "title": "Racial Justice", "slug": "racial-justice-5"},
    {"letter": "L", "title": "local", "slug": "local-en-ca"},
    {"letter": "T", "title": "Technology", "slug": "technology-10"},
    {"letter": "C", "title": "conservation", "slug": "conservation-6"},
    {"letter": "B", "title": "Business and Brands", "slug": "business-and-brands-en-ca"},
    {"letter": "C", "title": "Canada", "slug": "canada-en-ca"},
    {"letter": "C", "title": "Consumer Rights", "slug": "consumer-rights-4"},
    {"letter": "E", "title": "Entertainment & Media", "slug": "entertainment-media-en-ca"},
    {"letter": "W", "title": "Wildlife Conservation", "slug": "wildlife-conservation-en-ca"},
    {"letter": "R", "title": "Regional Government", "slug": "regional-government-en-ca"},
    {"letter": "C", "title": "Children's Rights", "slug": "children-s-rights-3"},
    {"letter": "W", "title": "wildlife", "slug": "wildlife-en-ca"},
    {"letter": "C", "title": "Corruption", "slug": "corruption-12"},
    {"letter": "I", "title": "Immigration", "slug": "immigration-8"},
    {"letter": "I", "title": "Immigrants", "slug": "immigrants-en-ca"},
    {"letter": "A", "title": "Access to Healthcare", "slug": "access-to-healthcare-en-ca"},
    {"letter": "B", "title": "Business Regulation", "slug": "business-regulation-en-ca"},
    {"letter": "O", "title": "ontario", "slug": "ontario-3"},
    {"letter": "A", "title": "Arab and Middle Eastern", "slug": "arab-and-middle-eastern-en-ca"},
    {"letter": "H", "title": "Healthcare Reform", "slug": "healthcare-reform-en-ca"},
    {"letter": "P", "title": "Prisoners' Rights", "slug": "prisoners-rights-en-ca"},
    {"letter": "I", "title": "Iran", "slug": "iran-en-ca"},
    {"letter": "P", "title": "Public Health", "slug": "public-health-en-ca"},
    {"letter": "H", "title": "Health Inequality", "slug": "health-inequality-en-ca"},
    {"letter": "H", "title": "Health and Safety", "slug": "health-and-safety-en-ca"},
    {"letter": "F", "title": "Food", "slug": "food-en-ca"},
    {"letter": "F", "title": "Family", "slug": "family-en-ca"},
    {"letter": "W", "title": "Wildlife Protection", "slug": "wildlife-protection-en-ca"},
    {"letter": "W", "title": "Wildlife Biodiversity", "slug": "wildlife-biodiversity-en-ca"},
    {"letter": "P", "title": "Patients' Rights", "slug": "patients-rights-en-ca"},
    {"letter": "F", "title": "Freedom of religion", "slug": "freedom-of-religion-en-ca"},
]

SOURCE_TOPIC_DIRECTORY = [
    {"letter": "G", "slug": "government-and-politics-en-ca",
     "title": "Government and Politics", "signatures": "21,262,037"},
    {"letter": "H", "slug": "human-rights-12",
     "title": "Human Rights", "signatures": "18,364,777"},
    {"letter": "A", "slug": "animals-14",
     "title": "Animals", "signatures": "14,366,800"},
    {"letter": "C", "slug": "criminal-justice-en-ca",
     "title": "Criminal Justice", "signatures": "12,020,009"},
    {"letter": "H", "slug": "health",
     "title": "Health", "signatures": "10,887,676"},
    {"letter": "P", "slug": "public-safety-en-ca",
     "title": "Public Safety", "signatures": "8,771,205"},
    {"letter": "E", "slug": "economic-justice-en-ca",
     "title": "Economic Justice", "signatures": "8,103,427"},
    {"letter": "E", "slug": "environment",
     "title": "Environment", "signatures": "7,832,813"},
    {"letter": "H", "slug": "health-and-well-being-en-ca",
     "title": "Health and Well-Being", "signatures": "7,697,883"},
    {"letter": "P", "slug": "politics-11",
     "title": "Politics", "signatures": "7,232,399"},
    {"letter": "B", "slug": "business-and-economy-en-ca",
     "title": "Business and Economy", "signatures": "6,620,515"},
    {"letter": "N", "slug": "national-government-en-ca",
     "title": "National Government", "signatures": "6,442,821"},
    {"letter": "W", "slug": "women-s-rights-12",
     "title": "Women's Rights", "signatures": "6,376,245"},
    {"letter": "A", "slug": "animal-rights",
     "title": "Animal Rights", "signatures": "6,057,257"},
    {"letter": "A", "slug": "animal-welfare-8",
     "title": "Animal Welfare", "signatures": "5,546,895"},
    {"letter": "E", "slug": "education-17",
     "title": "Education", "signatures": "5,379,527"},
    {"letter": "L", "slug": "local-government-en-ca",
     "title": "Local Government", "signatures": "5,280,948"},
    {"letter": "G", "slug": "global-social-justice-issues-en-ca",
     "title": "Global Social Justice Issues", "signatures": "5,141,136"},
    {"letter": "E", "slug": "environmental-issues-en-ca",
     "title": "Environmental Issues", "signatures": "4,886,555"},
    {"letter": "A", "slug": "animal-rights-and-conservation-en-ca",
     "title": "Animal Rights and Conservation", "signatures": "4,364,586"},
    {"letter": "C", "slug": "child-and-family-well-being-en-ca",
     "title": "Child and Family Well-Being", "signatures": "4,327,169"},
    {"letter": "E", "slug": "entertainment-12",
     "title": "Entertainment", "signatures": "4,260,365"},
    {"letter": "E", "slug": "ethnic-and-racial-minorities-en-ca",
     "title": "Ethnic and Racial Minorities", "signatures": "4,069,296"},
    {"letter": "C", "slug": "covid-19-en-ca",
     "title": "COVID-19", "signatures": "3,992,621"},
]
for source_topic in SOURCE_TOPIC_DIRECTORY:
    source_topic["description"] = (
        f"Discover petitions and campaigns about {source_topic['title']}."
    )

GUIDE_SECTIONS = [
    {
        "title": "Get started",
        "body": (
            "Creating a high-quality petition with a clear story, specific "
            "Decision Maker, memorable headline, and compelling image will "
            "resonate with people, grow support, and help you achieve the "
            "change you want."
        ),
        "links": [
            {
                "label": "How to create a petition",
                "href": "/petition-guides/create-a-petition",
            },
            {
                "label": (
                    "How to collect signatures and turn your petition "
                    "into real change"
                ),
                "href": "/petition-guides/share-your-petition",
            },
        ],
    },
    {
        "title": "Amplify your impact",
        "body": (
            "You’ve created a compelling petition and gathered supporters—now "
            "turn that momentum into action with media coverage and direct "
            "engagement with the people who can make change happen."
        ),
        "links": [
            {
                "label": (
                    "How to reach out to the media and get coverage for your "
                    "cause"
                ),
                "href": "/petition-guides/media",
            },
            {
                "label": "How to win with Decision Makers",
                "href": "/petition-guides/engage-decision-makers",
            },
        ],
    },
    {
        "title": "Celebrate your win!",
        "body": (
            "Declare victory when a tangible change happens. The outcome may "
            "look different from your original ask—and that’s okay. Celebrate "
            "the people who helped make it possible."
        ),
        "links": [
            {
                "label": "How to declare victory for your petition",
                "href": "/petition-guides/declare-petition-victory",
            }
        ],
    },
]

GUIDE_ARTICLES = {
    "create-a-petition": {
        "kicker": "How to create a petition",
        "title": "How to create a petition",
        "intro": (
            "Creating a high-quality petition gives you the best chance of "
            "achieving the change you want. A memorable headline, compelling "
            "image, carefully selected Decision Maker, and strong story help "
            "your petition grow support and win."
        ),
        "related": [
            {
                "label": "Collect signatures and grow your petition",
                "href": "/petition-guides/share-your-petition",
            },
            {
                "label": "Reach Out to the Media",
                "href": "/petition-guides/media",
            },
            {
                "label": "Engage Your Decision Maker",
                "href": "/petition-guides/engage-decision-makers",
            },
            {
                "label": "Declaring Petition Victory",
                "href": "/petition-guides/declare-petition-victory",
            },
        ],
        "sections": [
            {
                "id": "what-is-a-petition",
                "title": "What is a petition?",
                "paragraphs": [
                    (
                        "A petition is a written request for a specific change "
                        "made to a person or organization with the authority to "
                        "act. Signatures show the breadth of support for that ask."
                    ),
                    (
                        "Petitions can address local, national, or global issues "
                        "including public safety, education, healthcare, animal "
                        "welfare, civil rights, and the environment."
                    ),
                ],
                "points": [
                    "Write a clear request and explain why the change matters.",
                    "Choose the Decision Maker who can respond to your request.",
                    "Ask other people to sign and share your petition.",
                    "Deliver the petition and keep supporters informed.",
                ],
            },
            {
                "id": "choose-topic",
                "title": "How to Choose Your Topic",
                "paragraphs": [
                    (
                        "Start with an issue that matters to you, then narrow it "
                        "to one specific and achievable outcome. Make it easy for "
                        "a potential supporter to understand what success means."
                    ),
                    (
                        "Consider who is affected, who can make the change, why "
                        "the issue matters now, and how you will measure progress."
                    ),
                ],
                "points": [
                    "Define the exact outcome you want.",
                    "Identify a person with the power to make that change.",
                    "Explain the impact on people or a community.",
                    "Set a clear way to recognize success.",
                ],
            },
            {
                "id": "headline",
                "title": "How to Write Your Headline",
                "paragraphs": [
                    (
                        "Your headline is the first opportunity to make the "
                        "requested change clear. Name specific places, people, "
                        "or organizations and keep the wording concise."
                    ),
                    (
                        "Begin with an action verb such as stop, save, ban, "
                        "change, grant, oppose, add, or start. Use urgency without "
                        "relying on all caps or extra punctuation."
                    ),
                ],
                "points": [],
            },
            {
                "id": "story",
                "title": "How to Tell Your Story",
                "paragraphs": [
                    (
                        "Storytelling is the heart of a successful petition. "
                        "Facts add credibility, while a personal experience helps "
                        "people understand the human impact."
                    ),
                    (
                        "Describe who is affected, the obstacles standing in the "
                        "way, what is at stake, and why now is the time to act."
                    ),
                ],
                "points": [
                    "Open with the personal reason you care.",
                    "Explain the problem in plain language.",
                    "Describe the solution and who can deliver it.",
                    "Close with a direct request to sign.",
                ],
            },
            {
                "id": "image",
                "title": "How to Choose an Image or Add a Video",
                "paragraphs": [
                    (
                        "Choose one simple, high-quality image that conveys "
                        "emotion and remains clear at small sizes. Avoid busy "
                        "collages, heavy text, and low-contrast graphics."
                    )
                ],
                "points": [
                    "Use a photo you own whenever possible.",
                    "Show a person, animal, place, or object connected to the issue.",
                    "Upload an image at least 1600 by 900 pixels.",
                ],
            },
            {
                "id": "decision-maker",
                "title": "How to Choose Your Decision Maker",
                "paragraphs": [
                    (
                        "A Decision Maker is a person with the authority to "
                        "implement the change. Choose a named individual who is "
                        "directly responsible rather than a broad organization."
                    )
                ],
                "points": [
                    "Pick the person closest to the decision.",
                    "Make sure the request is within their authority.",
                    "Include accurate contact information when available.",
                ],
            },
        ],
    },
    "share-your-petition": {
        "kicker": "Collect signatures",
        "title": "How to collect signatures and grow your petition",
        "intro": (
            "A clear sharing plan helps the people closest to your issue become "
            "your first supporters, then gives them simple ways to bring others in."
        ),
        "related": [],
        "sections": [
            {
                "id": "first-supporters",
                "title": "Start with your first supporters",
                "paragraphs": [
                    "Ask friends, family, neighbours, and affected communities to sign first.",
                    "A personal message explains why their support matters more effectively than a generic post.",
                ],
                "points": ["Send individual messages.", "Invite supporters to share.", "Thank people as momentum grows."],
            },
            {
                "id": "share-online",
                "title": "Share your petition online",
                "paragraphs": [
                    "Use the channels where your community already gathers and tailor each message to that audience."
                ],
                "points": ["Post a clear image.", "Lead with the requested change.", "Include the petition link."],
            },
            {
                "id": "offline",
                "title": "Build support in your community",
                "paragraphs": [
                    "Local events, community meetings, and conversations can reach people who do not see your online posts."
                ],
                "points": [],
            },
        ],
    },
    "media": {
        "kicker": "Amplify your impact",
        "title": "How to reach out to the media",
        "intro": (
            "A timely, focused pitch can help a journalist understand why your "
            "petition matters to their audience and why the story matters now."
        ),
        "related": [],
        "sections": [
            {
                "id": "newsworthy",
                "title": "Make your story newsworthy",
                "paragraphs": [
                    "Connect the petition to a timely event, a local impact, or a clear public-interest question."
                ],
                "points": ["Lead with what changed.", "Use specific local details.", "Provide one strong spokesperson."],
            },
            {
                "id": "pitch",
                "title": "Write a concise media pitch",
                "paragraphs": [
                    "Introduce the issue, explain why it matters now, and offer a reliable person to interview."
                ],
                "points": [],
            },
            {
                "id": "follow-up",
                "title": "Follow up respectfully",
                "paragraphs": [
                    "Give journalists time to respond and send one concise follow-up with any meaningful new development."
                ],
                "points": [],
            },
        ],
    },
    "engage-decision-makers": {
        "kicker": "Turn support into action",
        "title": "How to engage your Decision Maker",
        "intro": (
            "Show the person with authority that your petition represents real "
            "people, a practical solution, and sustained community support."
        ),
        "related": [],
        "sections": [
            {
                "id": "research",
                "title": "Understand your Decision Maker",
                "paragraphs": [
                    "Learn what they control, what they have said publicly, and which evidence will help them act."
                ],
                "points": [],
            },
            {
                "id": "contact",
                "title": "Ask for a meeting",
                "paragraphs": [
                    "Make a specific request, explain who will attend, and share the petition’s current support."
                ],
                "points": ["Be concise.", "Offer flexible times.", "Bring a clear solution."],
            },
            {
                "id": "deliver",
                "title": "Deliver your petition",
                "paragraphs": [
                    "Plan a respectful delivery that centres affected people and creates a clear moment for a response."
                ],
                "points": [],
            },
        ],
    },
    "declare-petition-victory": {
        "kicker": "Celebrate your win",
        "title": "How to declare victory for your petition",
        "intro": (
            "When a tangible change happens, share the result, recognize the "
            "people who helped, and explain what the victory means."
        ),
        "related": [],
        "sections": [
            {
                "id": "victory",
                "title": "Recognize a real victory",
                "paragraphs": [
                    "A victory is a concrete outcome connected to your request, even when the final solution differs from the original ask."
                ],
                "points": [],
            },
            {
                "id": "update",
                "title": "Tell your supporters",
                "paragraphs": [
                    "Publish an update with the outcome, a thank-you, and any next steps."
                ],
                "points": [],
            },
        ],
    },
}

IMPACT_AVATARS = [
    f"/static/assets/source-current/2026-08-02-rebuild-01/public/impact/avatar-{index:02d}.jpg"
    for index in range(1, 14)
]

VICTORIES = [
    {
        "title": "Support for Tenants in Singapore, especially non-essential businesses",
        "signatures": "7,652 signatures",
    },
    {
        "title": "Keep Service 66 the same and introduce a new route instead",
        "signatures": "1,214 signatures",
    },
    {
        "title": "Add Singapore to the UK travel corridor list",
        "signatures": "2,578 signatures",
    },
    {
        "title": "Stop the European Super League",
        "signatures": "3,547 signatures",
    },
]

TEAM = [
    ("Ben Rattray", "Founder & Chief Executive Officer"),
    ("Benjamin Joffe-Walt", "Chief Operating Officer"),
    ("Brad Henrickson", "Chief Technology Officer"),
    ("Steve Dziedzic", "Chief Product Officer"),
    ("Allie Roseman", "Director of People Operations"),
    ("Anabella Di Ciancia", "Director of Communications"),
    ("Andrew Konya", "President, Deliberations"),
    ("Barbara Cvenic", "Chief of Staff to the CEO"),
    ("Bryan Galvin", "Senior Director of Finance"),
    ("Chelsea Williams", "Senior Director of Brand Growth"),
    ("Chris Campbell", "Director of Engineering"),
    ("Danny Moldovan", "VP of Policy and Legal"),
    ("David Lifson", "VP of Product"),
    ("Duncan Lockard", "VP of Finance & Strategy"),
    ("Ed Urgola", "Senior Director of Product"),
    ("Eric Steinle", "Director of Product"),
    ("Hamish Chandra", "VP of Design and Research"),
    ("Jaime Rodas", "VP of Engineering"),
    ("Jeff Knight", "VP of Engineering"),
    ("Jen Garfield", "Senior Director of Product"),
    ("Kajal Odedra", "VP of Communications"),
    ("Leslie Moser", "Senior Director of Product"),
    ("Lia Siebert", "VP of Product"),
    ("Maroun Najjar", "Senior Director of Design"),
    (
        "Mayur Bhatia",
        "Senior Director of Engineering, Technical Operations",
    ),
    ("Meg McClean", "Chief of Staff to the CMO"),
    ("Meg Sawatzke", "Chief of Staff to the CPO"),
    ("Melissa Benjamin", "VP of People"),
]
TEAM_ASSET_ORDER = [
    1, 2, 3, 4, 7, 5, 6, 8, 9, 11, 10, 12,
    5, 6, 7, 8, 9, 10, 11, 12, 2, 3, 4, 5, 6, 7, 8, 10,
]
TEAM_MEMBERS = [
    {
        "name": name,
        "role": role,
        "image": (
            "/static/assets/source-current/2026-08-02-rebuild-01/public/team/"
            f"canonical-{asset_index:02d}."
            f"{'png' if asset_index in {1, 6} else 'svg' if asset_index == 9 else 'jpg'}"
        ),
    }
    for (name, role), asset_index in zip(TEAM, TEAM_ASSET_ORDER)
]

POLICIES = {
    "community": {
        "slug": "community",
        "title": "Community Guidelines",
        "updated": "13 August 2025",
        "sections": [
            {
                "id": "purpose",
                "title": "",
                "paragraphs": [
                    (
                        "As an open platform, we’re committed to freedom of "
                        "expression. You’ll see a variety of perspectives "
                        "here, reflecting the diverse views of people in the "
                        "community. Anyone can use Change.org no matter who "
                        "they are, where they live, and what they believe, as "
                        "long as they follow simple guidelines to keep our "
                        "platform safe and open."
                    ),
                    (
                        "This applies to all content you post. “Content” "
                        "includes, but is not limited to, petitions, updates, "
                        "comments, photographs, and usernames."
                    ),
                    (
                        "These Community Guidelines, along with our Terms of "
                        "Service, lay out the rules for using Change.org."
                    ),
                ],
                "points": [],
            },
            {
                "id": "dos",
                "title": "Do’s",
                "paragraphs": [
                    "First, here are few things we love to see you do on Change.org:"
                ],
                "points": [
                    {
                        "title": "Speak out on any issue you want to change",
                        "body": (
                            "Tell your personal story when you start a "
                            "petition — hearing how you are affected by a "
                            "problem is powerful. Explain the problem, how it "
                            "impacts you, your family, friends, or community. "
                            "Then explain the solution and how others can be "
                            "a part of it. We recognize the need for anonymity "
                            "in some cases and allow aliases to be used. For "
                            "example, if you are concerned that using your real "
                            "name may put your safety, livelihood, or privacy "
                            "at risk."
                        ),
                    },
                    {
                        "title": "Choose the right decision maker",
                        "body": (
                            "Choose the decision maker who can give you what "
                            "you want. A decision maker may be a particular "
                            "person, group, or company, who has the direct "
                            "ability to fix your problem. Work with them "
                            "constructively both on and off our platform to "
                            "come up with solutions."
                        ),
                    },
                ],
            },
            {
                "id": "authenticity",
                "title": "Be authentic",
                "paragraphs": [
                    "Represent yourself and your campaign honestly. Do not manipulate signatures or impersonate another person."
                ],
                "points": [],
            },
            {
                "id": "enforcement",
                "title": "How we enforce these guidelines",
                "paragraphs": [
                    "Content may be limited or removed when it violates these rules. Serious or repeated violations can result in account restrictions."
                ],
                "points": [],
            },
        ],
    },
    "privacy": {
        "slug": "privacy",
        "title": "Privacy Policy",
        "updated": "21 May 2026",
        "toc": [
            {"id": "1", "label": "What this Privacy Policy Covers"},
            {"id": "2", "label": "Information We Collect"},
            {"id": "3", "label": "How We Use Your Information"},
            {"id": "4", "label": "Who May Receive Your Information"},
            {"id": "5", "label": "Data Security"},
            {"id": "6", "label": "Data Retention"},
            {"id": "7", "label": "Personal Data of Children"},
            {"id": "8", "label": "Your Privacy Choices"},
            {"id": "8a", "label": "U.S. State Privacy Rights", "nested": True},
            {"id": "8b", "label": "EU/UK Privacy Rights", "nested": True},
            {"id": "9", "label": "Key Contacts"},
        ],
        "sections": [
            {
                "id": "introduction",
                "title": "",
                "paragraphs": [
                    {
                        "html": (
                            "At Change.org, PBC (“Change.org”), we take your "
                            "privacy seriously. Please read this Privacy Policy "
                            "to learn how we treat your personal data. "
                            "<strong>By using or accessing our platform and "
                            "websites (“Services”) in any manner, you "
                            "acknowledge that you accept the practices and "
                            "policies outlined below, and you hereby agree that "
                            "we will collect, use and disclose your information "
                            "as described in this Privacy Policy.</strong>"
                        )
                    },
                    {
                        "html": (
                            "Remember that your use of Change.org’s Services is "
                            "at all times subject to our "
                            "<a href=\"/policies/terms-of-service\">Terms of "
                            "Service</a>, which incorporates this Privacy "
                            "Policy. Any terms we use in this Policy without "
                            "defining them have the definitions given to them "
                            "in the <a href=\"/policies/terms-of-service\">"
                            "Terms of Service</a>."
                        )
                    },
                    (
                        "As we continually work to improve our Services, we may "
                        "need to change this Privacy Policy from time to time. "
                        "We will alert you of material changes by placing a "
                        "notice on the Change.org website, by sending you an "
                        "email and/or by some other means. If you use the "
                        "Services after any changes have been posted, that "
                        "means you acknowledge all of the changes."
                    ),
                ],
                "points": [],
            },
            {
                "id": "1",
                "title": "1. What this Privacy Policy Covers",
                "paragraphs": [
                    (
                        "This Privacy Policy covers how we treat Personal Data "
                        "that we gather when you access or use our Services."
                    )
                ],
                "points": [],
            },
            {
                "id": "2",
                "title": "2. Information We Collect",
                "paragraphs": [
                    (
                        "We collect information you provide, information "
                        "created when you use the Services, and information "
                        "from cookies and similar technologies."
                    )
                ],
                "points": [],
            },
            {
                "id": "3",
                "title": "3. How We Use Your Information",
                "paragraphs": [
                    (
                        "We use information to provide petition features, "
                        "personalize relevant content, protect the platform, "
                        "communicate with you, and meet legal obligations."
                    )
                ],
                "points": [],
            },
            {
                "id": "4",
                "title": "4. Who May Receive Your Information",
                "paragraphs": [
                    (
                        "We disclose Personal Data to service providers and "
                        "other parties only as described in this Policy."
                    )
                ],
                "points": [],
            },
            {
                "id": "5",
                "title": "5. Data Security",
                "paragraphs": [
                    (
                        "We use appropriate technical and organizational "
                        "measures designed to protect Personal Data."
                    )
                ],
                "points": [],
            },
            {
                "id": "6",
                "title": "6. Data Retention",
                "paragraphs": [
                    (
                        "We retain information only for as long as reasonably "
                        "necessary for the purposes described in this Policy."
                    )
                ],
                "points": [],
            },
            {
                "id": "7",
                "title": "7. Personal Data of Children",
                "paragraphs": [
                    (
                        "The Services are not directed to children under the "
                        "minimum age permitted in their country."
                    )
                ],
                "points": [],
            },
            {
                "id": "8",
                "title": "8. Your Privacy Choices",
                "paragraphs": [
                    (
                        "You can change communication and cookie preferences, "
                        "update account details, and request access to or "
                        "deletion of eligible information."
                    )
                ],
                "points": [],
            },
            {
                "id": "8a",
                "title": "8A. U.S. State Privacy Rights",
                "paragraphs": [
                    (
                        "Residents of eligible U.S. states may have additional "
                        "access, correction, deletion, and opt-out rights."
                    )
                ],
                "points": [],
            },
            {
                "id": "8b",
                "title": (
                    "8B. European Union, United Kingdom, and Swiss "
                    "Privacy Rights"
                ),
                "paragraphs": [
                    (
                        "People in these regions may exercise applicable data "
                        "protection rights and contact the relevant authority."
                    )
                ],
                "points": [],
            },
            {
                "id": "9",
                "title": "9. Key Contacts",
                "paragraphs": [
                    (
                        "Questions about privacy can be submitted through the "
                        "Help Center linked in the site footer."
                    )
                ],
                "points": [],
            },
        ],
    },
    "terms-of-service": {
        "slug": "terms-of-service",
        "title": "Terms of Service",
        "updated": "17 March 2026",
        "toc": [
            {"id": "1", "label": "User accounts"},
            {"id": "2", "label": "User content rules"},
            {"id": "3", "label": "Posting user content"},
            {"id": "4", "label": "Open platform"},
            {"id": "5", "label": "Our rights"},
            {"id": "6", "label": "Purchases and donations"},
            {"id": "7", "label": "Copyright infringement"},
            {"id": "8", "label": "More legal stuff to protect us"},
            {"id": "9", "label": "Dispute resolution"},
            {"id": "10", "label": "Text messaging"},
            {"id": "11", "label": "Updates to Terms"},
            {"id": "12", "label": "How to contact us"},
            {
                "id": "13",
                "label": "Privacy addendum for petition starters",
            },
        ],
        "sections": [
            {
                "id": "introduction",
                "title": "",
                "paragraphs": [
                    (
                        "Change.org, PBC (“Change.org”) is a corporation "
                        "registered in the state of Delaware, United States. "
                        "Change.org, PBC is fully owned by The Change.org "
                        "Charitable Foundation, a 501c3 nonprofit organization."
                    ),
                    (
                        "Change.org’s mission is to empower people everywhere "
                        "to create the change they want to see. We’re an open "
                        "platform, because we believe more change happens when "
                        "people with different backgrounds and perspectives "
                        "can participate in the conversation. We need rules to "
                        "keep our platforms safe for you, us, and the "
                        "community, and these Terms of Service (“Terms”) "
                        "outline your rights and responsibilities related to "
                        "our platform and services to the extent permitted by "
                        "applicable laws."
                    ),
                ],
                "points": [],
            },
            {
                "id": "1",
                "title": "1. User accounts",
                "paragraphs": [
                    (
                        "Provide accurate account information, protect your "
                        "access credentials, and use the platform only for "
                        "lawful participation."
                    )
                ],
                "points": [
                    "Do not interfere with platform security.",
                    "Do not automate deceptive activity or manipulate support.",
                    "Respect the rights and privacy of other people.",
                ],
            },
            {
                "id": "2",
                "title": "2. User content rules",
                "paragraphs": [
                    (
                        "Content must follow our Community Guidelines and may "
                        "not violate law or another person’s rights."
                    )
                ],
                "points": [],
            },
            {
                "id": "3",
                "title": "3. Posting user content",
                "paragraphs": [
                    (
                        "You retain ownership of content you submit and give "
                        "Change.org the permissions needed to host, display, "
                        "and distribute it through the service."
                    )
                ],
                "points": [],
            },
            {
                "id": "4",
                "title": "4. Open platform",
                "paragraphs": [
                    (
                        "Change.org is an open platform where many different "
                        "people and perspectives can participate."
                    )
                ],
                "points": [],
            },
            {
                "id": "5",
                "title": "5. Our rights",
                "paragraphs": [
                    (
                        "We may protect, maintain, and improve the Services "
                        "and enforce these Terms."
                    )
                ],
                "points": [],
            },
            {
                "id": "6",
                "title": "6. Purchases and donations",
                "paragraphs": [
                    (
                        "Payment features identify the amount, frequency, and "
                        "recipient before you submit a transaction."
                    )
                ],
                "points": [],
            },
            {
                "id": "7",
                "title": "7. Copyright infringement",
                "paragraphs": [
                    (
                        "We respond to valid notices concerning copyrighted "
                        "material in accordance with applicable law."
                    )
                ],
                "points": [],
            },
            {
                "id": "8",
                "title": "8. More legal stuff to protect us",
                "paragraphs": [
                    (
                        "The Services are provided subject to the warranties, "
                        "limitations, and exclusions permitted by law."
                    )
                ],
                "points": [],
            },
            {
                "id": "9",
                "title": "9. Dispute resolution",
                "paragraphs": [
                    (
                        "This section explains how disputes are handled and "
                        "which law applies."
                    )
                ],
                "points": [],
            },
            {
                "id": "10",
                "title": "10. Text messaging",
                "paragraphs": [
                    (
                        "Text-message programs are optional and the applicable "
                        "consent and opt-out terms are shown when you enroll."
                    )
                ],
                "points": [],
            },
            {
                "id": "11",
                "title": "11. Updates to Terms",
                "paragraphs": [
                    (
                        "We may update these Terms and will provide notice of "
                        "material changes as required."
                    )
                ],
                "points": [],
            },
            {
                "id": "12",
                "title": "12. How to contact us",
                "paragraphs": [
                    (
                        "Use the Help Center boundary linked from the footer "
                        "for questions about these Terms."
                    )
                ],
                "points": [],
            },
            {
                "id": "13",
                "title": "13. Privacy addendum for petition starters",
                "paragraphs": [
                    (
                        "Petition starters must handle supporter information "
                        "lawfully and only for the purposes disclosed."
                    )
                ],
                "points": [],
            },
        ],
    },
    "cookies": {
        "slug": "cookies",
        "title": "Cookie Policy",
        "updated": "30 July 2026",
        "toc": [
            {"id": "1", "label": "What is a cookie?"},
            {"id": "2", "label": "What cookies do we use?"},
            {"id": "3", "label": "How do I manage cookies?"},
            {"id": "4", "label": "Policy updates"},
        ],
        "sections": [
            {
                "id": "introduction",
                "title": "",
                "paragraphs": [
                    (
                        "Like all platforms, we use cookies and similar "
                        "technologies for the site to function, and to give "
                        "you a better and more personalized experience of "
                        "Change.org. This policy outlines which cookies we use "
                        "and explains how you can manage them."
                    )
                ],
                "points": [],
            },
            {
                "id": "1",
                "title": "What is a cookie?",
                "paragraphs": [
                    {
                        "html": (
                            "Cookies and similar technologies such as pixel tags, "
                            "web beacons, clear GIFs, and JavaScript are standard "
                            "features of websites that allow us to store small "
                            "amounts of data on your computer about your visit to "
                            "the Change.org platform. They help us learn which "
                            "areas of the platform are useful and which areas need "
                            "improvement.<br>On Change.org, we use cookies for many "
                            "things, which we explain in detail below and which include:"
                        )
                    },
                ],
                "points": [
                    "to remember your preferred language and country;",
                    "to help you log in again when you revisit the platform;",
                    (
                        "to connect your Change.org account to your social "
                        "media account, if you choose to do so; and"
                    ),
                    (
                        "to help our engineers improve the platform, by "
                        "understanding how people find us and what devices "
                        "they’re using."
                    ),
                ],
            },
            {
                "id": "2",
                "title": "What cookies do we use?",
                "paragraphs": [
                    (
                        "We use Essential, Preference, Analytics, and "
                        "Marketing cookies. Essential cookies enable core "
                        "security and account functions; optional categories "
                        "are used only according to your preferences."
                    ),
                    (
                        "Cookie providers, expiry periods, and uses are shown "
                        "in the category tables below."
                    ),
                ],
                "points": [],
            },
            {
                "id": "3",
                "title": "How do I manage cookies?",
                "paragraphs": [
                    {
                        "html": (
                            "Use the <a href=\"/account_settings/"
                            "manage_cookies\">Manage cookies</a> page to enable "
                            "or disable optional categories. Essential cookies "
                            "cannot be disabled because core features depend "
                            "on them."
                        )
                    }
                ],
                "points": [],
            },
            {
                "id": "4",
                "title": "Policy updates",
                "paragraphs": [
                    (
                        "We may update this Cookie Policy as technologies, "
                        "partners, or legal requirements change. The date at "
                        "the top identifies the latest revision."
                    )
                ],
                "points": [],
            },
        ],
    },
}


def external_url(host: str, path: str = "") -> str:
    """Build a reviewed HTTPS destination without embedding it in page HTML."""
    return urllib.parse.urlunsplit(("https", host, path, "", ""))


EXTERNAL_DESTINATIONS = {
    "blog": {
        "label": "Change.org Blog",
        "description": (
            "News and campaign stories are available beyond this offline edition."
        ),
        "return_path": "/",
    },
    "careers": {
        "label": "Careers at Change.org",
        "description": "Explore open roles and learn about working at Change.org.",
        "return_path": "/about",
        "url": external_url("careers.change.org", "/"),
    },
    "help": {
        "label": "Change.org Help Center",
        "description": "Find account, petition, signature, and contribution support.",
        "return_path": "/",
        "url": external_url("help.change.org", "/en_US"),
    },
    "instagram": {
        "label": "Change.org on Instagram",
        "description": "Stories and updates from campaigns around the world.",
        "return_path": "/",
        "url": external_url("www.instagram.com", "/changedotorg"),
    },
    "x": {
        "label": "Change.org on X",
        "description": "Public updates from Change.org and petition starters.",
        "return_path": "/",
        "url": external_url("x.com", "/Change"),
    },
    "facebook": {
        "label": "Change.org on Facebook",
        "description": "Campaign stories and community updates.",
        "return_path": "/",
        "url": external_url("www.facebook.com", "/change.org"),
    },
    "linkedin": {
        "label": "Change.org on LinkedIn",
        "description": "This social profile is outside the offline edition.",
        "return_path": "/l/us/p/press",
        "url": external_url("www.linkedin.com", "/company/change.org"),
    },
    "facebook-auth": {
        "label": "Continue with Facebook",
        "description": "Facebook sign-in is outside this offline edition.",
        "return_path": "/login_or_join",
    },
    "google-auth": {
        "label": "Continue with Google",
        "description": "Google sign-in is outside this offline edition.",
        "return_path": "/login_or_join",
    },
    "tiktok": {
        "label": "Change.org on TikTok",
        "description": "Short videos from people creating change.",
        "return_path": "/",
        "url": external_url("www.tiktok.com", "/@changedotorg"),
    },
    "google-privacy": {
        "label": "Google Privacy Policy",
        "description": "The privacy policy for the service that protects source forms.",
        "return_path": "/policies/privacy",
        "url": external_url("policies.google.com", "/privacy"),
    },
    "google-terms": {
        "label": "Google Terms of Service",
        "description": "The terms for the service that protects source forms.",
        "return_path": "/policies/terms-of-service",
        "url": external_url("policies.google.com", "/terms"),
    },
}

# ---------------------------------------------------------------------------
# Persistent storage boot (sqlite3 WAL under CLAWBENCH_DATA_DIR, outside
# clone/): migrate to head + deterministic seed on every process start.
# ---------------------------------------------------------------------------

PAYMENT_RUNTIME_PATH = ROOT.parent / "backend" / "runtime.json"
PAYMENT_RUNTIME = json.loads(PAYMENT_RUNTIME_PATH.read_text(encoding="utf-8"))
if PAYMENT_RUNTIME["database"]["filename"] != db.DB_FILENAME:
    raise RuntimeError("Change database filename differs from runtime contract")
if not db.db_path().exists() and db.legacy_db_path().exists():
    migrate_legacy_namespace_copy(
        db.legacy_db_path(),
        db.db_path(),
        expected_site_id=SITE_ID,
    )
SITE_BACKEND = SiteBackend.open(
    PAYMENT_RUNTIME,
    data_root=db.db_path().parent,
)
SITE_BACKEND.lifecycle.initialize()
assert SITE_BACKEND.session_cookie["name"] == SESSION_COOKIE
db.ensure_ready()
repository = build_repository()

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

AUTH_STORE = LocalAuthStore(
    db.db_path(),
    site_id=SITE_ID,
    now=lambda: 1_785_332_800,
)


def dispatch_harbor_auth_mail(session_token: str, purpose: str) -> None:
    """Compatibility hook; the auth store delivers synchronously to Mailpit."""

    return None

SEED_AUTH_ACCOUNTS = {
    "taylor.brooks@example.test": {
        "name": "Taylor Brooks",
        "password": OWNER_PASSWORD,
    },
    "jordan.rivera@example.test": {
        "name": "Jordan Rivera",
        "password": FIXTURE_PASSWORD,
    },
    "casey.newman@example.test": {
        "name": "Casey Newman",
        "password": FIXTURE_PASSWORD,
    },
}


def seed_auth_accounts() -> None:
    AUTH_STORE.ensure_schema()
    for email, credentials in SEED_AUTH_ACCOUNTS.items():
        business_account = db.ensure_account(email)
        AUTH_STORE.seed_account(
            subject_id=business_account["id"],
            email=email,
            display_name=credentials["name"],
            password=credentials["password"],
        )
    AUTH_STORE.reconcile_mail()


def reset_site_to_seed() -> dict[str, int]:
    with closing(db.connect()) as connection:
        connection.execute("BEGIN IMMEDIATE")
        SITE_BACKEND.lifecycle.reset_embedded(
            connection, confirm_site_id=SITE_ID
        )
        connection.commit()
    counts = db.reset_to_seed()
    seed_auth_accounts()
    AUTH_UI_STATES.clear()
    counts.update(AUTH_STORE.counts())
    return counts


seed_auth_accounts()

app = FastAPI(
    title="Change.org offline clone — persistent backend",
    docs_url=None,
    redoc_url=None,
    openapi_url=None,
)


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


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


@app.middleware("http")
async def runtime_headers(request: Request, call_next):
    incoming_token = request.cookies.get(SESSION_COOKIE)
    token, session = AUTH_STORE.ensure_session(incoming_token)
    request.state.auth_token = token
    request.state.auth_session = session
    response = await call_next(request)
    final_token = request.state.auth_token
    if final_token != incoming_token:
        cookie = SITE_BACKEND.session_cookie
        response.set_cookie(
            str(cookie["name"]),
            final_token,
            httponly=bool(cookie["httponly"]),
            samesite=str(cookie["samesite"]),
            secure=bool(cookie["secure"]),
            path=str(cookie["path"]),
            max_age=3600,
        )
    response.headers["Content-Security-Policy"] = (
        "default-src 'self'; img-src 'self' data:; style-src 'self'; "
        "script-src 'self'; connect-src 'self'; font-src 'self'; "
        "object-src 'none'; frame-ancestors 'none'; base-uri 'self'; "
        "form-action 'self'"
    )
    response.headers["Referrer-Policy"] = "no-referrer"
    response.headers["X-Content-Type-Options"] = "nosniff"
    response.headers["X-WebsiteBench-Site"] = SITE_ID
    response.headers["X-WebsiteBench-Version"] = VERSION
    return response


def current_account(request: Request) -> dict[str, str] | None:
    """Resolve the opaque server session to its durable business subject."""
    session = getattr(request.state, "auth_session", None)
    auth_account = session.get("account") if session else None
    if not auth_account:
        return None
    return db.get_account(str(auth_account["subject_id"]))


def signed_in(request: Request) -> bool:
    return current_account(request) is not None


def fixture_context(request: Request, **values: object) -> dict[str, object]:
    account = current_account(request)
    context: dict[str, object] = {
        "request": request,
        "site_id": SITE_ID,
        "version": VERSION,
        "fixture_id": FIXTURE_ID,
        "frozen_clock": FROZEN_CLOCK,
        "frozen_date": FROZEN_DATE,
        "signed_in": account is not None,
        "owner_name": account["name"] if account else OWNER_NAME,
        "owner_email": OWNER_EMAIL,
        "csrf": CSRF_VALUE,
        "draft_version": DRAFT_VERSION,
        "helper_disclosure": HELPER_DISCLOSURE,
        "local_only_label": LOCAL_ONLY_LABEL,
        "current_path": request.url.path,
        "title_min": TITLE_MIN,
        "title_max": TITLE_MAX,
        "target_min": TARGET_MIN,
        "target_max": TARGET_MAX,
        "body_min": BODY_MIN,
        "body_max": BODY_MAX,
        "update_min": UPDATE_MIN,
        "update_max": UPDATE_MAX,
        "publish_idempotency_key": PUBLISH_IDEMPOTENCY_KEY,
        "form_target_type": "organization",
        "form_target_location": "",
        "form_contact_label": "Decision maker",
    }
    context.update(values)
    return context


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,
    )


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}


async def api_values(request: Request) -> dict[str, object]:
    """Accept a small JSON object or the existing URL-encoded form shape."""
    content_type = request.headers.get("content-type", "").casefold()
    if "application/json" in content_type:
        try:
            payload = json.loads(await request.body())
        except (UnicodeDecodeError, json.JSONDecodeError):
            raise RepositoryError(
                "invalid-json", "request body must be valid JSON", status=400
            )
        if not isinstance(payload, dict):
            raise RepositoryError(
                "invalid-json", "request body must be a JSON object", status=400
            )
        return payload
    return dict(await urlencoded_form(request))


def api_account(request: Request) -> dict[str, str]:
    account = current_account(request)
    if account is None:
        raise RepositoryError(
            "authentication-required", "sign in to continue", status=401
        )
    return account


def require_api_csrf(
    request: Request, values: dict[str, object] | None = None
) -> None:
    supplied = request.headers.get("X-CSRF-Token", "")
    if not supplied and values is not None:
        supplied = str(values.get("csrf", ""))
    if not hmac.compare_digest(supplied, CSRF_VALUE):
        raise RepositoryError(
            "invalid-csrf", "request CSRF token is invalid", status=403
        )


def repository_error_response(error: RepositoryError) -> JSONResponse:
    return JSONResponse(
        {"ok": False, "error": error.code, "message": str(error)},
        status_code=error.status,
    )


def safe_next(value: str | None) -> str:
    candidate = str(value or "").strip()
    if not candidate or any(ord(character) < 32 for character in candidate):
        return "/"
    decoded = urllib.parse.unquote(candidate)
    if (
        not candidate.startswith("/")
        or candidate.startswith("//")
        or decoded.startswith("//")
        or "\\" in candidate
        or "\\" in decoded
    ):
        return "/"
    parsed = urllib.parse.urlsplit(candidate)
    if parsed.scheme or parsed.netloc or not parsed.path.startswith("/"):
        return "/"
    if urllib.parse.urlsplit(decoded).netloc:
        return "/"
    return urllib.parse.urlunsplit(
        ("", "", parsed.path, parsed.query, parsed.fragment)
    )


def auth_ui_key(session_token: str, purpose: str) -> tuple[str, str]:
    digest = hashlib.sha256(session_token.encode("utf-8")).hexdigest()
    return digest, purpose


def set_auth_ui_state(session_token: str, purpose: str, state: str) -> None:
    if state not in {
        "pending", "sent", "failed", "retry", "expired", "recovered"
    }:
        raise ValueError("unknown authentication UI state")
    if len(AUTH_UI_STATES) >= 512:
        AUTH_UI_STATES.clear()
    AUTH_UI_STATES[auth_ui_key(session_token, purpose)] = state


def auth_ui_state(session_token: str, purpose: str) -> str:
    flow = AUTH_STORE.session_flow_status(session_token, purpose=purpose)
    if flow.get("state") in {"stale", "locked"}:
        return "expired"
    if flow.get("state") == "verified":
        return "recovered"
    explicit = AUTH_UI_STATES.get(auth_ui_key(session_token, purpose))
    if explicit in {"failed", "retry", "expired", "recovered"}:
        return explicit
    mail = AUTH_STORE.session_mail_state(session_token, purpose=purpose)
    if mail is not None:
        status = str(mail.get("status", ""))
        if status in {"LOCAL_ONLY", "SMTP_SENT"}:
            return "sent"
        if status == "SMTP_FAILED":
            return "retry" if bool(mail.get("retryable")) else "failed"
        if status in {"SMTP_PENDING", "OUTCOME_UNKNOWN"}:
            return "pending"
    if flow.get("state") == "challenge":
        # Cleartext codes never survive a process restart, so startup removes
        # the replayable outbox row while retaining the hash-only challenge.
        # The message was already issued; keep that durable public state.
        return "sent"
    return explicit or "pending"


def mark_auth_delivery_success(session_token: str, purpose: str) -> str:
    prior = AUTH_UI_STATES.get(auth_ui_key(session_token, purpose))
    state = (
        "recovered"
        if prior in {"failed", "retry", "expired"}
        else "sent"
    )
    set_auth_ui_state(session_token, purpose, state)
    return state


def auth_ui_view(session_token: str, purpose: str) -> dict[str, object]:
    state = auth_ui_state(session_token, purpose)
    content = {
        "pending": (
            "Pending",
            "No local verification message has been stored yet.",
            False,
        ),
        "sent": (
            "Sent",
            "The verification message is available in this local inbox.",
            False,
        ),
        "failed": (
            "Failed",
            "The local message could not be prepared. You can try again.",
            True,
        ),
        "retry": (
            "Retry",
            "Please wait, then request another local verification message.",
            True,
        ),
        "expired": (
            "Expired",
            "This verification challenge has expired. Request a new one.",
            True,
        ),
        "recovered": (
            "Recovered",
            "The local delivery flow recovered successfully.",
            False,
        ),
    }
    label, detail, can_retry = content[state]
    return {
        "state": state,
        "label": label,
        "detail": detail,
        "can_retry": can_retry,
    }


def normalize_single_line(value: str) -> str:
    """NFKC-normalize, trim, and collapse all whitespace to one space."""
    normalized = unicodedata.normalize("NFKC", value)
    return re.sub(r"\s+", " ", normalized).strip()


def normalize_multiline(value: str) -> str:
    """NFKC-normalize line endings and whitespace while preserving paragraphs."""
    normalized = unicodedata.normalize("NFKC", value)
    normalized = normalized.replace("\r\n", "\n").replace("\r", "\n")
    lines = [re.sub(r"[^\S\n]+", " ", line).strip() for line in normalized.split("\n")]
    while lines and not lines[0]:
        lines.pop(0)
    while lines and not lines[-1]:
        lines.pop()
    return "\n".join(lines)


def petition_slug(topic: str, title: str) -> str:
    """Return a deterministic server-owned slug for arbitrary legal content."""
    del title  # Title edits never rebind the generic topic identity.
    normalized_topic = normalize_single_line(topic)
    ascii_topic = unicodedata.normalize("NFKD", normalized_topic).encode(
        "ascii", "ignore"
    ).decode("ascii")
    base = re.sub(r"[^a-z0-9]+", "-", ascii_topic.casefold()).strip("-")
    base = (base or "petition")[:72].rstrip("-")
    topic_digest = hashlib.sha256(
        normalized_topic.encode("utf-8")
    ).hexdigest()[:10]
    return f"{base}-{topic_digest}"


def assisted_template(topic: str, location: str) -> dict[str, str]:
    """Build disclosed deterministic helper text without an AI or task lookup."""
    normalized_topic = normalize_single_line(topic)
    normalized_location = normalize_single_line(location)
    return {
        "id": normalized_topic,
        "label": normalized_topic,
        "location": normalized_location,
        "template_title": normalized_topic,
        "template_target": (
            f"Relevant decision maker for {normalized_location}"
        )[:TARGET_MAX],
        "template_body": (
            f"We ask the relevant decision maker for {normalized_location} "
            f"to act on this request: {normalized_topic}. This first draft "
            "is a starting point; edit it to describe the "
            "requested change and why it matters."
        ),
    }


def _validate_topic_location(
    topic: str, location: str | None = None
) -> list[str]:
    errors: list[str] = []
    if len(topic) < TOPIC_MIN:
        errors.append("Petition topic is required.")
    elif len(topic) > TOPIC_MAX:
        errors.append(
            f"Petition topic must be at most {TOPIC_MAX} characters "
            f"(got {len(topic)})."
        )
    if location is not None:
        if len(location) < LOCATION_MIN:
            errors.append("Petition location is required.")
        elif len(location) > LOCATION_MAX:
            errors.append(
                f"Petition location must be at most {LOCATION_MAX} characters "
                f"(got {len(location)})."
            )
    return errors


def request_fingerprint(*parts: str) -> str:
    framed = "\x1f".join(f"{len(part)}:{part}" for part in parts)
    return hashlib.sha256(framed.encode("utf-8")).hexdigest()


def valid_idempotency_key(value: str) -> bool:
    return (
        1 <= len(value) <= IDEMPOTENCY_KEY_MAX
        and re.fullmatch(r"[A-Za-z0-9._:-]+", value) is not None
    )


def comment_idempotency_key(
    slug: str, account_id: str, petition_version: int
) -> str:
    """Return the stable command key rendered for one comment form version."""
    digest = request_fingerprint(
        "petition-comment", slug, account_id, str(petition_version)
    )
    return f"comment:{digest[:32]}"


def signature_idempotency_key(
    slug: str, account_id: str, petition_version: int
) -> str:
    """Return the stable command key rendered for one signature form version."""
    digest = request_fingerprint(
        "petition-signature", slug, account_id, str(petition_version)
    )
    return f"signature:{digest[:32]}"


def login_redirect(next_path: str) -> RedirectResponse:
    return RedirectResponse(
        f"/login_or_join?next={quote(next_path, safe='')}"
        "&reason=unauthorized",
        status_code=303,
    )


def refusal(
    request: Request,
    *,
    status_code: int,
    reason_title: str,
    reason_body: str,
    **extra: object,
) -> HTMLResponse:
    return render(
        request,
        "refused.html",
        status_code=status_code,
        page_title="Request refused",
        reason_title=reason_title,
        reason_body=reason_body,
        **extra,
    )


# ---------------------------------------------------------------------------
# Health, reset, and boundary endpoints
# ---------------------------------------------------------------------------


@app.get("/healthz")
async def healthz() -> JSONResponse:
    return JSONResponse(
        {
            "ok": True,
            "status": "ok",
            "site_id": SITE_ID,
            "stage": STAGE,
            "version": VERSION,
            "fixture_id": FIXTURE_ID,
            "frozen_clock": FROZEN_CLOCK,
            "persistent_backend": True,
            "repository_profile": os.environ.get(
                "WEBSITEBENCH_CHANGE_REPOSITORY_PROFILE", "sqlite"
            ),
            "remote_runtime": 0,
            "db": db.db_info(),
        },
        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:
    supplied = request.headers.get(ADMIN_TOKEN_HEADER, "")
    if not hmac.compare_digest(supplied, ADMIN_TOKEN):
        return JSONResponse(
            {"ok": False, "error": "invalid admin token; state unchanged"},
            status_code=403,
        )
    counts = reset_site_to_seed()
    return JSONResponse(
        {
            "ok": True,
            "reset": True,
            "site_id": SITE_ID,
            "frozen_clock": FROZEN_CLOCK,
            "counts": counts,
        }
    )


# ---------------------------------------------------------------------------
# Home, browse, search
# ---------------------------------------------------------------------------


@app.get("/", response_class=HTMLResponse)
async def home(request: Request, signed_out: str = "") -> HTMLResponse:
    return render(
        request,
        "home.html",
        page_title="Change starts here",
        trending_stories=TRENDING_STORIES,
        home_chips=HOME_CHIPS,
        home_local_cards=HOME_LOCAL_CARDS,
        just_signed_out=(signed_out == "1"),
        page_class="page-home",
    )


@app.get("/browse")
async def browse_deprecated() -> RedirectResponse:
    return RedirectResponse(
        "/search?redirect_reason=deprecated-page", status_code=307
    )


@app.get("/browse-petitions", response_class=HTMLResponse)
async def browse_petitions(request: Request) -> HTMLResponse:
    return render(
        request,
        "browse.html",
        page_title="Discover your next cause",
        browse_cards=BROWSE_CARDS,
    )


@app.get("/local", response_class=HTMLResponse)
async def local_petitions(request: Request) -> HTMLResponse:
    return render(
        request,
        "info_page.html",
        page_title="Petitions near you",
        page_class="info-page-shell local-petitions-page",
        info={
            "eyebrow": "Change near you",
            "title": "Discover petitions in your community",
            "intro": (
                "Find people taking action on the issues that matter where "
                "you live, then add your voice or start something new."
            ),
            "sections": [
                {
                    "title": "Explore local causes",
                    "body": "Browse active petitions and community campaigns.",
                    "href": "/search?source_location=local_page",
                    "link": "Search petitions",
                },
                {
                    "title": "Browse by issue",
                    "body": "See campaigns grouped by the topics you care about.",
                    "href": "/topic?source_location=local_page",
                    "link": "Browse topics",
                },
                {
                    "title": "Lead change locally",
                    "body": "Create a petition and invite your community to join.",
                    "href": "/start-a-petition/intro?source_location=local_page",
                    "link": "Start a petition",
                },
            ],
        },
    )


@app.get("/nonprofit", response_class=HTMLResponse)
async def nonprofit_page(request: Request) -> HTMLResponse:
    return render(
        request,
        "info_page.html",
        page_title="Change.org for nonprofits",
        page_class="info-page-shell nonprofit-page",
        info={
            "eyebrow": "For nonprofits",
            "title": "Mobilize supporters around your mission",
            "intro": (
                "Use Change.org's campaign tools to tell your story, build "
                "momentum, and reach the people who can make a difference."
            ),
            "sections": [
                {
                    "title": "Launch a campaign",
                    "body": "Turn a clear goal into a petition people can support.",
                    "href": "/start-a-petition/intro?source_location=nonprofit_page",
                    "link": "Start a petition",
                },
                {
                    "title": "Build your audience",
                    "body": "Learn how to share your petition and collect signatures.",
                    "href": "/petition-guides/share-your-petition?source_location=nonprofit_page",
                    "link": "Read the guide",
                },
                {
                    "title": "Show what is possible",
                    "body": "Explore campaigns that turned public support into impact.",
                    "href": "/impact?source_location=nonprofit_page",
                    "link": "See the impact",
                },
            ],
        },
    )


@app.get("/search", response_class=HTMLResponse)
async def search(
    request: Request,
    q: str = "",
    state: str = "results",
    redirect_reason: str = "",
    topic: str = "",
    topics: str = "",
    location: str = "",
    organization: str = "",
    filter_status: str = "",
    sort: str = "recent-activity",
    page: int = 1,
) -> HTMLResponse:
    normalized = (
        state if state in {"results", "loading", "empty", "error"} else "results"
    )
    query = q.strip()
    selected_topic = topic.strip() or urllib.parse.unquote(topics.strip())
    plural_topic_filter = bool(topics.strip())
    is_landing = (
        not query
        and not selected_topic
        and not location
        and not organization
        and not filter_status
        and normalized == "results"
        and redirect_reason != "deprecated-page"
    )
    local_results: list[dict[str, object]] = []
    frozen_results: list[dict[str, str]] = []
    frozen_display_query = FROZEN_SEARCH_QUERY
    frozen_display_count = FROZEN_SEARCH_COUNT
    if normalized == "results" and not is_landing:
        needle = query.casefold()
        search_result = await repository.execute(
            "search.petitions",
            {"query": query, "topic": selected_topic, "location": location,
             "organization": organization, "status": filter_status,
             "limit": 50},
        )
        for item in search_result["items"]:
            petition = db.get_petition(str(item["slug"]))
            if petition is not None:
                local_results.append(petition)
        if needle and CLIMATE_SEARCH_QUERY in needle:
            frozen_results = [dict(item) for item in CLIMATE_SEARCH_RESULTS]
            frozen_display_query = CLIMATE_SEARCH_QUERY
            frozen_display_count = CLIMATE_SEARCH_COUNT
        elif needle and FROZEN_SEARCH_QUERY in needle:
            frozen_results = [dict(item) for item in FROZEN_SEARCH_RESULTS]
        if sort == "most-signatures":
            frozen_results.sort(
                key=lambda item: int(item["signatures"].replace(",", "")),
                reverse=True,
            )
            local_results.sort(
                key=lambda item: int(item.get("signatures", 0)),
                reverse=True,
            )
        elif sort == "least-signatures":
            frozen_results.sort(
                key=lambda item: int(item["signatures"].replace(",", ""))
            )
            local_results.sort(
                key=lambda item: int(item.get("signatures", 0))
            )
        elif sort == "newest":
            frozen_results = list(reversed(frozen_results))
            local_results = list(reversed(local_results))
        if not local_results and not frozen_results and not plural_topic_filter:
            normalized = "empty"
    page = max(1, min(page, 1503 if frozen_results else 1))
    # Offer only the facets that lead somewhere. Skipped on the landing state,
    # which shows its own topic entry points rather than result filters.
    topic_facets: list[str] = []
    if not is_landing and normalized == "results":
        topic_facets = await available_search_topics(
            query,
            location=location,
            organization=organization,
            filter_status=filter_status,
            page_already_has_results=bool(frozen_results),
        )
    return render(
        request,
        "search.html",
        page_title="Search",
        page_class="search-page-shell",
        query=query,
        is_landing=is_landing,
        topic_facets=topic_facets,
        search_landing_topics=SEARCH_LANDING_TOPICS,
        search_landing_topic_options=[
            {
                "label": landing_topic,
                "href": (
                    "/search?topics="
                    + urllib.parse.quote(
                        urllib.parse.quote(landing_topic, safe=""),
                        safe="",
                    )
                ),
            }
            for landing_topic in SEARCH_LANDING_TOPICS
        ],
        state=normalized,
        local_results=local_results,
        frozen_results=frozen_results,
        frozen_search_query=frozen_display_query,
        frozen_search_count=frozen_display_count,
        search_filters={"topic": selected_topic, "location": location,
                        "organization": organization,
                        "status": filter_status},
        search_sort=sort,
        search_page=page,
        search_page_count=(1503 if frozen_results else 1),
        deprecated_redirect=(redirect_reason == "deprecated-page"),
    )


# ---------------------------------------------------------------------------
# Frozen public navigation depth 2
# ---------------------------------------------------------------------------


@app.get("/topic", response_class=HTMLResponse)
async def topic_directory(request: Request) -> HTMLResponse:
    return render(
        request,
        "topics.html",
        page_title="Browse by Topic",
        page_class="topic-directory-page",
        alphabet=list("ABCDEFGHIJKLMNOPQRSTUVWXYZ"),
        topics=SOURCE_TOPIC_PAGES,
        curated_topics=curated_topic_links(),
    )


@app.get("/topic/{slug}", response_class=HTMLResponse)
async def topic_page(request: Request, slug: str) -> HTMLResponse:
    topic = next(
        (
            item
            for item in [*SOURCE_TOPIC_PAGES, *SOURCE_TOPIC_DIRECTORY, *TOPICS]
            if item["slug"] == slug
        ),
        None,
    )
    if topic is None:
        return render(
            request,
            "not_found.html",
            page_title="Page not found",
            status_code=404,
        )
    cards = [
        {**card, "signatures": card["signatures"]}
        for card in HOME_LOCAL_CARDS[:4]
    ]
    return render(
        request,
        "topic_detail.html",
        page_title=f"{topic['title']} petitions",
        page_class="topic-detail-page",
        topic={**topic, "cards": cards},
    )


@app.get("/petition-guides", response_class=HTMLResponse)
async def petition_guides(request: Request) -> HTMLResponse:
    return render(
        request,
        "guides.html",
        page_title="Change.org petition guide",
        page_class="petition-guides-page",
        guide_sections=GUIDE_SECTIONS,
    )


@app.get("/petition-guides/{slug}", response_class=HTMLResponse)
async def petition_guide_detail(request: Request, slug: str) -> HTMLResponse:
    guide = GUIDE_ARTICLES.get(slug)
    if guide is None:
        return render(
            request,
            "not_found.html",
            page_title="Page not found",
            status_code=404,
        )
    return render(
        request,
        "guide_detail.html",
        page_title=str(guide["title"]),
        page_class="petition-guide-article-page",
        guide=guide,
    )


@app.get("/about", response_class=HTMLResponse)
async def about_page(request: Request) -> HTMLResponse:
    return render(
        request,
        "brand_page.html",
        page_title="Learn More About The Change.org Mission",
        page_class="about-page",
        brand_kind="about",
        heading="The world’s platform for change",
    )


@app.get("/impact", response_class=HTMLResponse)
async def impact_page(request: Request) -> HTMLResponse:
    return render(
        request,
        "brand_page.html",
        page_title="What Impact Has Change.org Made",
        page_class="impact-page",
        brand_kind="impact",
        heading="The power of your voice",
        impact_avatars=IMPACT_AVATARS,
        victories=VICTORIES,
        impact_tail_petitions=impact_tail_petitions(),
    )


@app.get("/about/team", response_class=HTMLResponse)
async def team_page(request: Request) -> HTMLResponse:
    return render(
        request,
        "brand_page.html",
        page_title="Meet Our Team",
        page_class="team-page",
        brand_kind="team",
        heading="Our Global Team",
        team=TEAM_MEMBERS,
        management_team=TEAM_MEMBERS[:12],
        global_team=TEAM_MEMBERS[12:28],
    )


@app.get("/press", response_class=HTMLResponse)
@app.get("/l/us/p/press", response_class=HTMLResponse)
async def press_page(request: Request) -> HTMLResponse:
    return render(
        request,
        "press_page.html",
        page_title="Press",
        page_class="press-page",
    )


@app.get("/l/us", response_class=HTMLResponse)
async def blog_boundary(request: Request) -> HTMLResponse:
    return render(
        request,
        "info_page.html",
        page_title="Change.org Blog",
        page_class="info-page-shell blog-page",
        info={
            "eyebrow": "Change.org Blog",
            "title": "Stories, ideas, and tools for change",
            "intro": (
                "Read about people building movements, winning campaigns, "
                "and helping their communities move forward."
            ),
            "sections": [
                {
                    "title": "Victory stories",
                    "body": "See how supporters and decision makers found solutions.",
                    "href": "/impact?source_location=blog",
                    "link": "Explore impact",
                },
                {
                    "title": "Campaign guides",
                    "body": "Practical guidance for every stage of a petition.",
                    "href": "/petition-guides?source_location=blog",
                    "link": "Read the guides",
                },
                {
                    "title": "Community action",
                    "body": "Discover petitions and causes growing near you.",
                    "href": "/local?source_location=blog",
                    "link": "Browse local petitions",
                },
            ],
        },
    )


@app.get("/policies/{slug}", response_class=HTMLResponse)
async def policy_page(request: Request, slug: str) -> HTMLResponse:
    policy = POLICIES.get(slug)
    if policy is None:
        return render(
            request,
            "not_found.html",
            page_title="Page not found",
            status_code=404,
        )
    return render(
        request,
        "policy.html",
        page_title=str(policy["title"]),
        page_class="policy-document-page",
        policy=policy,
    )


COOKIE_PREFERENCES_COOKIE = "change_cookie_preferences"


def cookie_preferences(request: Request) -> dict[str, bool]:
    defaults = {
        "analytics": True,
        "personalization": True,
        "advertising": True,
    }
    encoded = request.cookies.get(COOKIE_PREFERENCES_COOKIE)
    if not encoded:
        return defaults
    try:
        values = json.loads(encoded)
    except json.JSONDecodeError:
        return defaults
    if not isinstance(values, dict):
        return defaults
    return {key: values.get(key) is True for key in defaults}


@app.get("/account_settings/manage_cookies", response_class=HTMLResponse)
async def manage_cookies(
    request: Request, saved: str = ""
) -> HTMLResponse:
    return render(
        request,
        "manage_cookies.html",
        page_title="Manage cookies",
        page_class="manage-cookies",
        preferences=cookie_preferences(request),
        saved=(saved == "1"),
    )


@app.post("/account_settings/manage_cookies")
async def save_cookie_preferences(request: Request):
    values = await urlencoded_form(request)
    if not hmac.compare_digest(values.get("csrf", ""), CSRF_VALUE):
        return render(
            request,
            "manage_cookies.html",
            page_title="Manage cookies",
            page_class="manage-cookies",
            preferences=cookie_preferences(request),
            saved=False,
            status_code=403,
        )
    preferences = {
        "analytics": values.get("analytics") == "on",
        "personalization": values.get("personalization") == "on",
        "advertising": values.get("advertising") == "on",
    }
    response = RedirectResponse(
        "/account_settings/manage_cookies?saved=1", status_code=303
    )
    response.set_cookie(
        COOKIE_PREFERENCES_COOKIE,
        json.dumps(preferences, separators=(",", ":"), sort_keys=True),
        max_age=365 * 24 * 60 * 60,
        httponly=False,
        samesite="lax",
        secure=False,
        path="/",
    )
    return response


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


# ---------------------------------------------------------------------------
# Membership and contribution payments
# ---------------------------------------------------------------------------


def payment_owner(request: Request) -> tuple[str, str | None]:
    account = current_account(request)
    if account is not None:
        return str(account["id"]), str(account["id"])
    token = str(getattr(request.state, "auth_token", "guest"))
    digest = hashlib.sha256(token.encode("utf-8")).hexdigest()[:32]
    return f"guest:{digest}", None


def payment_form_key(request: Request, payment_kind: str) -> str:
    owner, _account_id = payment_owner(request)
    with closing(db.connect()) as connection:
        row = connection.execute(
            "SELECT COUNT(*) AS n FROM websitebench_payment_flows "
            "WHERE site_id=? AND owner=?",
            (SITE_ID, owner),
        ).fetchone()
        ordinal = int(row["n"]) + 1
    digest = hashlib.sha256(
        f"{owner}\x1f{payment_kind}\x1f{ordinal}".encode("utf-8")
    ).hexdigest()[:24]
    return f"change-payment:{payment_kind}:{digest}"


def parse_payment_amount(values: dict[str, str]) -> int:
    raw = values.get("custom_amount", "").strip() or values.get("amount", "")
    try:
        amount = Decimal(raw).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
    except (InvalidOperation, ValueError):
        raise PaymentError("Choose a valid contribution amount.")
    if amount < Decimal("1.00") or amount > Decimal("10000.00"):
        raise PaymentError("Amount must be between $1 and $10,000 CAD.")
    return int(amount * 100)


def payment_page_values(
    request: Request,
    payment_kind: str,
    *,
    payment_result: dict[str, str] | None = None,
) -> dict[str, object]:
    if payment_kind == "membership":
        heading = "Power change every month"
        copy = (
            "Members provide dependable monthly support that keeps Change.org "
            "free, open, and available to petition starters everywhere."
        )
        amounts = [5, 10, 20]
    else:
        heading = "Help people create change"
        copy = (
            "Your contribution supports the tools and guidance people use to "
            "start petitions, find supporters, and reach Decision Makers."
        )
        amounts = [10, 25, 50]
    return {
        "page_title": (
            "Become a member"
            if payment_kind == "membership"
            else "Contribute to Change.org"
        ),
        "page_class": "change-payment-page",
        "payment_kind": payment_kind,
        "payment_heading": heading,
        "payment_copy": copy,
        "amounts": amounts,
        "action": "/payments/local",
        "payment_form_key": payment_form_key(request, payment_kind),
        "payment_result": payment_result,
    }


def existing_payment_record(
    connection: sqlite3.Connection, flow_id: str
) -> dict[str, str] | None:
    for table, kind in (
        ("memberships", "membership"),
        ("contributions", "contribution"),
    ):
        row = connection.execute(
            f"SELECT id,status,payment_flow_id FROM {table} "
            "WHERE payment_flow_id=?",
            (flow_id,),
        ).fetchone()
        if row is not None:
            return {
                "id": str(row["id"]),
                "status": str(row["status"]),
                "payment_kind": kind,
                "flow_id": str(row["payment_flow_id"]),
            }
    return None


def consume_and_record_payment(
    connection: sqlite3.Connection,
    *,
    payment_kind: str,
    owner: str,
    account_id: str | None,
    amount_minor: int,
    fingerprint: str,
    flow_id: str,
) -> dict[str, str]:
    existing = existing_payment_record(connection, flow_id)
    if existing is not None:
        return existing
    consumed = SITE_BACKEND.payments.consume_approval(
        connection,
        flow_id=flow_id,
        owner=owner,
        amount_minor=amount_minor,
        currency="CAD",
        fingerprint=fingerprint,
    )
    attempt_id = str(consumed["attempt_id"])
    record_id = (
        f"{payment_kind}-"
        + hashlib.sha256(flow_id.encode("utf-8")).hexdigest()[:24]
    )
    if payment_kind == "membership":
        connection.execute(
            "INSERT INTO memberships("
            "id,owner_key,account_id,amount_minor,currency,status,"
            "payment_flow_id,payment_attempt_id,row_version,created_at,updated_at"
            ") VALUES (?,?,?,?,?,'active',?,?,1,?,?)",
            (
                record_id,
                owner,
                account_id,
                amount_minor,
                "CAD",
                flow_id,
                attempt_id,
                FROZEN_CLOCK,
                FROZEN_CLOCK,
            ),
        )
        status = "active"
    else:
        connection.execute(
            "INSERT INTO contributions("
            "id,owner_key,account_id,amount_minor,currency,status,"
            "payment_flow_id,payment_attempt_id,created_at"
            ") VALUES (?,?,?,?,?,'completed',?,?,?)",
            (
                record_id,
                owner,
                account_id,
                amount_minor,
                "CAD",
                flow_id,
                attempt_id,
                FROZEN_CLOCK,
            ),
        )
        status = "completed"
    return {
        "id": record_id,
        "status": status,
        "payment_kind": payment_kind,
        "flow_id": flow_id,
    }


@app.get("/member", response_class=HTMLResponse)
async def membership_page(request: Request) -> HTMLResponse:
    return render(
        request,
        "payment.html",
        **payment_page_values(request, "membership"),
    )


@app.get("/member/join", response_class=HTMLResponse)
async def membership_join_source_boundary() -> HTMLResponse:
    return HTMLResponse(
        "<!doctype html><html lang=\"en-CA\"><head>"
        "<meta charset=\"utf-8\"><meta name=\"viewport\" "
        "content=\"width=device-width, initial-scale=1\">"
        "<title>Change.org</title>"
        "<link rel=\"stylesheet\" href=\"/static/styles.css?v=20260803-cycle9\">"
        "</head><body class=\"member-join-loading-page\">"
        "<main class=\"member-join-loading\" aria-live=\"polite\">"
        "<span class=\"member-join-status-text\">Loading membership</span>"
        "<span class=\"member-join-spinner\" role=\"status\" "
        "aria-label=\"Loading membership\"></span>"
        "</main></body></html>"
    )


@app.get("/membership")
async def membership_alias() -> RedirectResponse:
    return RedirectResponse("/member", status_code=307)


@app.get("/contribute", response_class=HTMLResponse)
async def contribution_page(request: Request) -> HTMLResponse:
    return render(
        request,
        "payment.html",
        **payment_page_values(request, "contribution"),
    )


@app.post("/payments/local", response_class=HTMLResponse)
async def local_payment(request: Request) -> HTMLResponse:
    values = await urlencoded_form(request)
    payment_kind = values.get("payment_kind", "")
    if payment_kind not in {"membership", "contribution"}:
        payment_kind = "contribution"
    result: dict[str, str]
    status_code = 200
    try:
        if not hmac.compare_digest(values.get("csrf", ""), CSRF_VALUE):
            raise PaymentRejected("Your form expired. Refresh and try again.")
        amount_minor = parse_payment_amount(values)
        scenario = values.get("scenario", "sandbox-card-approved")
        if scenario not in {
            "sandbox-card-approved",
            "sandbox-card-declined",
            "sandbox-retry",
        }:
            raise PaymentRejected("Choose a valid local payment outcome.")
        create_key = values.get("idempotency_key", "")
        if not create_key.startswith(f"change-payment:{payment_kind}:"):
            raise PaymentRejected("Your form expired. Refresh and try again.")
        owner, account_id = payment_owner(request)
        fingerprint = hashlib.sha256(
            f"{payment_kind}\x1f{amount_minor}\x1fCAD".encode("utf-8")
        ).hexdigest()
        attempt_key = (
            "change-attempt:"
            + hashlib.sha256(
                f"{create_key}\x1f{scenario}".encode("utf-8")
            ).hexdigest()[:32]
        )
        with closing(db.connect()) as connection:
            connection.execute("BEGIN IMMEDIATE")
            flow = SITE_BACKEND.payments.create_intent(
                owner=owner,
                amount_minor=amount_minor,
                currency="CAD",
                fingerprint=fingerprint,
                idempotency_key=create_key,
                adapter="local-sandbox",
                connection=connection,
            )
            flow_id = str(flow["flow_id"])
            recorded = existing_payment_record(connection, flow_id)
            if flow["status"] == "CONSUMED" and recorded is not None:
                # A browser retry after the approval and business write must
                # reproduce the successful result without attempting to
                # reopen the terminal shared payment flow.
                attempt_status = "APPROVED"
            else:
                attempt = SITE_BACKEND.payments.attempt(
                    flow_id=flow_id,
                    owner=owner,
                    amount_minor=amount_minor,
                    currency="CAD",
                    fingerprint=fingerprint,
                    scenario_id=scenario,
                    idempotency_key=attempt_key,
                    connection=connection,
                )
                attempt_status = str(attempt["status"])
            if attempt_status == "APPROVED" and recorded is None:
                consume_and_record_payment(
                    connection,
                    payment_kind=payment_kind,
                    owner=owner,
                    account_id=account_id,
                    amount_minor=amount_minor,
                    fingerprint=fingerprint,
                    flow_id=flow_id,
                )
            connection.commit()
        if attempt_status == "APPROVED":
            result = {
                "status": "approved",
                "title": (
                    "You’re a Change.org member"
                    if payment_kind == "membership"
                    else "Thank you for contributing"
                ),
                "message": (
                    "Your local sandbox payment was approved. No real charge occurred."
                ),
            }
        elif attempt_status == "DECLINED":
            result = {
                "status": "declined",
                "title": "Payment declined",
                "message": (
                    "The simulated issuer declined this payment. Choose another "
                    "outcome and try again."
                ),
            }
        else:
            result = {
                "status": "retryable",
                "title": "Please try again",
                "message": (
                    "The simulated payment could not be completed yet. Your "
                    "membership or contribution was not created."
                ),
            }
    except (PaymentError, PaymentConflict, PaymentRejected) as error:
        status_code = 422
        result = {
            "status": "declined",
            "title": "We couldn’t complete that payment",
            "message": str(error),
        }
    return render(
        request,
        "payment.html",
        status_code=status_code,
        **payment_page_values(
            request, payment_kind, payment_result=result
        ),
    )


def stripe_test_credentials() -> tuple[str, str]:
    payments = PAYMENT_RUNTIME["payments"]
    if not payments.get("enabled", True) or payments["stripe_test"] is None:
        raise PaymentRejected("Payments are not enabled for this site.")
    adapter = (
        os.environ.get("WEBSITEBENCH_CHANGE_PAYMENT_ADAPTER")
        or str(payments["default_adapter"])
    )
    if adapter != "stripe-test":
        raise PaymentRejected("Stripe test mode is not enabled.")
    secret_key = os.environ.get("STRIPE_TEST_SECRET_KEY", "")
    webhook_secret = os.environ.get("STRIPE_TEST_WEBHOOK_SECRET", "")
    # Keep live-key signatures out of the shipped candidate bytes while still
    # rejecting them if a deployment environment supplies one.
    if secret_key.startswith(("sk_" + "live_", "rk_" + "live_")):
        raise PaymentRejected("Live Stripe keys are never accepted.")
    if not secret_key.startswith("sk_test_"):
        raise PaymentRejected("Stripe test mode requires an sk_test_ key.")
    if not webhook_secret.startswith("whsec_"):
        raise PaymentRejected(
            "Stripe test mode requires a dedicated webhook secret."
        )
    return secret_key, webhook_secret


def require_stripe_public_request(
    request: Request, expected_path: str
) -> None:
    """Bind Stripe-test callbacks and checkout creation to the frozen origin."""
    stripe_runtime = PAYMENT_RUNTIME["payments"]["stripe_test"]
    configured = urllib.parse.urlsplit(str(stripe_runtime["public_origin"]))
    actual_host = request.headers.get("host", "")
    if (
        configured.scheme != "https"
        or not configured.hostname
        or configured.username is not None
        or configured.password is not None
        or configured.path not in {"", "/"}
        or request.url.scheme.casefold() != configured.scheme
        or actual_host.casefold() != configured.netloc.casefold()
        or request.url.path != expected_path
    ):
        raise PaymentRejected(
            "Stripe test request origin or callback path is invalid."
        )


def validate_stripe_checkout_session(
    session: dict[str, object],
) -> tuple[str, str]:
    provider_session_id = str(session.get("id", ""))
    checkout_url = str(session.get("url", ""))
    parsed_url = urllib.parse.urlsplit(checkout_url)
    try:
        has_port = parsed_url.port is not None
    except ValueError as error:
        raise PaymentRejected(
            "Stripe did not create a safe test Checkout Session."
        ) from error
    if (
        not provider_session_id.startswith("cs_test_")
        or session.get("object") != "checkout.session"
        or session.get("livemode") is not False
        or parsed_url.scheme != "https"
        or parsed_url.netloc.casefold() != "checkout.stripe.com"
        or parsed_url.username is not None
        or parsed_url.password is not None
        or has_port
        or not parsed_url.path.startswith("/c/pay/")
    ):
        raise PaymentRejected(
            "Stripe did not create a safe test Checkout Session."
        )
    return provider_session_id, checkout_url


def stripe_api_request(
    method: str,
    path: str,
    secret_key: str,
    values: dict[str, str] | None = None,
) -> dict[str, object]:
    origin = "https:" + "//api." + "stripe" + ".com"
    encoded = (
        urllib.parse.urlencode(values).encode("utf-8") if values else None
    )
    request = urllib.request.Request(
        origin + path,
        data=encoded,
        method=method,
        headers={
            "Authorization": "Basic "
            + base64.b64encode((secret_key + ":").encode("ascii")).decode(
                "ascii"
            ),
            "Content-Type": "application/x-www-form-urlencoded",
        },
    )
    try:
        with urllib.request.urlopen(request, timeout=20) as response:
            payload = json.loads(response.read().decode("utf-8"))
    except (urllib.error.URLError, json.JSONDecodeError) as error:
        raise PaymentRejected("Stripe test request failed.") from error
    if not isinstance(payload, dict):
        raise PaymentRejected("Stripe test response was invalid.")
    return payload


@app.post("/api/payments/stripe/checkout")
async def create_stripe_checkout(request: Request) -> JSONResponse:
    try:
        secret_key, _webhook_secret = stripe_test_credentials()
        require_stripe_public_request(
            request, "/api/payments/stripe/checkout"
        )
        values = await api_values(request)
        require_api_csrf(request, values)
        payment_kind = str(values.get("payment_kind", "contribution"))
        if payment_kind not in {"membership", "contribution"}:
            raise PaymentRejected("payment kind is invalid")
        amount_minor = parse_payment_amount(
            {
                "amount": str(values.get("amount", "")),
                "custom_amount": str(values.get("custom_amount", "")),
            }
        )
        owner, _account_id = payment_owner(request)
        fingerprint = hashlib.sha256(
            f"{payment_kind}\x1f{amount_minor}\x1fCAD".encode("utf-8")
        ).hexdigest()
        create_key = str(values.get("idempotency_key", ""))
        with closing(db.connect()) as connection:
            connection.execute("BEGIN IMMEDIATE")
            flow = SITE_BACKEND.payments.create_intent(
                owner=owner,
                amount_minor=amount_minor,
                currency="CAD",
                fingerprint=fingerprint,
                idempotency_key=create_key,
                adapter="stripe-test",
                connection=connection,
            )
            connection.commit()
        flow_id = str(flow["flow_id"])
        metadata = {
            "site_id": SITE_ID,
            "flow_id": flow_id,
            "owner": owner,
            "amount_minor": str(amount_minor),
            "currency": "CAD",
            "fingerprint": fingerprint,
            "is_simulation": "true",
            "payment_kind": payment_kind,
        }
        provider_values = {
            "mode": (
                "subscription"
                if payment_kind == "membership"
                else "payment"
            ),
            "client_reference_id": flow_id,
            "success_url": (
                str(PAYMENT_RUNTIME["site"]["public_origin"])
                + "/payments/stripe/return?session_id={CHECKOUT_SESSION_ID}"
            ),
            "cancel_url": (
                str(PAYMENT_RUNTIME["site"]["public_origin"])
                + ("/member" if payment_kind == "membership" else "/contribute")
            ),
            "line_items[0][quantity]": "1",
            "line_items[0][price_data][currency]": "cad",
            "line_items[0][price_data][unit_amount]": str(amount_minor),
            "line_items[0][price_data][product_data][name]": (
                "Change.org Membership"
                if payment_kind == "membership"
                else "Change.org Contribution"
            ),
        }
        if payment_kind == "membership":
            provider_values[
                "line_items[0][price_data][recurring][interval]"
            ] = "month"
        for key, value in metadata.items():
            provider_values[f"metadata[{key}]"] = value
        session = await asyncio.to_thread(
            stripe_api_request,
            "POST",
            "/v1/checkout/sessions",
            secret_key,
            provider_values,
        )
        provider_session_id, checkout_url = validate_stripe_checkout_session(
            session
        )
        with closing(db.connect()) as connection:
            connection.execute(
                "INSERT OR REPLACE INTO stripe_checkout_sessions("
                "provider_session_id,payment_flow_id,owner_key,payment_kind,"
                "amount_minor,currency,fingerprint,status,created_at,updated_at"
                ") VALUES (?,?,?,?,?,'CAD',?,'created',?,?)",
                (
                    provider_session_id,
                    flow_id,
                    owner,
                    payment_kind,
                    amount_minor,
                    fingerprint,
                    FROZEN_CLOCK,
                    FROZEN_CLOCK,
                ),
            )
            connection.commit()
        return JSONResponse(
            {
                "ok": True,
                "adapter": "stripe-test",
                "checkout_url": checkout_url,
                "session_id": provider_session_id,
            },
            status_code=201,
        )
    except (PaymentError, PaymentConflict, PaymentRejected) as error:
        return JSONResponse(
            {"ok": False, "error": "stripe-test-unavailable", "message": str(error)},
            status_code=422,
        )


def finalize_stripe_session(
    snapshot: dict[str, object],
) -> dict[str, str]:
    provider_session_id = str(snapshot.get("id", ""))
    metadata = snapshot.get("metadata")
    if not isinstance(metadata, dict):
        raise PaymentRejected("Stripe test metadata is missing.")
    flow_id = str(metadata.get("flow_id", ""))
    with closing(db.connect()) as connection:
        row = connection.execute(
            "SELECT * FROM stripe_checkout_sessions "
            "WHERE provider_session_id=? AND payment_flow_id=?",
            (provider_session_id, flow_id),
        ).fetchone()
        if row is None:
            raise PaymentRejected("Stripe test Session is missing or foreign.")
        existing = existing_payment_record(connection, flow_id)
        if existing is not None:
            return existing
        connection.execute("BEGIN IMMEDIATE")
        owner = str(row["owner_key"])
        amount_minor = int(row["amount_minor"])
        fingerprint = str(row["fingerprint"])
        SITE_BACKEND.payments.attempt_verified_stripe(
            flow_id=flow_id,
            owner=owner,
            amount_minor=amount_minor,
            currency="CAD",
            fingerprint=fingerprint,
            provider_session_id=provider_session_id,
            idempotency_key=f"change-stripe:{provider_session_id}",
            provider_verifier=lambda _session_id: snapshot,
            connection=connection,
        )
        account = connection.execute(
            "SELECT id FROM accounts WHERE id=?", (owner,)
        ).fetchone()
        result = consume_and_record_payment(
            connection,
            payment_kind=str(row["payment_kind"]),
            owner=owner,
            account_id=(str(account["id"]) if account is not None else None),
            amount_minor=amount_minor,
            fingerprint=fingerprint,
            flow_id=flow_id,
        )
        connection.execute(
            "UPDATE stripe_checkout_sessions "
            "SET status='completed',updated_at=? WHERE provider_session_id=?",
            (FROZEN_CLOCK, provider_session_id),
        )
        connection.commit()
        return result


@app.get("/payments/stripe/return", response_class=HTMLResponse)
async def stripe_return(
    request: Request, session_id: str = ""
) -> HTMLResponse:
    payment_kind = "contribution"
    try:
        secret_key, _webhook_secret = stripe_test_credentials()
        require_stripe_public_request(
            request,
            str(PAYMENT_RUNTIME["payments"]["stripe_test"]["return_path"]),
        )
        if not session_id.startswith("cs_test_"):
            raise PaymentRejected("Stripe test Session id is invalid.")
        snapshot = await asyncio.to_thread(
            stripe_api_request,
            "GET",
            "/v1/checkout/sessions/" + urllib.parse.quote(session_id, safe=""),
            secret_key,
            None,
        )
        result_record = finalize_stripe_session(snapshot)
        payment_kind = result_record["payment_kind"]
        result = {
            "status": "approved",
            "title": (
                "You’re a Change.org member"
                if payment_kind == "membership"
                else "Thank you for contributing"
            ),
            "message": "Your Stripe test payment was verified by the server.",
        }
        status_code = 200
    except (PaymentError, PaymentConflict, PaymentRejected) as error:
        result = {
            "status": "declined",
            "title": "We couldn’t verify that payment",
            "message": str(error),
        }
        status_code = 422
    return render(
        request,
        "payment.html",
        status_code=status_code,
        **payment_page_values(
            request, payment_kind, payment_result=result
        ),
    )


def verify_stripe_signature(
    payload: bytes, signature_header: str, secret: str
) -> None:
    pairs: dict[str, list[str]] = {}
    for part in signature_header.split(","):
        key, separator, value = part.partition("=")
        if separator:
            pairs.setdefault(key, []).append(value)
    try:
        timestamp = int(pairs.get("t", [""])[0])
    except ValueError as error:
        raise PaymentRejected("Stripe signature timestamp is invalid.") from error
    if abs(int(time.time()) - timestamp) > 300:
        raise PaymentRejected("Stripe signature timestamp is outside tolerance.")
    signed = str(timestamp).encode("ascii") + b"." + payload
    expected = hmac.new(
        secret.encode("utf-8"), signed, hashlib.sha256
    ).hexdigest()
    if not any(
        hmac.compare_digest(expected, candidate)
        for candidate in pairs.get("v1", [])
    ):
        raise PaymentRejected("Stripe webhook signature is invalid.")


@app.post("/api/payments/stripe/webhook")
async def stripe_webhook(request: Request) -> JSONResponse:
    try:
        _secret_key, webhook_secret = stripe_test_credentials()
        require_stripe_public_request(
            request,
            str(PAYMENT_RUNTIME["payments"]["stripe_test"]["webhook_path"]),
        )
        payload = await request.body()
        verify_stripe_signature(
            payload, request.headers.get("stripe-signature", ""), webhook_secret
        )
        event = json.loads(payload)
        if not isinstance(event, dict):
            raise PaymentRejected("Stripe event is invalid.")
        event_id = str(event.get("id", ""))
        if (
            event.get("object") != "event"
            or event.get("livemode") is not False
            or re.fullmatch(r"evt_[A-Za-z0-9]{8,}", event_id) is None
        ):
            raise PaymentRejected("Stripe test event identity is invalid.")
        event_type = str(event.get("type", ""))
        data = event.get("data")
        snapshot = data.get("object") if isinstance(data, dict) else None
        if event_type == "checkout.session.completed":
            if not isinstance(snapshot, dict):
                raise PaymentRejected("Stripe Session snapshot is missing.")
            finalize_stripe_session(snapshot)
        return JSONResponse({"ok": True, "received": True})
    except (json.JSONDecodeError, PaymentError, PaymentConflict, PaymentRejected) as error:
        return JSONResponse(
            {"ok": False, "error": "invalid-stripe-webhook", "message": str(error)},
            status_code=400,
        )


# ---------------------------------------------------------------------------
# Local account boundary
# ---------------------------------------------------------------------------


@app.get("/login_or_join", response_class=HTMLResponse)
async def login_or_join(
    request: Request, next: str | None = None, reason: str = ""
) -> HTMLResponse:
    return render(
        request,
        "login.html",
        page_title="Log in or sign up",
        next_path=safe_next(next),
        unauthorized=(reason == "unauthorized"),
        auth_error=None,
        hide_footer=True,
    )


def auth_error_message(error: AuthError) -> str:
    if isinstance(error, AuthRateLimited):
        return "Please wait before requesting another message."
    if isinstance(error, AuthConflict):
        return "That email cannot be used for this request."
    if isinstance(error, AuthValidationError):
        return str(error)
    return "We couldn't complete that request. Check the details and try again."


def auth_subject_factory(connection, registration) -> str:
    auth_account_id = str(registration["account_id"])
    subject_id = "change-member-" + hashlib.sha256(
        auth_account_id.encode("utf-8")
    ).hexdigest()[:24]
    connection.execute(
        "INSERT INTO accounts(id,name,email,created_at) VALUES (?,?,?,?)",
        (
            subject_id,
            str(registration["display_name"]),
            str(registration["email"]),
            FROZEN_CLOCK,
        ),
    )
    return subject_id


@app.post("/auth/sign-in")
async def auth_sign_in(request: Request):
    values = await urlencoded_form(request)
    next_path = safe_next(values.get("next"))
    if values.get("csrf") != CSRF_VALUE:
        return render(
            request,
            "login.html",
            page_title="Log in or sign up",
            next_path=next_path,
            unauthorized=False,
            auth_error="This form has expired. Please try again.",
            hide_footer=True,
            status_code=403,
        )
    try:
        result = AUTH_STORE.sign_in(
            request.state.auth_token,
            email=values.get("email", ""),
            password=values.get("password", ""),
        )
    except AuthError:
        return render(
            request,
            "login.html",
            page_title="Log in or sign up",
            next_path=next_path,
            unauthorized=False,
            auth_error="Email or password is invalid.",
            hide_footer=True,
            status_code=401,
        )
    token = str(result["session_token"])
    request.state.auth_token = token
    request.state.auth_session = AUTH_STORE.resolve_session(token)
    attribution = request.cookies.get(SHARE_ATTRIBUTION_COOKIE, "")
    account = current_account(request)
    if attribution and account:
        try:
            await repository.execute(
                "share.attribute",
                {"account_id": account["id"], "token": attribution,
                 "event_type": "login"},
            )
        except RepositoryError:
            pass
    return RedirectResponse(next_path, status_code=303)


@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=AUTH_STORE,
        session_token=str(request.state.auth_token),
    )


@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=AUTH_STORE,
        session_token=str(request.state.auth_token),
    )


@app.get("/register", response_class=HTMLResponse)
async def register_page(
    request: Request, next: str | None = None, retry: bool = False
) -> HTMLResponse:
    next_path = safe_next(next)
    current_state = auth_ui_state(
        request.state.auth_token, "registration"
    )
    if retry and current_state in {"failed", "retry", "expired"}:
        set_auth_ui_state(
            request.state.auth_token, "registration", "retry"
        )
    return render(
        request,
        "register.html",
        page_title="Create your account",
        next_path=next_path,
        auth_status=auth_ui_view(
            request.state.auth_token, "registration"
        ),
        errors=[],
    )


@app.post("/register")
async def register_start(request: Request):
    values = await urlencoded_form(request)
    next_path = safe_next(values.get("next"))
    flow = AUTH_STORE.session_flow_status(
        request.state.auth_token, purpose="registration"
    )
    if values.get("csrf") != CSRF_VALUE:
        return render(
            request,
            "register.html",
            page_title="Create your account",
            next_path=next_path,
            auth_status=auth_ui_view(
                request.state.auth_token, "registration"
            ),
            errors=["This form has expired. Please try again."],
            status_code=403,
        )
    if PUBLIC_REGISTRATION_VERIFICATION is not None:
        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=str(request.state.auth_token),
                email=values.get("email", ""),
            )
            if not ticket:
                return render(
                    request,
                    "register.html",
                    page_title="Create your account",
                    next_path=next_path,
                    auth_status=auth_ui_view(
                        request.state.auth_token, "registration"
                    ),
                    errors=["Verify this email address before creating the account."],
                    status_code=422,
                )
            result = AUTH_STORE.complete_externally_verified_registration(
                str(request.state.auth_token),
                email=values.get("email", ""),
                display_name=values.get("display_name", ""),
                password=values.get("password", ""),
                subject_factory=auth_subject_factory,
            )
        except VerificationUnavailable:
            set_auth_ui_state(
                request.state.auth_token, "registration", "failed"
            )
            return render(
                request,
                "register.html",
                page_title="Create your account",
                next_path=next_path,
                auth_status=auth_ui_view(
                    request.state.auth_token, "registration"
                ),
                errors=["Email verification is temporarily unavailable."],
                status_code=503,
            )
        except AuthError as error:
            status_code = 422
            if isinstance(error, AuthRateLimited):
                status_code = 429
                set_auth_ui_state(
                    request.state.auth_token, "registration", "retry"
                )
            elif not isinstance(error, AuthValidationError):
                status_code = 503
                set_auth_ui_state(
                    request.state.auth_token, "registration", "failed"
                )
            return render(
                request,
                "register.html",
                page_title="Create your account",
                next_path=next_path,
                auth_status=auth_ui_view(
                    request.state.auth_token, "registration"
                ),
                errors=[auth_error_message(error)],
                status_code=status_code,
            )
        token = str(result["session_token"])
        request.state.auth_token = token
        request.state.auth_session = AUTH_STORE.resolve_session(token)
        set_auth_ui_state(token, "registration", "recovered")
        return RedirectResponse(next_path, status_code=303)
    try:
        AUTH_STORE.start_registration(
            request.state.auth_token,
            email=values.get("email", ""),
            display_name=values.get("display_name", ""),
            password=values.get("password", ""),
            restart_invalid_flow=flow.get("state") in {"stale", "locked"},
        )
        dispatch_harbor_auth_mail(
            request.state.auth_token, "registration"
        )
    except AuthError as error:
        status_code = 422
        if isinstance(error, AuthRateLimited):
            status_code = 429
            set_auth_ui_state(
                request.state.auth_token, "registration", "retry"
            )
        elif not isinstance(error, AuthValidationError):
            status_code = 503
            set_auth_ui_state(
                request.state.auth_token, "registration", "failed"
            )
        return render(
            request,
            "register.html",
            page_title="Create your account",
            next_path=next_path,
            auth_status=auth_ui_view(
                request.state.auth_token, "registration"
            ),
            errors=[auth_error_message(error)],
            status_code=status_code,
        )
    mark_auth_delivery_success(
        request.state.auth_token, "registration"
    )
    return RedirectResponse(
        f"/register/verify?next={quote(next_path, safe='/')}",
        status_code=303,
    )


@app.get("/register/verify", response_class=HTMLResponse)
async def register_verify_page(
    request: Request, next: str | None = None
) -> HTMLResponse:
    return render(
        request,
        "register_verify.html",
        page_title="Verify your email",
        purpose="registration",
        next_path=safe_next(next),
        auth_status=auth_ui_view(
            request.state.auth_token, "registration"
        ),
        errors=[],
    )


@app.post("/register/verify")
async def register_verify(request: Request):
    values = await urlencoded_form(request)
    next_path = safe_next(values.get("next"))
    if values.get("csrf") != CSRF_VALUE:
        return render(
            request,
            "register_verify.html",
            page_title="Verify your email",
            purpose="registration",
            next_path=next_path,
            auth_status=auth_ui_view(
                request.state.auth_token, "registration"
            ),
            errors=["This form has expired. Please try again."],
            status_code=403,
        )
    try:
        AUTH_STORE.verify_registration_code(
            request.state.auth_token,
            values.get("code", ""),
        )
        result = AUTH_STORE.complete_registration(
            request.state.auth_token,
            subject_factory=auth_subject_factory,
        )
    except AuthError as error:
        state = (
            "expired"
            if isinstance(error, (AuthExpired, AuthLocked))
            else "retry"
        )
        set_auth_ui_state(
            request.state.auth_token, "registration", state
        )
        return render(
            request,
            "register_verify.html",
            page_title="Verify your email",
            purpose="registration",
            next_path=next_path,
            auth_status=auth_ui_view(
                request.state.auth_token, "registration"
            ),
            errors=[auth_error_message(error)],
            status_code=422,
        )
    token = str(result["session_token"])
    request.state.auth_token = token
    request.state.auth_session = AUTH_STORE.resolve_session(token)
    set_auth_ui_state(token, "registration", "recovered")
    attribution = request.cookies.get(SHARE_ATTRIBUTION_COOKIE, "")
    account = current_account(request)
    if attribution and account:
        try:
            await repository.execute(
                "share.attribute",
                {"account_id": account["id"], "token": attribution,
                 "event_type": "login"},
            )
        except RepositoryError:
            pass
    return RedirectResponse(next_path, status_code=303)


@app.get("/recover", response_class=HTMLResponse)
async def recover_page(
    request: Request, next: str | None = None, retry: bool = False
) -> HTMLResponse:
    next_path = safe_next(next)
    current_state = auth_ui_state(
        request.state.auth_token, "password-reset"
    )
    if retry and current_state in {"failed", "retry", "expired"}:
        set_auth_ui_state(
            request.state.auth_token, "password-reset", "retry"
        )
    return render(
        request,
        "recover.html",
        page_title="Reset your password",
        state="request",
        next_path=next_path,
        auth_status=auth_ui_view(
            request.state.auth_token, "password-reset"
        ),
        message="",
        errors=[],
    )


@app.post("/recover")
async def recover_start(request: Request):
    values = await urlencoded_form(request)
    next_path = safe_next(values.get("next"))
    flow = AUTH_STORE.session_flow_status(
        request.state.auth_token, purpose="password-reset"
    )
    if values.get("csrf") != CSRF_VALUE:
        return render(
            request,
            "recover.html",
            page_title="Reset your password",
            state="request",
            next_path=next_path,
            auth_status=auth_ui_view(
                request.state.auth_token, "password-reset"
            ),
            message="",
            errors=["This form has expired. Please try again."],
            status_code=403,
        )
    try:
        result = AUTH_STORE.start_password_reset(
            request.state.auth_token,
            email=values.get("email", ""),
            restart_invalid_flow=flow.get("state") in {"stale", "locked"},
        )
        dispatch_harbor_auth_mail(
            request.state.auth_token, "password-reset"
        )
        message = str(result["message"])
    except AuthRateLimited:
        set_auth_ui_state(
            request.state.auth_token, "password-reset", "retry"
        )
        return render(
            request,
            "recover.html",
            page_title="Reset your password",
            state="request",
            next_path=next_path,
            auth_status=auth_ui_view(
                request.state.auth_token, "password-reset"
            ),
            message=RESET_PUBLIC_MESSAGE,
            errors=["Please wait before requesting another message."],
            status_code=429,
        )
    except AuthValidationError as error:
        return render(
            request,
            "recover.html",
            page_title="Reset your password",
            state="request",
            next_path=next_path,
            auth_status=auth_ui_view(
                request.state.auth_token, "password-reset"
            ),
            message="",
            errors=[str(error)],
            status_code=422,
        )
    except AuthError:
        set_auth_ui_state(
            request.state.auth_token, "password-reset", "failed"
        )
        return render(
            request,
            "recover.html",
            page_title="Reset your password",
            state="request",
            next_path=next_path,
            auth_status=auth_ui_view(
                request.state.auth_token, "password-reset"
            ),
            message=RESET_PUBLIC_MESSAGE,
            errors=["The local verification message could not be prepared."],
            status_code=503,
        )
    mark_auth_delivery_success(
        request.state.auth_token, "password-reset"
    )
    return render(
        request,
        "recover.html",
        page_title="Reset your password",
        state="verify",
        next_path=next_path,
        auth_status=auth_ui_view(
            request.state.auth_token, "password-reset"
        ),
        message=message,
        errors=[],
    )


@app.post("/recover/complete")
async def recover_complete(request: Request):
    values = await urlencoded_form(request)
    next_path = safe_next(values.get("next"))
    if values.get("csrf") != CSRF_VALUE:
        return render(
            request,
            "recover.html",
            page_title="Reset your password",
            state="verify",
            next_path=next_path,
            auth_status=auth_ui_view(
                request.state.auth_token, "password-reset"
            ),
            message=RESET_PUBLIC_MESSAGE,
            errors=["This form has expired. Please try again."],
            status_code=403,
        )
    try:
        AUTH_STORE.verify_password_reset_code(
            request.state.auth_token,
            values.get("code", ""),
        )
        token = AUTH_STORE.complete_password_reset(
            request.state.auth_token,
            new_password=values.get("new_password", ""),
        )
    except AuthError as error:
        state = (
            "expired"
            if isinstance(error, (AuthExpired, AuthLocked))
            else "retry"
        )
        set_auth_ui_state(
            request.state.auth_token, "password-reset", state
        )
        return render(
            request,
            "recover.html",
            page_title="Reset your password",
            state="verify",
            next_path=next_path,
            auth_status=auth_ui_view(
                request.state.auth_token, "password-reset"
            ),
            message=RESET_PUBLIC_MESSAGE,
            errors=[auth_error_message(error)],
            status_code=422,
        )
    request.state.auth_token = token
    request.state.auth_session = AUTH_STORE.resolve_session(token)
    set_auth_ui_state(token, "password-reset", "recovered")
    return RedirectResponse(next_path, status_code=303)


@app.get("/auth/inbox", response_class=HTMLResponse)
async def auth_inbox(
    request: Request, purpose: str = "registration", next: str | None = None
) -> HTMLResponse:
    selected = (
        "password-reset" if purpose == "password-reset" else "registration"
    )
    return render(
        request,
        "auth_inbox.html",
        page_title="Your verification message",
        purpose=selected,
        next_path=safe_next(next),
        auth_status=auth_ui_view(request.state.auth_token, selected),
    )


@app.post("/fixture/session")
async def fixture_session(request: Request):
    if not hmac.compare_digest(
        request.headers.get(ADMIN_TOKEN_HEADER, ""), ADMIN_TOKEN
    ):
        return JSONResponse(
            {"ok": False, "error": "test session boundary refused"},
            status_code=403,
        )
    values = await urlencoded_form(request)
    next_path = safe_next(values.get("next"))
    if values.get("csrf") != CSRF_VALUE:
        return render(
            request,
            "login.html",
            page_title="Log in or sign up",
            next_path=next_path,
            unauthorized=False,
            auth_error="This form has expired. Please try again.",
            hide_footer=True,
            status_code=403,
        )
    email = (values.get("email") or "").strip().casefold()
    if not email.endswith("@example.test") or email == "@example.test":
        return render(
            request,
            "login.html",
            page_title="Log in or sign up",
            next_path=next_path,
            unauthorized=False,
            auth_error=(
                "We couldn't sign you in with that email address. "
                "Please check it and try again."
            ),
            hide_footer=True,
            status_code=403,
        )
    business_account = db.ensure_account(email)
    fixture_password = str(
        SEED_AUTH_ACCOUNTS.get(email, {}).get(
            "password", FIXTURE_PASSWORD
        )
    )
    AUTH_STORE.seed_account(
        subject_id=business_account["id"],
        email=email,
        display_name=business_account["name"],
        password=fixture_password,
    )
    result = AUTH_STORE.sign_in(
        request.state.auth_token,
        email=email,
        password=fixture_password,
    )
    token = str(result["session_token"])
    request.state.auth_token = token
    request.state.auth_session = AUTH_STORE.resolve_session(token)
    attribution = request.cookies.get(SHARE_ATTRIBUTION_COOKIE, "")
    if attribution:
        try:
            await repository.execute(
                "share.attribute",
                {"account_id": business_account["id"], "token": attribution,
                 "event_type": "login"},
            )
        except RepositoryError:
            pass
    return RedirectResponse(next_path, status_code=303)


@app.get("/my-petitions", response_class=HTMLResponse)
async def my_petitions(request: Request):
    return _render_my_petitions(request, active_tab="started")


def _request_path_and_query(request: Request) -> str:
    path = request.url.path
    return f"{path}?{request.url.query}" if request.url.query else path


def _petition_card_location(petition: dict[str, object]) -> str:
    """Return deterministic display-only geography for owner profile cards."""
    slug = str(petition["slug"]).casefold()
    if "toronto" in slug or "riverdale" in slug:
        return "Toronto, ON, Canada"
    if "nyc" in slug or "new-york" in slug:
        return "New York, NY, United States"
    if "sf-" in slug or "san-francisco" in slug:
        return "San Francisco, CA, United States"
    return "Canada"


def _petition_started_label(petition: dict[str, object]) -> str:
    created = str(petition.get("created_at", FROZEN_DATE))[:10]
    try:
        year, month, day = (int(part) for part in created.split("-"))
        month_name = (
            "January", "February", "March", "April", "May", "June",
            "July", "August", "September", "October", "November", "December",
        )[month - 1]
        return f"Started {month_name} {day}, {year}"
    except (ValueError, IndexError):
        return f"Started {created}"


def _owner_profile_card(petition: dict[str, object]) -> dict[str, object]:
    card = dict(petition)
    card["location"] = _petition_card_location(petition)
    card["started_label"] = _petition_started_label(petition)
    return card


def _render_my_petitions(
    request: Request, *, active_tab: str
) -> HTMLResponse | RedirectResponse:
    account = current_account(request)
    if account is None:
        return login_redirect(_request_path_and_query(request))
    started = [
        _owner_profile_card(petition)
        for petition in db.list_petitions_for_owner(account["id"])
    ]
    signed = [
        _owner_profile_card(petition)
        for petition in db.list_petitions()
        if db.get_signature(str(petition["slug"]), account["id"]) is not None
    ]
    selected_tab = "signed" if active_tab == "signed" else "started"
    petitions = signed if selected_tab == "signed" else started
    return render(
        request,
        "my_petitions.html",
        page_title="My petitions",
        petitions=petitions,
        started_petitions=started,
        signed_petitions=signed,
        active_tab=selected_tab,
        most_recent=(started[0] if started else None),
        dashboard_state=(
            "zero" if not petitions else "one" if len(petitions) == 1 else "multiple"
        ),
    )


@app.get("/u/me", response_class=HTMLResponse)
async def user_petitions(request: Request, tab: str = "started"):
    return _render_my_petitions(request, active_tab=tab)


def _owner_petition_access(
    request: Request, slug: str, *, next_path: str
) -> tuple[
    dict[str, str] | None,
    dict[str, object] | None,
    HTMLResponse | RedirectResponse | None,
]:
    account = current_account(request)
    if account is None:
        return None, None, login_redirect(next_path)
    petition = db.get_petition(slug)
    if petition is None:
        return account, None, render(
            request,
            "not_found.html",
            page_title="Petition not found",
            status_code=404,
        )
    if petition["owner"] != account["id"]:
        return account, None, refusal(
            request,
            status_code=403,
            reason_title="You can't manage this petition",
            reason_body=(
                "Only the petition owner can open its campaign dashboard."
            ),
        )
    return account, petition, None


def _render_owner_dashboard(
    request: Request, petition: dict[str, object]
) -> HTMLResponse:
    goal = max(int(petition["next_goal"]), 1)
    supporters = int(petition["signatures"])
    return render(
        request,
        "owner_dashboard.html",
        page_title=f"Dashboard — {petition['title']}",
        petition=petition,
        supporter_goal=goal,
        supporter_count=supporters,
        supporter_progress=min(100, round((supporters / goal) * 100)),
        petition_strength=("Strong" if supporters >= goal / 2 else "Growing"),
        next_steps_complete=0,
        next_steps_total=9,
    )


@app.get("/p/{slug}/dashboard")
async def owner_dashboard_alias(
    request: Request, slug: str, source_location: str = ""
):
    _, petition, failure = _owner_petition_access(
        request, slug, next_path=_request_path_and_query(request)
    )
    if failure is not None:
        return failure
    assert petition is not None
    target = f"/p/{slug}/dashboard/home"
    if source_location:
        target += f"?source_location={quote(source_location, safe='')}"
    return RedirectResponse(target, status_code=307)


@app.get("/p/{slug}/dashboard/home", response_class=HTMLResponse)
async def owner_dashboard_home(request: Request, slug: str):
    _, petition, failure = _owner_petition_access(
        request, slug, next_path=_request_path_and_query(request)
    )
    if failure is not None:
        return failure
    assert petition is not None
    return _render_owner_dashboard(request, petition)


ACCOUNT_SETTINGS_SECTIONS: dict[str, dict[str, object]] = {
    "profile": {
        "title": "Profile",
        "description": "Review the name and email shown for this local account.",
    },
    "change_password": {
        "title": "Change password",
        "description": (
            "Password changes are handled by the protected recovery flow. "
            "No password is changed from this read-only settings page."
        ),
    },
    "manage_email": {
        "title": "Manage email",
        "description": "Review the email address attached to this account.",
    },
    "privacy": {
        "title": "Privacy",
        "description": (
            "Review privacy choices and open the local cookie preference page."
        ),
    },
    "disable_account": {
        "title": "Disable account",
        "description": (
            "Account disabling is not performed from this informational page."
        ),
    },
}


@app.get("/account_settings", response_class=HTMLResponse)
async def account_settings(request: Request):
    account = current_account(request)
    if account is None:
        return login_redirect(_request_path_and_query(request))
    return render(
        request,
        "account_settings.html",
        page_title="Settings",
        account=account,
        sections=ACCOUNT_SETTINGS_SECTIONS,
    )


@app.get("/account_settings/{section}", response_class=HTMLResponse)
async def account_settings_detail(request: Request, section: str):
    account = current_account(request)
    if account is None:
        return login_redirect(_request_path_and_query(request))
    setting = ACCOUNT_SETTINGS_SECTIONS.get(section)
    if setting is None:
        return render(
            request,
            "not_found.html",
            page_title="Settings page not found",
            status_code=404,
        )
    return render(
        request,
        "account_settings_detail.html",
        page_title=str(setting["title"]),
        account=account,
        section=section,
        setting=setting,
    )


@app.post("/logout")
async def logout(request: Request):
    values = await urlencoded_form(request)
    if values.get("csrf") != CSRF_VALUE:
        return refusal(
            request,
            status_code=403,
            reason_title="Sign-out form expired",
            reason_body=(
                "This sign-out request has expired. Refresh the page "
                "and try again."
            ),
        )
    AUTH_STORE.sign_out(request.state.auth_token)
    token = AUTH_STORE.create_anonymous_session()
    request.state.auth_token = token
    request.state.auth_session = AUTH_STORE.resolve_session(token)
    return RedirectResponse("/?signed_out=1", status_code=303)


@app.post("/fixture/sign-out")
async def fixture_sign_out(request: Request):
    if not hmac.compare_digest(
        request.headers.get(ADMIN_TOKEN_HEADER, ""), ADMIN_TOKEN
    ):
        return JSONResponse(
            {"ok": False, "error": "test sign-out boundary refused"},
            status_code=403,
        )
    return await logout(request)


# ---------------------------------------------------------------------------
# Start-a-petition entry, assisted draft steps, scratch form
# ---------------------------------------------------------------------------


@app.get("/start-a-petition")
async def start_a_petition() -> RedirectResponse:
    return RedirectResponse(
        "/start-a-petition/intro", status_code=301
    )


@app.get("/start-a-petition/intro", response_class=HTMLResponse)
async def start_intro(request: Request) -> HTMLResponse:
    return render(
        request,
        "start_intro.html",
        page_title="Start a Petition",
        page_class="page-start-petition-intro",
        hide_footer=True,
        hide_start_petition=True,
    )


@app.get("/start-a-petition/issue", response_class=HTMLResponse)
async def start_issue(
    request: Request, topic: str = "", location: str = ""
) -> HTMLResponse:
    return render(
        request,
        "start_flow.html",
        page_title="Start a Petition",
        flow_step="issue",
        heading="First, tell us about your issue",
        description=(
            "We’ll combine your words with our expertise to generate the most "
            "impactful petition draft for you."
        ),
        field_label="I want to…",
        field_name="issue",
        placeholder=(
            "Require all public buildings in Sacramento, CA to be wheelchair "
            "accessible."
        ),
        error_message="Describe your concern in a sentence or two",
        optional=False,
        next_path="/start-a-petition/personal-story",
        back_path="/start-a-petition/intro",
        page_class="page-start-petition-issue",
        hide_footer=True,
        hide_start_petition=True,
    )


@app.get("/start-a-petition/personal-story", response_class=HTMLResponse)
async def start_personal_story(request: Request) -> HTMLResponse:
    return render(
        request,
        "start_flow.html",
        page_title="Start a Petition",
        flow_step="personalStory",
        heading="One last thing",
        description="Adding a personal story will make the petition stronger.",
        field_label="Why is it personal to you? (Optional)",
        field_name="personalStory",
        placeholder=(
            "There are no ramps for my sister to get to her classroom at "
            "Washington Elementary school"
        ),
        error_message="",
        optional=True,
        next_path="/start-a-petition/edit",
        back_path="/start-a-petition/issue",
        page_class="page-start-petition-personal-story",
        hide_footer=True,
        hide_start_petition=True,
    )


@app.get("/start-a-petition/create", response_class=HTMLResponse)
async def start_create(request: Request) -> HTMLResponse:
    return render(
        request,
        "start_edit.html",
        page_title="Start a Petition",
        recommended=False,
        page_class="page-start-petition-create",
        hide_footer=True,
        hide_start_petition=True,
    )


@app.get("/start-a-petition/edit", response_class=HTMLResponse)
async def start_edit(request: Request) -> HTMLResponse:
    return render(
        request,
        "start_edit.html",
        page_title="Start a Petition",
        recommended=True,
        page_class="page-start-petition-edit",
        hide_footer=True,
        hide_start_petition=True,
    )


@app.get("/start-a-petition/preview", response_class=HTMLResponse)
@app.get("/start-a-petition/optional-preview", response_class=HTMLResponse)
async def start_preview(request: Request) -> HTMLResponse:
    return render(
        request,
        "start_preview.html",
        page_title="Start a Petition",
        page_class="page-start-petition-preview",
        hide_footer=True,
        hide_start_petition=True,
    )


@app.get("/start-a-petition/location", response_class=HTMLResponse)
async def start_location(request: Request) -> HTMLResponse:
    return render(
        request,
        "start_location.html",
        page_title="Start a Petition",
        page_class="page-start-petition-location",
        hide_footer=True,
        hide_start_petition=True,
    )


@app.get("/start-a-petition/prepublish", response_class=HTMLResponse)
async def start_prepublish(request: Request) -> HTMLResponse:
    return render(
        request,
        "start_prepublish.html",
        page_title="Start a Petition",
        page_class="page-start-petition-prepublish",
        hide_footer=True,
        hide_start_petition=True,
    )


@app.get("/start-a-petition/draft/{step}", response_class=HTMLResponse)
async def assisted_draft_step(
    request: Request, step: str, topic: str = "", location: str = ""
) -> HTMLResponse:
    if step not in {"topic", "location", "review"}:
        return render(
            request,
            "not_found.html",
            page_title="Page not found",
            status_code=404,
        )
    if not signed_in(request):
        next_path = request.url.path
        if request.url.query:
            next_path += f"?{request.url.query}"
        return login_redirect(next_path)
    if step == "topic":
        return render(
            request,
            "assisted_topic.html",
            page_title="Assisted draft — describe your topic",
            form_topic=normalize_single_line(topic),
            form_location=normalize_single_line(location),
            errors=[],
        )
    normalized_topic = normalize_single_line(topic)
    normalized_location = normalize_single_line(location)
    errors = _validate_topic_location(normalized_topic, normalized_location)
    if errors:
        return render(
            request,
            "assisted_topic.html",
            page_title="Assisted draft — describe your topic",
            form_topic=normalized_topic,
            form_location=normalized_location,
            errors=errors,
            status_code=422,
        )
    resolved = assisted_template(normalized_topic, normalized_location)
    if step == "location":
        return render(
            request,
            "assisted_location.html",
            page_title="Assisted draft — confirm location",
            topic=resolved,
        )
    return render(
        request,
        "assisted_review.html",
        page_title="Assisted draft — review your petition",
        topic=resolved,
        form_title=resolved["template_title"],
        form_target=resolved["template_target"],
        form_body=resolved["template_body"],
        errors=[],
    )


@app.get("/start-a-petition/scratch", response_class=HTMLResponse)
async def scratch_form(request: Request) -> HTMLResponse:
    if not signed_in(request):
        return login_redirect("/start-a-petition/scratch")
    return render(
        request,
        "scratch.html",
        page_title="Write your own petition",
        form_topic="",
        form_title="",
        form_target="",
        form_body="",
        errors=[],
    )


# ---------------------------------------------------------------------------
# Server-owned publish (disposable fixture store)
# ---------------------------------------------------------------------------


def _validate_petition_fields(
    title: str, target: str, body: str
) -> list[str]:
    errors: list[str] = []
    if len(title) < TITLE_MIN:
        errors.append(
            f"Petition title is required. Minimum {TITLE_MIN} normalized character."
        )
    elif len(title) > TITLE_MAX:
        errors.append(
            f"Petition title must be at most {TITLE_MAX} characters "
            f"(got {len(title)})."
        )
    if len(target) < TARGET_MIN:
        errors.append(
            "Decision-maker target is required. "
            f"Minimum {TARGET_MIN} normalized character."
        )
    elif len(target) > TARGET_MAX:
        errors.append(
            f"Decision-maker target must be at most {TARGET_MAX} "
            f"characters (got {len(target)})."
        )
    if len(body) < BODY_MIN:
        errors.append(
            f"Petition body is required. Minimum {BODY_MIN} normalized character."
        )
    elif len(body) > BODY_MAX:
        errors.append(
            f"Petition body must be at most {BODY_MAX} characters "
            f"(got {len(body)})."
        )
    return errors


def _render_publish_form(
    request: Request,
    *,
    path: str,
    topic: dict[str, object] | None,
    values: dict[str, str],
    errors: list[str],
    status_code: int,
) -> HTMLResponse:
    common = {
        "form_title": values.get("title", ""),
        "form_target": values.get("target", ""),
        "form_body": values.get("body", ""),
        "form_target_type": values.get("target_type", "organization"),
        "form_target_location": values.get("target_location", values.get("location", "")),
        "form_contact_label": values.get("contact_label", "Decision maker"),
        "form_idempotency_key": values.get(
            "idempotency_key", PUBLISH_IDEMPOTENCY_KEY
        ),
        "simulate_transient_once": values.get("simulate_transient_once", ""),
        "errors": errors,
    }
    if path == "assisted" and topic is not None:
        return render(
            request,
            "assisted_review.html",
            page_title="Assisted draft — review your petition",
            topic=topic,
            status_code=status_code,
            **common,
        )
    return render(
        request,
        "scratch.html",
        page_title="Write your own petition",
        form_topic=values.get("topic", ""),
        status_code=status_code,
        **common,
    )


@app.post("/petitions/publish")
@app.post("/fixture/petitions/publish")
async def publish_petition(request: Request):
    account = current_account(request)
    if account is None:
        next_path = "/start-a-petition/prepublish"
        if request.url.query:
            next_path = f"{next_path}?{request.url.query}"
        return login_redirect(next_path)
    values = await urlencoded_form(request)
    path = values.get("path", "scratch")
    if path not in {"scratch", "assisted"}:
        path = "scratch"
    topic_id = normalize_single_line(values.get("topic", ""))
    location = normalize_single_line(values.get("location", ""))
    topic = (
        assisted_template(topic_id, location or "the affected community")
        if path == "assisted" and topic_id
        else None
    )
    errors: list[str] = []
    if values.get("csrf") != CSRF_VALUE:
        errors.append("This form has expired. Reload the page and try again.")
    errors.extend(_validate_topic_location(topic_id))
    submitted_version = values.get("draft_version", "")
    title = normalize_single_line(values.get("title", ""))
    target = normalize_single_line(values.get("target", ""))
    body = normalize_multiline(values.get("body", ""))
    target_type = normalize_single_line(values.get("target_type", "organization"))
    target_location = normalize_single_line(
        values.get("target_location", location)
    )
    contact_label = normalize_single_line(
        values.get("contact_label", "Decision maker")
    )
    idempotency_key = values.get("idempotency_key", "").strip()
    normalized_values = {
        **values,
        "topic": topic_id,
        "location": location,
        "title": title,
        "target": target,
        "body": body,
        "target_type": target_type,
        "target_location": target_location,
        "contact_label": contact_label,
        "idempotency_key": idempotency_key,
    }
    if submitted_version != DRAFT_VERSION:
        return _render_publish_form(
            request,
            path=path,
            topic=topic,
            values=normalized_values,
            errors=[
                f"Stale draft version {submitted_version!r}: the current "
                f"draft version is {DRAFT_VERSION!r}. Reload the draft "
                "form to continue — your title, body, and target are "
                "preserved below and nothing was overwritten."
            ],
            status_code=409,
        )
    if not valid_idempotency_key(idempotency_key):
        errors.append(
            "Idempotency key must contain 1 to "
            f"{IDEMPOTENCY_KEY_MAX} ASCII letters, digits, dots, colons, "
            "underscores, or hyphens."
        )
    errors.extend(_validate_petition_fields(title, target, body))
    if errors:
        return _render_publish_form(
            request,
            path=path,
            topic=topic,
            values=normalized_values,
            errors=errors,
            status_code=422,
        )
    slug = petition_slug(topic_id, title)
    try:
        moderation = await repository.execute(
            "moderation.publish",
            {
                "actor_id": account["id"],
                "subject_id": slug,
                "text": "\n".join((title, target, body)),
            },
            idempotency_key=(
                "moderation:" + request_fingerprint(idempotency_key)[:32]
            ),
        )
    except RepositoryError as error:
        return _render_publish_form(
            request,
            path=path,
            topic=topic,
            values=normalized_values,
            errors=[f"Moderation check unavailable: {error}"],
            status_code=error.status if error.status >= 500 else 422,
        )
    if moderation["decision"] != "approved":
        reasons = [
            str(item.get("reason", "This petition cannot be published."))
            for item in moderation.get("reasons", [])
        ]
        return _render_publish_form(
            request,
            path=path,
            topic=topic,
            values=normalized_values,
            errors=reasons or ["This petition cannot be published."],
            status_code=422,
        )
    fingerprint = request_fingerprint(
        topic_id,
        path,
        submitted_version,
        slug,
        title,
        target,
        body,
        target_type,
        target_location,
        contact_label,
    )
    if (
        values.get("simulate_transient_once") == "1"
        and db.consume_transient_failure(
            operation="publish",
            owner_id=account["id"],
            partition_id=topic_id,
            idempotency_key=idempotency_key,
        )
    ):
        return _render_publish_form(
            request,
            path=path,
            topic=topic,
            values=normalized_values,
            errors=[
                "Transient local publish failure. No petition or signature "
                "was created. Retry the retained command with the same topic, "
                "draft version, and idempotency key."
            ],
            status_code=503,
        )
    command_status, petition = db.execute_publish_command(
        topic_id=topic_id,
        draft_version=int(submitted_version),
        slug=slug,
        title=title,
        target=target,
        body=body,
        owner_id=account["id"],
        path=path,
        idempotency_key=idempotency_key,
        request_fingerprint=fingerprint,
    )
    if command_status == "replay":
        try:
            await repository.execute(
                "target.upsert",
                {
                    "actor_id": account["id"], "petition_slug": slug,
                    "type": target_type, "name": target,
                    "location": target_location, "contact_label": contact_label,
                    "topic": topic_id,
                },
                idempotency_key=(
                    "target:" + request_fingerprint(slug, idempotency_key)[:32]
                ),
            )
            await repository.execute(
                "event.record",
                {
                    "account_id": account["id"], "event_type": "petition_published",
                    "object_type": "petition", "object_id": slug,
                    "metadata": {"topic": topic_id, "organization": target,
                                 "location": target_location, "title": title,
                                 "body": body, "target": target},
                    "account_email": account["email"],
                },
                idempotency_key=("publish:" + request_fingerprint(idempotency_key)[:32]),
            )
        except RepositoryError:
            pass
        return RedirectResponse(
            f"/p/{slug}/published?replay=1", status_code=303
        )
    if command_status == "idempotency-conflict":
        return _render_publish_form(
            request,
            path=path,
            topic=topic,
            values=normalized_values,
            errors=[
                "Idempotency conflict: this topic-partitioned key already "
                "belongs to a different normalized publish request. Use the "
                "original retained values or start a new command."
            ],
            status_code=409,
        )
    if command_status == "slug-conflict":
        if petition is not None and petition["owner"] != account["id"]:
            return refusal(
                request,
                status_code=403,
                reason_title="Foreign-owned petition",
                reason_body=(
                    "This petition belongs to another account and cannot "
                    "be changed."
                ),
            )
        return _render_publish_form(
            request,
            path=path,
            topic=topic,
            values=normalized_values,
            errors=[
                "Petition slug conflict: this topic was already published "
                "under a different command identity. No record or counter "
                "was changed."
            ],
            status_code=409,
        )
    assert command_status == "created" and petition is not None
    try:
        await repository.execute(
            "target.upsert",
            {
                "actor_id": account["id"],
                "petition_slug": slug,
                "type": target_type,
                "name": target,
                "location": target_location,
                "contact_label": contact_label,
                "topic": topic_id,
            },
            idempotency_key=(
                "target:" + request_fingerprint(slug, idempotency_key)[:32]
            ),
        )
        await repository.execute(
            "event.record",
            {
                "account_id": account["id"],
                "event_type": "petition_published",
                "object_type": "petition",
                "object_id": slug,
                    "metadata": {
                        "topic": topic_id,
                        "organization": target,
                        "location": target_location,
                        "title": title,
                        "body": body,
                        "target": target,
                    },
                    "account_email": account["email"],
            },
            idempotency_key=("publish:" + request_fingerprint(idempotency_key)[:32]),
        )
    except RepositoryError as error:
        return refusal(
            request,
            status_code=503,
            reason_title="Petition published; campaign services are unavailable",
            reason_body=(
                "The petition was saved, but its target, growth, or notification "
                f"record could not be synchronized ({error.code}). Retry with the "
                "same idempotency key; publishing will not duplicate the petition."
            ),
        )
    return RedirectResponse(f"/p/{slug}/published", status_code=303)


# ---------------------------------------------------------------------------
# Petition detail, signing, comments, publish confirmation, supporter updates
# ---------------------------------------------------------------------------


def _detail_context(
    request: Request,
    petition: dict[str, object],
    *,
    tab: str,
    posted: str = "",
    update_replay: str = "",
    signed: str = "",
    commented: str = "",
    comment_replay: str = "",
    sign_errors: list[str] | None = None,
    comment_errors: list[str] | None = None,
    form_display_name: str | None = None,
    form_reason: str = "",
    form_comment: str = "",
    comment_petition_version: int | None = None,
    comment_idempotency_key_value: str | None = None,
    sign_idempotency_key_value: str | None = None,
    simulate_signature_transient: bool = False,
    simulate_comment_transient: bool = False,
) -> dict[str, object]:
    account = current_account(request)
    viewer_signature = (
        db.get_signature(str(petition["slug"]), account["id"])
        if account
        else None
    )
    if tab == "updates":
        active_tab = "updates"
    elif tab == "comments":
        active_tab = "comments"
    else:
        active_tab = "petition"
    created_sequence = int(petition["created_seq"])
    petition_hero_image = petition.get("hero_image")
    if not petition_hero_image and created_sequence >= 0:
        petition_hero_image = PETITION_HERO_IMAGES[
            created_sequence % len(PETITION_HERO_IMAGES)
        ]
    current_petition_version = int(petition.get("row_version", 1))
    rendered_comment_version = (
        comment_petition_version
        if comment_petition_version is not None
        else current_petition_version
    )
    rendered_comment_key = (
        comment_idempotency_key_value
        if comment_idempotency_key_value is not None
        else (
            comment_idempotency_key(
                str(petition["slug"]),
                account["id"],
                rendered_comment_version,
            )
            if account
            else ""
        )
    )
    rendered_signature_key = (
        sign_idempotency_key_value
        if sign_idempotency_key_value is not None
        else (
            signature_idempotency_key(
                str(petition["slug"]),
                account["id"],
                current_petition_version,
            )
            if account
            else ""
        )
    )
    return {
        "page_title": str(petition["title"]),
        "page_class": (
            "page-petition-detail"
            if petition_hero_image
            else "page-petition-detail page-petition-detail-no-media"
        ),
        "force_account_avatar": (
            str(petition["slug"]) == CURRENT_CLOSED_PETITION["slug"]
        ),
        "petition": petition,
        "petition_hero_image": petition_hero_image,
        "petition_has_media": bool(petition_hero_image),
        "active_tab": active_tab,
        "is_owner": bool(account) and petition["owner"] == account["id"],
        "just_posted": posted == "1",
        "update_replayed": update_replay == "1",
        "just_signed": signed == "1",
        "just_commented": commented == "1",
        "comment_replayed": comment_replay == "1",
        "viewer_signature": viewer_signature,
        "sign_errors": sign_errors or [],
        "comment_errors": comment_errors or [],
        "form_display_name": (
            form_display_name
            if form_display_name is not None
            else (account["name"] if account else "")
        ),
        "form_reason": form_reason,
        "form_comment": form_comment,
        "sign_idempotency_key": rendered_signature_key,
        "simulate_signature_transient": simulate_signature_transient,
        "comment_petition_version": rendered_comment_version,
        "comment_idempotency_key": rendered_comment_key,
        "simulate_comment_transient": simulate_comment_transient,
        "display_name_max": DISPLAY_NAME_MAX,
        "reason_max": REASON_MAX,
        "comment_max": COMMENT_MAX,
    }


@app.get("/p/{slug}", response_class=HTMLResponse)
async def petition_detail(
    request: Request,
    slug: str,
    tab: str = "petition",
    posted: str = "",
    update_replay: str = "",
    signed: str = "",
    commented: str = "",
    comment_replay: str = "",
) -> HTMLResponse:
    petition = db.get_petition(slug)
    if petition is None and slug == CURRENT_CLOSED_PETITION["slug"]:
        petition = dict(CURRENT_CLOSED_PETITION)
    if petition is None:
        return render(
            request,
            "not_found.html",
            page_title="Petition not found",
            status_code=404,
        )
    return render(
        request,
        "petition_detail.html",
        **_detail_context(
            request, petition, tab=tab, posted=posted,
            update_replay=update_replay,
            signed=signed, commented=commented,
            comment_replay=comment_replay,
        ),
    )


def _validate_signature_fields(
    display_name: str, reason: str
) -> list[str]:
    errors: list[str] = []
    if not display_name.strip():
        errors.append("Display name is required.")
    elif len(display_name) > DISPLAY_NAME_MAX:
        errors.append(
            f"Display name must be at most {DISPLAY_NAME_MAX} characters "
            f"(got {len(display_name)})."
        )
    if len(reason) > REASON_MAX:
        errors.append(
            f"Signing reason must be at most {REASON_MAX} characters "
            f"(got {len(reason)})."
        )
    return errors


@app.post("/petitions/{slug}/sign")
@app.post("/fixture/petitions/{slug}/sign")
async def sign_petition(request: Request, slug: str):
    petition = db.get_petition(slug)
    if petition is None:
        return render(
            request,
            "not_found.html",
            page_title="Petition not found",
            status_code=404,
        )
    account = current_account(request)
    if account is None:
        return login_redirect(f"/p/{slug}")
    values = await urlencoded_form(request)
    existing_signature = db.get_signature(slug, account["id"])
    if existing_signature is not None:
        return RedirectResponse(
            f"/p/{slug}?signed=1&replay=1", status_code=303
        )
    errors: list[str] = []
    if values.get("csrf") != CSRF_VALUE:
        errors.append("This form has expired. Reload the page and try again.")
    submitted_version = values.get("petition_version", "")
    if submitted_version != str(petition["row_version"]):
        return render(
            request,
            "petition_detail.html",
            status_code=409,
            **_detail_context(
                request,
                petition,
                tab="petition",
                sign_errors=[
                    f"Stale petition version {submitted_version!r}: the "
                    f"current version is {petition['row_version']!r}. "
                    "Reload the petition and sign again — nothing was "
                    "recorded."
                ],
                form_display_name=values.get("display_name", ""),
                form_reason=values.get("reason", ""),
            ),
        )
    if petition["status"] != "open":
        return refusal(
            request,
            status_code=403,
            reason_title="Petition is not open for signatures",
            reason_body=(
                f"This petition has status \"{petition['status']}\" and "
                "no longer accepts signatures. Signature counts never "
                "change after a petition closes or wins."
            ),
        )
    display_name = values.get("display_name", "")
    reason = values.get("reason", "")
    display_publicly = values.get("display_publicly", "") == "on"
    idempotency_key = values.get("idempotency_key", "") or (
        signature_idempotency_key(
            slug, account["id"], int(petition["row_version"])
        )
    )
    if not valid_idempotency_key(idempotency_key):
        errors.append(
            "Signature idempotency key is invalid. Reload the petition "
            "and try again."
        )
    errors.extend(_validate_signature_fields(display_name, reason))
    if errors:
        return render(
            request,
            "petition_detail.html",
            status_code=422,
            **_detail_context(
                request,
                petition,
                tab="petition",
                sign_errors=errors,
                form_display_name=display_name,
                form_reason=reason,
                sign_idempotency_key_value=idempotency_key,
            ),
        )
    if (
        values.get("simulate_transient_once") == "1"
        and db.consume_transient_failure(
            operation="signature",
            owner_id=account["id"],
            partition_id=slug,
            idempotency_key=idempotency_key,
        )
    ):
        return render(
            request,
            "petition_detail.html",
            status_code=503,
            **_detail_context(
                request,
                petition,
                tab="petition",
                sign_errors=[
                    "Transient local signature failure. Nothing was "
                    "recorded. Retry the retained form."
                ],
                form_display_name=display_name,
                form_reason=reason,
                sign_idempotency_key_value=idempotency_key,
                simulate_signature_transient=True,
            ),
        )
    _, created = db.add_signature(
        slug=slug,
        account_id=account["id"],
        display_name=display_name.strip(),
        display_publicly=display_publicly,
        reason=reason.strip(),
    )
    if created:
        try:
            refreshed = db.get_petition(slug) or petition
            await repository.execute(
                "event.record",
                {
                    "account_id": account["id"],
                    "event_type": "signature_created",
                    "object_type": "petition",
                    "object_id": slug,
                    "metadata": {"signatures": refreshed["signatures"]},
                    "account_email": account["email"],
                    "attribution_token": request.cookies.get(
                        SHARE_ATTRIBUTION_COOKIE, ""
                    ),
                },
                idempotency_key=f"signature:{account['id']}",
            )
            attribution = request.cookies.get(SHARE_ATTRIBUTION_COOKIE, "")
            if attribution:
                await repository.execute(
                    "share.attribute",
                    {
                        "account_id": account["id"],
                        "token": attribution,
                        "event_type": "signature",
                    },
                )
        except RepositoryError:
            pass
    # Duplicate sign is idempotent: same "you signed" destination, no
    # second row, no counter inflation.
    suffix = "signed=1" if created else "signed=1&replay=1"
    return RedirectResponse(f"/p/{slug}?{suffix}", status_code=303)


@app.post("/signatures/{signature_id}")
@app.post("/fixture/signatures/{signature_id}")
async def edit_signature(request: Request, signature_id: int):
    signature = db.get_signature_by_id(signature_id)
    if signature is None:
        return render(
            request,
            "not_found.html",
            page_title="Signature not found",
            status_code=404,
        )
    account = current_account(request)
    if account is None:
        return login_redirect(f"/p/{signature['petition_slug']}")
    if signature["account_id"] != account["id"]:
        return refusal(
            request,
            status_code=403,
            reason_title="Foreign signature mutation refused",
            reason_body=(
                "Only the supporter who created a signature may change "
                "its display settings or reason. This signature belongs "
                "to a different account, so the server refuses the "
                "mutation."
            ),
        )
    values = await urlencoded_form(request)
    if values.get("csrf") != CSRF_VALUE:
        return refusal(
            request,
            status_code=403,
            reason_title="Form expired",
            reason_body="This form has expired. Reload the page and try again.",
        )
    reason = values.get("reason", signature["reason"])
    if len(reason) > REASON_MAX:
        return refusal(
            request,
            status_code=422,
            reason_title="Signing reason too long",
            reason_body=(
                f"Signing reason must be at most {REASON_MAX} characters "
                f"(got {len(reason)})."
            ),
        )
    db.update_signature(
        signature_id,
        display_publicly=values.get("display_publicly", "") == "on",
        reason=reason.strip(),
    )
    return RedirectResponse(
        f"/p/{signature['petition_slug']}?signed=1", status_code=303
    )


@app.post("/petitions/{slug}/comments")
@app.post("/fixture/petitions/{slug}/comments")
async def post_comment(request: Request, slug: str):
    petition = db.get_petition(slug)
    if petition is None:
        return render(
            request,
            "not_found.html",
            page_title="Petition not found",
            status_code=404,
        )
    account = current_account(request)
    if account is None:
        return login_redirect(f"/p/{slug}?tab=comments")
    values = await urlencoded_form(request)
    body = values.get("body", "")
    idempotency_key = values.get("idempotency_key", "").strip()
    submitted_version = values.get("petition_version", "")
    try:
        expected_version = int(submitted_version)
    except ValueError:
        expected_version = -1
    if not hmac.compare_digest(values.get("csrf", ""), CSRF_VALUE):
        return render(
            request,
            "petition_detail.html",
            status_code=403,
            **_detail_context(
                request,
                petition,
                tab="comments",
                comment_errors=[
                    "This form has expired. Reload the page and try again."
                ],
                form_comment=body,
                comment_petition_version=(
                    expected_version
                    if expected_version >= 0
                    else int(petition["row_version"])
                ),
                comment_idempotency_key_value=idempotency_key,
            ),
        )
    # Documented source-mirroring decision: the captured 2026-07-25
    # evidence shows no comment surface, so we mirror the generic
    # Change.org product rule — comments are "reasons for signing"
    # authored by supporters, so commenting requires a signature first.
    if db.get_signature(slug, account["id"]) is None:
        return refusal(
            request,
            status_code=403,
            reason_title="Sign before commenting",
            reason_body=(
                "Comments on a petition are reasons for signing. Sign "
                "this petition first, then share why you signed."
            ),
        )
    errors: list[str] = []
    if not body.strip():
        errors.append("Comment text is required.")
    elif len(body) > COMMENT_MAX:
        errors.append(
            f"Comment text must be at most {COMMENT_MAX} characters "
            f"(got {len(body)})."
        )
    if expected_version < 0:
        errors.append("Petition version must be a non-negative integer.")
    if not valid_idempotency_key(idempotency_key):
        errors.append(
            "Idempotency key must contain 1 to "
            f"{IDEMPOTENCY_KEY_MAX} ASCII letters, digits, dots, colons, "
            "underscores, or hyphens."
        )
    if errors:
        return render(
            request,
            "petition_detail.html",
            status_code=422,
            **_detail_context(
                request,
                petition,
                tab="comments",
                comment_errors=errors,
                form_comment=body,
                comment_petition_version=(
                    expected_version
                    if expected_version >= 0
                    else int(petition["row_version"])
                ),
                comment_idempotency_key_value=idempotency_key,
            ),
        )
    normalized_body = body.strip()
    fingerprint = request_fingerprint(
        slug,
        str(expected_version),
        normalized_body,
    )
    if (
        values.get("simulate_transient_once") == "1"
        and db.consume_transient_failure(
            operation="petition-comment",
            owner_id=account["id"],
            partition_id=slug,
            idempotency_key=idempotency_key,
        )
    ):
        return render(
            request,
            "petition_detail.html",
            status_code=503,
            **_detail_context(
                request,
                petition,
                tab="comments",
                comment_errors=[
                    "We couldn't post your comment. Please try again."
                ],
                form_comment=normalized_body,
                comment_petition_version=expected_version,
                comment_idempotency_key_value=idempotency_key,
                simulate_comment_transient=True,
            ),
        )
    command_status, command = db.submit_comment_command(
        slug=slug,
        author_id=account["id"],
        body=normalized_body,
        expected_petition_version=expected_version,
        idempotency_key=idempotency_key,
        request_fingerprint=fingerprint,
    )
    if command_status == "replay":
        return RedirectResponse(
            f"/p/{slug}?tab=comments&commented=1&comment_replay=1",
            status_code=303,
        )
    if command_status == "idempotency-conflict":
        refreshed = db.get_petition(slug) or petition
        return render(
            request,
            "petition_detail.html",
            status_code=409,
            **_detail_context(
                request,
                refreshed,
                tab="comments",
                comment_errors=[
                    "Idempotency conflict: this comment key already belongs "
                    "to a different petition/version/body request. No "
                    "duplicate was created."
                ],
                form_comment=normalized_body,
                comment_petition_version=int(refreshed["row_version"]),
                comment_idempotency_key_value=idempotency_key,
            ),
        )
    if command_status == "stale":
        current_version = int(
            command["current_version"]
            if command is not None
            else petition["row_version"]
        )
        refreshed = db.get_petition(slug) or petition
        return render(
            request,
            "petition_detail.html",
            status_code=409,
            **_detail_context(
                request,
                refreshed,
                tab="comments",
                comment_errors=[
                    f"Stale petition version {submitted_version!r}; current "
                    f"version is {current_version}. Your comment and command "
                    "key are retained below."
                ],
                form_comment=normalized_body,
                comment_petition_version=current_version,
                comment_idempotency_key_value=idempotency_key,
            ),
        )
    if command_status == "missing":
        return render(
            request,
            "not_found.html",
            page_title="Petition not found",
            status_code=404,
        )
    assert command_status == "created"
    return RedirectResponse(
        f"/p/{slug}?tab=comments&commented=1", status_code=303
    )


@app.get("/p/{slug}/published", response_class=HTMLResponse)
async def publish_confirmation(
    request: Request, slug: str, replay: str = ""
) -> HTMLResponse:
    petition = db.get_petition(slug)
    if petition is None:
        return render(
            request,
            "not_found.html",
            page_title="Petition not found",
            status_code=404,
        )
    return render(
        request,
        "published.html",
        page_title="Petition published",
        petition=petition,
        replayed=(replay == "1"),
    )


def _update_access(
    request: Request, slug: str, *, next_path: str | None = None
) -> tuple[dict[str, object] | None, HTMLResponse | RedirectResponse | None]:
    account = current_account(request)
    if account is None:
        return None, login_redirect(next_path or f"/p/{slug}/updates/new")
    most_recent = db.most_recent_for_owner(account["id"])
    if most_recent is None:
        return None, refusal(
            request,
            status_code=409,
            reason_title="No petition to update",
            reason_body=(
                "You don't have a petition to update yet. Publish one first."
            ),
        )
    petition = db.get_petition(slug)
    if petition is None:
        return None, render(
            request,
            "not_found.html",
            page_title="Petition not found",
            status_code=404,
        )
    if petition["owner"] != account["id"]:
        return None, refusal(
            request,
            status_code=403,
            reason_title="You can't update this petition",
            reason_body=(
                "Only the petition owner can post an update. Sign in with "
                "the petition owner's account to continue."
            ),
        )
    if most_recent["slug"] != slug:
        return None, refusal(
            request,
            status_code=409,
            reason_title="Choose your latest petition",
            reason_body=(
                "Updates can be posted from your latest petition page. "
                "Continue with "
                f"\"{most_recent['title']}\"."
            ),
            most_recent_slug=str(most_recent["slug"]),
        )
    return petition, None


def _render_update_form(
    request: Request,
    petition: dict[str, object],
    *,
    body: str,
    idempotency_key: str,
    petition_version: int,
    errors: list[str],
    status_code: int,
    source_dashboard: bool = False,
    update_preview: str = "",
    update_preview_title: str = "",
) -> HTMLResponse:
    return render(
        request,
        "update_form.html",
        page_title="Post a supporter update",
        petition=petition,
        form_body=body,
        update_idempotency_key=idempotency_key,
        update_petition_version=petition_version,
        errors=errors,
        source_dashboard=source_dashboard,
        update_preview=update_preview,
        update_preview_title=update_preview_title,
        status_code=status_code,
    )


@app.get("/p/{slug}/updates/new", response_class=HTMLResponse)
async def supporter_update_form(request: Request, slug: str):
    petition, failure = _update_access(request, slug)
    if failure is not None:
        return failure
    assert petition is not None
    return _render_update_form(
        request,
        petition,
        body="",
        idempotency_key=f"update:{slug}:v{petition['row_version']}",
        petition_version=int(petition["row_version"]),
        errors=[],
        status_code=200,
    )


@app.get("/p/{slug}/dashboard/updates", response_class=HTMLResponse)
async def owner_dashboard_updates(request: Request, slug: str):
    petition, failure = _update_access(
        request,
        slug,
        next_path=_request_path_and_query(request),
    )
    if failure is not None:
        return failure
    assert petition is not None
    return _render_update_form(
        request,
        petition,
        body="",
        idempotency_key=f"update:{slug}:v{petition['row_version']}",
        petition_version=int(petition["row_version"]),
        errors=[],
        status_code=200,
        source_dashboard=True,
    )


@app.post("/petitions/{slug}/updates")
@app.post("/fixture/petitions/{slug}/updates")
async def post_supporter_update(request: Request, slug: str):
    petition, failure = _update_access(request, slug)
    if failure is not None:
        return failure
    values = await urlencoded_form(request)
    assert petition is not None
    errors: list[str] = []
    source_dashboard = values.get("source_dashboard") == "1"
    if values.get("csrf") != CSRF_VALUE:
        errors.append("This form has expired. Reload the page and try again.")
    body = normalize_multiline(values.get("body", ""))
    idempotency_key = values.get("idempotency_key", "").strip()
    submitted_version = values.get("petition_version", "")
    try:
        expected_version = int(submitted_version)
    except ValueError:
        expected_version = -1
    if values.get("action") == "preview":
        # Preview renders the pending draft back to the owner without
        # persisting anything, so the control works with scripting disabled.
        return _render_update_form(
            request,
            petition,
            body=body,
            idempotency_key=idempotency_key,
            petition_version=(
                expected_version
                if expected_version >= 0
                else int(petition["row_version"])
            ),
            errors=errors,
            status_code=403 if errors else 200,
            source_dashboard=source_dashboard,
            update_preview=body,
            update_preview_title=values.get("title", "").strip(),
        )
    if len(body) < UPDATE_MIN:
        errors.append(
            f"Update text is required. Minimum {UPDATE_MIN} normalized character."
        )
    elif len(body) > UPDATE_MAX:
        errors.append(
            f"Update text must be at most {UPDATE_MAX} characters "
            f"(got {len(body)})."
        )
    if not valid_idempotency_key(idempotency_key):
        errors.append(
            "Idempotency key must contain 1 to "
            f"{IDEMPOTENCY_KEY_MAX} ASCII letters, digits, dots, colons, "
            "underscores, or hyphens."
        )
    if errors:
        return _render_update_form(
            request,
            petition,
            body=body,
            idempotency_key=idempotency_key,
            petition_version=(
                expected_version
                if expected_version >= 0
                else int(petition["row_version"])
            ),
            errors=errors,
            source_dashboard=source_dashboard,
            status_code=422,
        )
    account = current_account(request)
    assert account is not None  # guaranteed by _update_access
    fingerprint = request_fingerprint(
        slug,
        str(expected_version),
        body,
    )
    if (
        values.get("simulate_transient_once") == "1"
        and db.consume_transient_failure(
            operation="supporter-update",
            owner_id=account["id"],
            partition_id=slug,
            idempotency_key=idempotency_key,
        )
    ):
        return _render_update_form(
            request,
            petition,
            body=body,
            idempotency_key=idempotency_key,
            petition_version=expected_version,
            errors=[
                "We couldn't post your update. Please try again."
            ],
            source_dashboard=source_dashboard,
            status_code=503,
        )
    command_status, command = db.submit_update_command(
        petition_slug=slug,
        body=body,
        author_id=account["id"],
        expected_petition_version=expected_version,
        idempotency_key=idempotency_key,
        request_fingerprint=fingerprint,
    )
    if command_status == "replay":
        return RedirectResponse(
            f"/p/{slug}?tab=updates&posted=1&update_replay=1",
            status_code=303,
        )
    if command_status == "idempotency-conflict":
        return _render_update_form(
            request,
            petition,
            body=body,
            idempotency_key=idempotency_key,
            petition_version=int(petition["row_version"]),
            errors=[
                "Idempotency conflict: this update key already belongs to a "
                "different petition/version/body request. No duplicate was "
                "created."
            ],
            source_dashboard=source_dashboard,
            status_code=409,
        )
    if command_status == "stale":
        current_version = int(
            command["current_version"] if command is not None else petition["row_version"]
        )
        refreshed = db.get_petition(slug) or petition
        return _render_update_form(
            request,
            refreshed,
            body=body,
            idempotency_key=idempotency_key,
            petition_version=current_version,
            errors=[
                f"Stale petition version {submitted_version!r}; current "
                f"version is {current_version}. The body and idempotency key "
                "are retained below. Retry with this refreshed version."
            ],
            source_dashboard=source_dashboard,
            status_code=409,
        )
    assert command_status == "created"
    try:
        await repository.execute(
            "event.record",
            {
                "account_id": account["id"],
                "event_type": "supporter_update",
                "object_type": "petition",
                "object_id": slug,
                "metadata": {"body": body},
                "account_email": account["email"],
            },
            idempotency_key=f"update:{request_fingerprint(idempotency_key)[:32]}",
        )
    except RepositoryError:
        pass
    return RedirectResponse(
        f"/p/{slug}?tab=updates&posted=1", status_code=303
    )


# ---------------------------------------------------------------------------
# Growth, follows, notifications, sharing, and FTS discovery
# ---------------------------------------------------------------------------


@app.get("/api/follows")
async def api_list_follows(
    request: Request,
    object_type: str = "",
    cursor: str = "",
    limit: int = 20,
) -> JSONResponse:
    account = api_account(request)
    result = await repository.execute(
        "follow.list",
        {"account_id": account["id"], "object_type": object_type,
         "cursor": cursor, "limit": limit},
    )
    return JSONResponse({"ok": True, **result})


@app.post("/api/follows")
async def api_create_follow(request: Request) -> JSONResponse:
    account = api_account(request)
    values = await api_values(request)
    require_api_csrf(request, values)
    key = str(values.get("idempotency_key", ""))
    result = await repository.execute(
        "follow.create",
        {"account_id": account["id"], "object_type": values.get("type"),
         "object_id": values.get("id"), "account_email": account["email"]},
        idempotency_key=key,
    )
    if result.get("created") and result.get("object_type") == "petition":
        try:
            await repository.execute(
                "event.record",
                {"account_id": account["id"], "event_type": "follow_created",
                 "object_type": "petition", "object_id": result["object_id"],
                 "metadata": {}, "account_email": account["email"]},
                idempotency_key=f"follow:{request_fingerprint(key)[:32]}",
            )
        except RepositoryError:
            pass
    return JSONResponse({"ok": True, **result}, status_code=201 if result.get("created") else 200)


@app.delete("/api/follows/{object_type}/{object_id}")
async def api_delete_follow(
    request: Request, object_type: str, object_id: str
) -> JSONResponse:
    account = api_account(request)
    require_api_csrf(request)
    result = await repository.execute(
        "follow.delete",
        {"account_id": account["id"], "object_type": object_type,
         "object_id": object_id},
    )
    return JSONResponse({"ok": True, **result})


@app.get("/api/notifications")
async def api_notifications(
    request: Request,
    cursor: str = "",
    unread_only: bool = False,
    limit: int = 20,
) -> JSONResponse:
    account = api_account(request)
    result = await repository.execute(
        "notification.list",
        {"account_id": account["id"], "cursor": cursor,
         "unread_only": unread_only, "limit": limit},
    )
    return JSONResponse({"ok": True, **result})


@app.get("/api/notifications/unread-count")
async def api_notification_unread_count(request: Request) -> JSONResponse:
    account = api_account(request)
    result = await repository.execute(
        "notification.unread_count", {"account_id": account["id"]}
    )
    return JSONResponse({"ok": True, **result})


@app.post("/api/notifications/{notification_id}/read")
async def api_read_notification(
    request: Request, notification_id: str
) -> JSONResponse:
    account = api_account(request)
    require_api_csrf(request)
    result = await repository.execute(
        "notification.read",
        {"account_id": account["id"], "notification_id": notification_id},
    )
    return JSONResponse({"ok": True, **result})


@app.post("/api/notifications/read-all")
async def api_read_all_notifications(request: Request) -> JSONResponse:
    account = api_account(request)
    require_api_csrf(request)
    result = await repository.execute(
        "notification.read_all", {"account_id": account["id"]}
    )
    return JSONResponse({"ok": True, **result})


@app.get("/api/notification-preferences")
async def api_get_notification_preferences(request: Request) -> JSONResponse:
    account = api_account(request)
    result = await repository.execute(
        "preferences.get", {"account_id": account["id"]}
    )
    return JSONResponse({"ok": True, **result})


@app.put("/api/notification-preferences")
async def api_update_notification_preferences(request: Request) -> JSONResponse:
    account = api_account(request)
    values = await api_values(request)
    require_api_csrf(request, values)
    result = await repository.execute(
        "preferences.update",
        # Session identity is applied after the request values so a
        # caller-supplied account_id cannot redirect the write onto
        # another account's preferences.
        {**values, "account_id": account["id"], "account_email": account["email"]},
    )
    return JSONResponse({"ok": True, **result})


@app.get("/api/notifications/stream")
async def api_notification_stream(
    request: Request, cursor: str = ""
) -> StreamingResponse:
    account = api_account(request)
    last_event_id = request.headers.get("Last-Event-ID", "") or cursor
    result = await repository.execute(
        "notification.list",
        {"account_id": account["id"], "after_id": last_event_id,
         "limit": 100},
    )

    async def events():
        yield "retry: 15000\n\n"
        for item in result["items"]:
            payload = json.dumps(item, sort_keys=True, separators=(",", ":"))
            yield f"id: {item['id']}\nevent: notification\ndata: {payload}\n\n"
        yield ": polling fallback interval is 15 seconds\n\n"

    return StreamingResponse(
        events(),
        media_type="text/event-stream",
        headers={"Cache-Control": "no-store", "X-Accel-Buffering": "no"},
    )


@app.post("/api/petitions/{slug}/shares")
async def api_create_share(request: Request, slug: str) -> JSONResponse:
    account = api_account(request)
    values = await api_values(request)
    require_api_csrf(request, values)
    key = str(values.get("idempotency_key", ""))
    result = await repository.execute(
        "share.create",
        {"account_id": account["id"], "petition_slug": slug,
         "channel": values.get("channel", "copy")},
        idempotency_key=key,
    )
    if result.get("created"):
        try:
            await repository.execute(
                "event.record",
                {"account_id": account["id"], "event_type": "share_created",
                 "object_type": "petition", "object_id": slug,
                 "metadata": {"channel": result["channel"]},
                 "account_email": account["email"]},
                idempotency_key=f"share:{request_fingerprint(key)[:32]}",
            )
        except RepositoryError:
            pass
    public_path = result["path"]
    return JSONResponse(
        {"ok": True, **result, "share_url": str(request.base_url).rstrip("/") + public_path},
        status_code=201 if result.get("created") else 200,
    )


@app.get("/s/{token}")
async def follow_share_link(request: Request, token: str) -> RedirectResponse:
    client_marker = request.headers.get("X-WebsiteBench-Client-IP", "")
    if not client_marker and request.client:
        client_marker = request.client.host
    visitor_hash = hashlib.sha256(
        "\x1f".join((client_marker or "unknown", request.headers.get("user-agent", "")))
        .encode("utf-8")
    ).hexdigest()
    result = await repository.execute(
        "share.click", {"token": token, "visitor_hash": visitor_hash}
    )
    if result.get("recorded"):
        try:
            await repository.execute(
                "event.record",
                {"event_type": "share_clicked", "object_type": "petition",
                 "object_id": result["petition_slug"], "metadata": {}},
                idempotency_key=f"click:{visitor_hash[:32]}",
            )
        except RepositoryError:
            pass
    response = RedirectResponse(f"/p/{result['petition_slug']}", status_code=302)
    response.set_cookie(
        SHARE_ATTRIBUTION_COOKIE,
        token,
        max_age=30 * 24 * 60 * 60,
        httponly=True,
        samesite="lax",
        secure=False,
        path="/",
    )
    return response


@app.get("/api/search")
async def api_search(
    request: Request,
    q: str = "",
    topic: str = "",
    location: str = "",
    organization: str = "",
    status: str = "",
    cursor: str = "",
    limit: int = 20,
) -> JSONResponse:
    result = await repository.execute(
        "search.petitions",
        {"query": q, "topic": topic, "location": location,
         "organization": organization, "status": status,
         "cursor": cursor, "limit": limit},
    )
    return JSONResponse({"ok": True, **result})


@app.get("/api/growth")
async def api_growth_dashboard(
    request: Request, petition_slug: str = ""
) -> JSONResponse:
    account = api_account(request)
    result = await repository.execute(
        "growth.dashboard",
        {"account_id": account["id"], "petition_slug": petition_slug},
    )
    return JSONResponse({"ok": True, **result})


@app.get("/notifications", response_class=HTMLResponse)
async def notifications_page(request: Request) -> HTMLResponse:
    account = current_account(request)
    if account is None:
        return login_redirect("/notifications")
    notifications = await repository.execute(
        "notification.list", {"account_id": account["id"], "limit": 50}
    )
    unread = await repository.execute(
        "notification.unread_count", {"account_id": account["id"]}
    )
    return render(
        request, "notifications.html", page_title="Notifications",
        notifications=notifications["items"], unread_count=unread["unread_count"],
    )


@app.get("/settings/notifications", response_class=HTMLResponse)
async def notification_settings_page(request: Request) -> HTMLResponse:
    account = current_account(request)
    if account is None:
        return login_redirect("/settings/notifications")
    preferences = await repository.execute(
        "preferences.get", {"account_id": account["id"]}
    )
    return render(
        request, "notification_settings.html",
        page_title="Notification settings", preferences=preferences,
        saved=request.query_params.get("saved") == "1",
    )


NOTIFICATION_PREFERENCE_TOGGLES = (
    "in_app_enabled",
    "double_opt_in",
    "petition_updates",
    "organization_updates",
    "topic_recommendations",
    "growth_tips",
)


@app.post("/settings/notifications")
async def notification_settings_save(request: Request):
    """Scripting-free save path for the notification preference form.

    The browser path submits the same values through
    ``PUT /api/notification-preferences``; both funnel into the identical
    ``preferences.update`` command, which owns enum validation and the
    optimistic row_version check.
    """
    account = current_account(request)
    if account is None:
        return login_redirect("/settings/notifications")
    values = await urlencoded_form(request)
    preferences = await repository.execute(
        "preferences.get", {"account_id": account["id"]}
    )
    if values.get("csrf") != CSRF_VALUE:
        return render(
            request, "notification_settings.html",
            page_title="Notification settings", preferences=preferences,
            settings_error="This form has expired. Reload the page and try again.",
            status_code=403,
        )
    payload: dict[str, object] = {
        "account_id": account["id"],
        "account_email": account["email"],
        "email_mode": values.get("email_mode", "off"),
        "row_version": values.get("row_version", "") or 0,
    }
    # An unchecked box is absent from the submission, so each toggle is
    # resolved explicitly rather than defaulting to its stored value.
    for field in NOTIFICATION_PREFERENCE_TOGGLES:
        payload[field] = values.get(field) is not None
    try:
        await repository.execute("preferences.update", payload)
    except RepositoryError as error:
        return render(
            request, "notification_settings.html",
            page_title="Notification settings", preferences=preferences,
            settings_error=str(getattr(error, "message", None) or error),
            status_code=getattr(error, "status", 422) or 422,
        )
    return RedirectResponse("/settings/notifications?saved=1", status_code=303)


@app.get("/growth", response_class=HTMLResponse)
async def growth_page(request: Request) -> HTMLResponse:
    account = current_account(request)
    if account is None:
        return login_redirect("/growth")
    dashboard = await repository.execute(
        "growth.dashboard", {"account_id": account["id"]}
    )
    return render(
        request, "growth.html", page_title="Campaign growth",
        recommendations=dashboard["recommendations"],
        analytics=dashboard["analytics"],
    )


@app.exception_handler(RepositoryError)
async def repository_exception_handler(
    _request: Request, exc: RepositoryError
) -> JSONResponse:
    return repository_error_response(exc)


# ---------------------------------------------------------------------------
# 404 handler (production GraphQL proxy is intentionally absent)
# ---------------------------------------------------------------------------


@app.exception_handler(StarletteHTTPException)
async def http_exception_handler(request: Request, exc: StarletteHTTPException):
    if exc.status_code == 404:
        return render(
            request,
            "not_found.html",
            page_title="Page not found",
            status_code=404,
        )
    return JSONResponse(
        {"detail": exc.detail}, status_code=exc.status_code
    )


def main() -> None:
    port = int(os.environ.get("PORT", "8431"))
    uvicorn.run(app, host="127.0.0.1", port=port, access_log=True)


if __name__ == "__main__":
    main()