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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
"""Eventbrite offline clone -- persistent backend (stage: backend).

R3 boundary: the server owns organizers, events, occurrences, ticket
classes (capacity, per-order max, sales window, optimistic version token),
attendee accounts, orders with order lines and per-ticket registrations,
organizer-created local events, and persisted sessions in a WAL-mode SQL
database selected by the WebsiteBench runtime contract (always outside the
clone tree). Session tokens are opaque and persisted server-side so login
state survives a process restart.

Every mutation is an honest local simulation: no production Eventbrite
API call, external charge, or email. Ticket classes carry the price their
listing advertises, and the server totals an accepted order from that
server-owned price alone (client-supplied prices are never trusted). Paid
orders use the runtime's local-sandbox ledger; no card data is collected.

Event status (upcoming / on-sale / sales-ended / event-ended) is DERIVED
from ticket-class sales windows plus the frozen clock; benchmark event
IDs exist only as ordinary seed rows in clone/backend/db.py and no
backend branch compares against them.
"""

from __future__ import annotations

import calendar
import hashlib
import hmac
import io
import json
import os
import re
import sqlite3
import sys
import warnings
from contextlib import asynccontextmanager
from datetime import date, datetime, timedelta
from pathlib import Path
from typing import NamedTuple
from urllib.parse import parse_qs, quote_plus

import uvicorn
from fastapi import BackgroundTasks, FastAPI, Request
from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse, Response
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from PIL import Image, UnidentifiedImageError
ROOT = Path(__file__).resolve().parent
if str(ROOT) not in sys.path:
    sys.path.insert(0, str(ROOT))

import websitebench.local_clone_auth as local_auth
from websitebench.public_clone_auth import (
    load_public_clone_registration_verification,
)
from websitebench.public_clone_auth.fastapi import (
    consume_registration_ticket,
    registration_script_response,
    send_registration_code,
    verify_registration_code,
)
from backend import db, listing_fixtures, organization_workspace, ticket_payments
from backend.site_backend_integration import (
    auth_mail_delivery_enabled,
    auth_mail_worker_token,
    load_site_runtime,
    open_site_services,
    resolve_deployment_profile,
    resolve_runtime_path,
)
from websitebench.site_backend import AuthMailDelivery, AuthMailDeliveryError

SITE_ID = "eventbrite"
VERSION = "eventbrite-r3-backend-2026-07-25.1"
FIXTURE_ID = "eventbrite-v2-372-1118-r2"
FIXTURE_CLOCK = db.FROZEN_CLOCK
FROZEN_CLOCK = db.FROZEN_CLOCK
FIXTURE_NOW = db.FROZEN_NOW
FIXTURE_TODAY = db.FROZEN_TODAY

SESSION_COOKIE = "clawbench_eventbrite_r2"
SITE_BACKEND_RUNTIME_PATH = resolve_runtime_path()
SITE_BACKEND_RUNTIME = load_site_runtime(SITE_BACKEND_RUNTIME_PATH)
DEPLOYMENT_PROFILE_NAME, DEPLOYMENT_PROFILE = resolve_deployment_profile(
    SITE_BACKEND_RUNTIME
)


def _load_public_registration_verification():
    """Enable the shared external verifier only for the declared public profile."""

    if DEPLOYMENT_PROFILE["mail_adapter"] != "redis-resend":
        return None
    registration = dict(
        SITE_BACKEND_RUNTIME.raw["mail"]["purposes"]["registration"]
    )
    sender = dict(SITE_BACKEND_RUNTIME.raw["mail"]["sender"])
    source = dict(os.environ)
    source["PUBLIC_CLONE_AUTH_MAIL_TEMPLATE"] = json.dumps(
        {
            "sender_display_name": sender["display_name"],
            **{
                key: registration[key]
                for key in ("subject", "lead", "body", "expiry", "footer")
            },
        },
        sort_keys=True,
        separators=(",", ":"),
    )
    verification = load_public_clone_registration_verification(source)
    if verification is None:
        raise RuntimeError(
            "cloudflare-review requires public registration verification"
        )
    return verification


PUBLIC_REGISTRATION_VERIFICATION = _load_public_registration_verification()
LEGACY_SESSION_COOKIE = SESSION_COOKIE
SESSION_COOKIE = SITE_BACKEND_RUNTIME.cookie_name
CSRF_VALUE = "eventbrite-r2-frontend-fixture"
DEFAULT_ACCOUNT = "jordan-rivera"
SEED_PASSWORDS = {
    "jordan-rivera": os.environ.get(
        "WEBSITEBENCH_EVALUATOR_SECONDARY_SECRET", "Eventbrite-Jordan-2026!"
    ),
    "casey-kim": os.environ.get(
        "WEBSITEBENCH_EVALUATOR_PRIMARY_SECRET", "Eventbrite-Casey-2026!"
    ),
}
LOCAL_ORGANIZATION_ID = "1"
LOCAL_ORGANIZER = db.LOCAL_ORGANIZER
FOREIGN_ORGANIZER = db.FOREIGN_ORGANIZER

ADMIN_TOKEN_HEADER = "X-WebsiteBench-Admin-Token"
LEGACY_ADMIN_TOKEN_HEADER = "X-Clawbench-Admin-Token"

SYNTHETIC_LABEL = db.SYNTHETIC_LABEL
LOCAL_SIMULATION_DISCLOSURE = (
    "This is a local benchmark simulation. No production ticket was issued, "
    "no real payment was processed, no email was sent, and nothing was "
    "published to production Eventbrite."
    if DEPLOYMENT_PROFILE["mail_adapter"] == "local-outbox"
    else "This is a protected review clone. No production ticket was issued, "
    "no real payment was processed, and nothing was published to production "
    "Eventbrite. Clone-owned account email may be delivered by the review service."
)
SEED_DISCLOSURE = (
    "The organizer draft uses the exact historical task metadata supplied for "
    "this local event; publication and delivery remain site-local."
)

ASSETS = "/static/assets/source-current/2026-07-25"
# Second frozen asset batch: the 2026-08-08 DOM capture (seasonal home hero,
# signin background, Neue Plak faces). Templates address each batch by its
# own root so StaticFiles never sees a ".." segment.
ASSETS_08 = "/static/assets/source-current/2026-08-08"

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

# Re-exports so tests exercise the server-owned resolution logic.
resolve_next_fourth_tuesday = db.resolve_next_fourth_tuesday
H2H_NEXT_DATE = db.H2H_NEXT_DATE
H2H_OCCURRENCE_ID = db.H2H_OCCURRENCE_ID
H2H_SOURCE_CURRENT_DATE = db.H2H_SOURCE_CURRENT_DATE
H2H_SOURCE_OCCURRENCE_ID = db.H2H_SOURCE_OCCURRENCE_ID


_SITE_DATABASE: "db.Database | None" = None
_SITE_AUTH: "local_auth.LocalAuthStore | None" = None
_SITE_BACKEND = None


def _db() -> "db.Database":
    if _SITE_DATABASE is None:
        raise RuntimeError("Eventbrite site backend is not initialized")
    return _SITE_DATABASE


def _auth() -> "local_auth.LocalAuthStore":
    if _SITE_AUTH is None:
        raise RuntimeError("Eventbrite auth backend is not initialized")
    return _SITE_AUTH


def ensure_auth_seed(
    store: "local_auth.LocalAuthStore | None" = None,
) -> None:
    store = store or _auth()
    store.ensure_schema()
    for _, slug, display_name, email, _role in db.SEED_ACCOUNTS:
        store.seed_account(
            subject_id=slug,
            email=email,
            display_name=display_name,
            password=SEED_PASSWORDS[slug],
        )


def auth_seed_accounts() -> list[dict[str, object]]:
    return [
        {
            "subject_id": slug,
            "email": email,
            "display_name": display_name,
            "password": SEED_PASSWORDS[slug],
        }
        for _account_id, slug, display_name, email, _role in db.SEED_ACCOUNTS
    ]


def auth_subject_factory(
    connection, registration: dict[str, object]
) -> str:
    account_id = str(registration["account_id"])
    subject_id = "member-" + hashlib.sha256(
        account_id.encode("utf-8")
    ).hexdigest()[:20]
    return _db().create_registered_subject(
        connection,
        subject_id=subject_id,
        email=str(registration["email"]),
        display_name=str(registration["display_name"]),
    )


def remaining_capacity(event_id: str, occurrence_id: str) -> int:
    return _db().remaining_capacity(event_id, occurrence_id)


def seed_registries() -> None:
    """Reset the persistent store to the deterministic seed state."""

    if _SITE_BACKEND is None:
        raise RuntimeError("Eventbrite site backend is not initialized")

    def reset_site(connection) -> None:
        _SITE_BACKEND.lifecycle.reset_embedded(
            connection, confirm_site_id=SITE_ID
        )
        _db().reset_in_transaction(connection)

    _auth().reset_site_state(
        site_reset=reset_site,
        seed_accounts=auth_seed_accounts(),
    )


class _OrdersView:
    """Dict-like live view of persisted orders (test compatibility)."""

    def __len__(self) -> int:
        return _db().order_count()

    def values(self) -> list[dict]:
        return _db().orders_snapshot()

    def __iter__(self):
        return iter(order["id"] for order in self.values())

    def __contains__(self, reference: object) -> bool:
        return _db().order_by_reference(str(reference)) is not None

    def get(self, reference: str) -> dict | None:
        return _db().order_by_reference(reference)


class _OrganizerEventsView:
    """Dict-like live view of persisted organizer events."""

    def __len__(self) -> int:
        return _db().organizer_event_count()

    def __iter__(self):
        return iter(_db().organizer_event_ids())

    def __contains__(self, local_id: object) -> bool:
        return _db().organizer_event(str(local_id)) is not None

    def get(self, local_id: str):
        return _db().organizer_event(local_id)


ORDERS = _OrdersView()
ORGANIZER_EVENTS = _OrganizerEventsView()


def order_id_for(
    event_id: str, occurrence_id: str, email: str, owner: str = ""
) -> str:
    return db.order_reference_for(
        event_id,
        occurrence_id,
        f"{owner}|{email}" if owner else email,
    )


def local_event_id_for(title: str) -> str:
    digest = hashlib.sha256(title.strip().casefold().encode("utf-8")).hexdigest()
    return f"local-evt-{digest[:10]}"


SF_FROZEN_CARDS = [
    {
        "title": "Hot Girl Walk\u00ae| San Francisco | August 1",
        "when": "Sat, Aug 1 \u2022 9:30 AM",
        "where": "San Francisco \u00b7 Golden Gate Bridge Plaza",
        "image": f"{ASSETS}/sf-free-directory/sf-directory-card-1187598354.jpg",
    },
    {
        "title": "Downtown First Thursdays w/ Eric Rhodes | Aug. 6, 2026",
        "when": "Thu, Aug 6 \u2022 5:00 PM",
        "where": "San Francisco \u00b7 Natoma Cabana",
        "image": f"{ASSETS}/sf-free-directory/sf-directory-card-1174269883.jpg",
    },
    {
        "title": (
            "San Francisco Job Fair August 6, 2026 - San Francisco Career "
            "Fairs"
        ),
        "when": "Thu, Aug 6 \u2022 10:00 AM",
        "where": "San Francisco \u00b7 San Francisco",
        "image": f"{ASSETS}/sf-free-directory/sf-directory-card-828964879.jpg",
    },
    {
        "title": "Free Summer Weekend | Museum of Craft and Design",
        "when": "Sales end soon",
        "where": "San Francisco \u00b7 Museum of Craft and Design",
        "image": f"{ASSETS}/sf-free-directory/sf-directory-card-1188109055.jpg",
    },
    {
        "title": "Fridays on Front Street | Free San Francisco Block Party",
        "when": "Fri, Jul 31 \u2022 4:00 PM",
        "where": "San Francisco \u00b7 240 Front St",
        "image": f"{ASSETS}/sf-free-directory/sf-directory-card-1189262072.jpg",
    },
]

NY_FROZEN_CARDS = [
    {
        "title": "Rooftop Rendezvous New York | Affiliate Summit East 2026",
        "when": "Monday \u2022 4:00 PM",
        "where": "New York \u00b7 Magic Hour Rooftop Bar & Lounge",
        "image": f"{ASSETS}/ny-free-directory/ny-directory-card-1188847234.jpg",
    },
    {
        "title": (
            "esperanza spalding in ceremonial grade creation with Kayla "
            "Farrish"
        ),
        "when": "Sat, Aug 8 \u2022 7:00 PM",
        "where": "New York \u00b7 Robert F. Wagner Jr. Park",
        "image": f"{ASSETS}/ny-free-directory/ny-directory-card-1188866412.jpg",
    },
    {
        "title": "Hot Girl Walk\u00ae | NYC | July 25",
        "when": "Today \u2022 9:30 AM",
        "where": "New York \u00b7 Cop Cot",
        "image": f"{ASSETS}/ny-free-directory/ny-directory-card-1187848373.jpg",
    },
    {
        "title": (
            "IronStrength and Sunset Yoga on Intrepid with Lyons Den Power "
            "Yoga"
        ),
        "when": "Monday \u2022 5:30 PM",
        "where": "New York \u00b7 Intrepid Museum",
        "image": f"{ASSETS}/ny-free-directory/ny-directory-card-1182690852.jpg",
    },
    {
        "title": "Longest Table - Upper East Side",
        "when": "Wednesday \u2022 6:00 PM",
        "where": "New York \u00b7 Lenox Hill Neighborhood House",
        "image": f"{ASSETS}/ny-free-directory/ny-directory-card-1188662102.jpg",
    },
]

HOME_EVENT_CARDS = [
    {
        "title": "Summer Club LA | Young Hollywood Edition @ The Moxy Hotel Rooftop",
        "when": "Sun, Aug 2 \u2022 2:00 PM",
        "where": "Golden Hour at Level 8",
        "price": "From $0.00",
        "badge": "Promoted",
        "image": f"{ASSETS}/home/home-event-card-1189589099.jpg",
    },
    {
        "title": "FREE EVENT! Keri Hilson, Paul Wall, Mike Jones, DaniLeigh, Yung Joc & MORE!",
        "when": "Today \u2022 3:00 PM",
        "where": "Pershing Square",
        "price": "From $0.00",
        "badge": "Going fast",
        "image": f"{ASSETS}/home/home-event-card-1189042687.jpg",
    },
    {
        "title": "FREE EVENT! Too Short, Xzibit, Layzie Bone, RJMrLA & MORE!",
        "when": "Tomorrow \u2022 3:00 PM",
        "where": "Pershing Square",
        "price": "From $0.00",
        "badge": "Almost full",
        "image": f"{ASSETS}/home/home-event-card-1189143231.jpg",
    },
    {
        "title": "Free Wealth Builders Network Mixer",
        "when": "Today \u2022 4:30 PM",
        "where": "888 S Figueroa St Skyview Plaza",
        "price": "Free",
        "badge": "Sales end soon",
        "image": f"{ASSETS}/home/home-event-card-1189109798.jpg",
    },
    {
        "title": "FREE EVENT! MC Magic, Baby Bash, Frankie J, Lil Rob, Amanda Perez & MORE!",
        "when": "Sun, Aug 9 \u2022 3:00 PM",
        "where": "Pershing Square",
        "price": "From $0.00",
        "badge": "Going fast",
        "image": f"{ASSETS}/home/home-event-card-1188383469.jpg",
    },
    {
        "title": "DARK SHADOWS 60th ANNIVERSARY",
        "when": "Fri, Jul 31 \u2022 10:00 AM",
        "where": "The Westin Los Angeles Airport",
        "price": "From $12.38",
        "badge": "Almost full",
        "image": f"{ASSETS}/home/home-event-card-1174788767.jpg",
    },
    {
        "title": "Riftbound Regional Qualifier: Los Angeles",
        "when": "Fri, Sep 25 \u2022 12:00 PM",
        "where": "Los Angeles Convention Center",
        "price": "From $0.00",
        "badge": "Going fast",
        "image": f"{ASSETS}/home/home-event-card-1187859679.jpg",
    },
    {
        "title": "High in the Sky: The Rooftop Sade Experience",
        "when": "Tomorrow \u2022 4:00 PM",
        "where": "Somewhere Special Los Angeles",
        "price": "Free",
        "badge": "Almost full",
        "image": f"{ASSETS}/home/home-event-card-1188430869.jpg",
    },
    {
        "title": "Afrobeats Day Party (Los Angeles)",
        "when": "Sun, Aug 2 \u2022 4:00 PM",
        "where": "Vuuka House",
        "price": "From $0.00",
        "badge": "Promoted",
        "image": f"{ASSETS}/home/home-event-card-1189349005.jpg",
    },
    {
        "title": "Lectures on Tap - How America Nearly Wasn't",
        "when": "Tomorrow \u2022 5:30 PM",
        "where": "Downtown",
        "price": "From $39.19",
        "badge": "Almost full",
        "image": f"{ASSETS}/home/home-event-card-784072119.jpg",
    },
    {
        "title": "ARE N BEE: All R&B. All Night. | Los Angeles",
        "when": "Sat, Aug 1 \u2022 9:00 PM",
        "where": "Matriarch LA",
        "price": "From $28.64",
        "badge": "",
        "image": f"{ASSETS}/home/home-event-card-1188529912.jpg",
    },
    {
        "title": "LA FUNCTION “SUMMER FINALE” x “PROLIFIC” Album Celebration Party!",
        "when": "Sat, Aug 15 \u2022 3:00 PM",
        "where": "Academy LA",
        "price": "From $0.00",
        "badge": "",
        "image": f"{ASSETS}/home/home-event-card-1189255255.jpg",
    },
    {
        "title": "Noche De Cumbia con Yaguaru, Socios Del Ritmo, Sonora Tropicana y Mas",
        "when": "Today \u2022 5:30 PM",
        "where": "Santa Fe Springs Swap Meet",
        "price": "From $33.56",
        "badge": "Going fast",
        "image": f"{ASSETS}/home/home-event-card-1185091685.jpg",
    },
    {
        "title": "FREE EVENT! Too Short, Xzibit, Layzie Bone, RJMrLA & MORE!",
        "when": "Tomorrow \u2022 3:00 PM",
        "where": "Pershing Square",
        "price": "Free",
        "badge": "Sales end soon",
        "image": f"{ASSETS}/home/home-event-card-1189143640.jpg",
    },
    {
        "title": "Afrobeats Day party @ I|O Godfrey Rooftop Hollywood (L.A)",
        "when": "Sat, Aug 1 \u2022 4:00 PM",
        "where": "I|O Rooftop Hollywood",
        "price": "From $0.00",
        "badge": "Almost full",
        "image": f"{ASSETS}/home/home-event-card-1189448666.jpg",
    },
    {
        "title": "The Compton Rodeo Benefit",
        "when": "Today \u2022 5:00 PM",
        "where": "The Compound by Dirt Dog",
        "price": "From $34.99",
        "badge": "Almost full",
        "image": f"{ASSETS}/home/home-event-card-1189154462.jpg",
    },
]

# These labels and their order are frozen from the Los Angeles home capture.
# The links use the ordinary location resolver so every chip remains useful
# even when a place has no dedicated curated feed.
HOME_POPULAR_LINKS = [
    {
        "label": label,
        "url": f"/search?location={quote_plus(label)}",
    }
    for label in (
        "Austin",
        "Abilene",
        "Denver",
        "Seattle",
        "Phoenix",
        "Albuquerque",
        "Detroit",
        "Anaheim",
        "Raleigh",
        "Baltimore",
        "Nashville",
        "Wichita",
        "Indianapolis",
        "San Antonio",
    )
]

HOME_STATE_LINKS = [
    {
        "label": label,
        "url": f"/search?location={quote_plus(label)}",
    }
    for label in (
        "Alabama",
        "Alaska",
        "Arizona",
        "Arkansas",
        "California",
        "Colorado",
        "Connecticut",
        "Delaware",
        "District of Columbia",
        "Florida",
        "Georgia",
        "Hawaii",
        "Idaho",
        "Illinois",
        "Indiana",
        "Iowa",
        "Kansas",
        "Kentucky",
        "Louisiana",
        "Maine",
        "Maryland",
        "Massachusetts",
        "Michigan",
        "Minnesota",
        "Mississippi",
        "Missouri",
        "Montana",
        "Nebraska",
        "Nevada",
        "New Hampshire",
        "New Jersey",
        "New Mexico",
        "New York",
        "North Carolina",
        "North Dakota",
        "Ohio",
        "Oklahoma",
        "Oregon",
        "Pennsylvania",
        "Rhode Island",
        "South Carolina",
        "South Dakota",
        "Tennessee",
        "Texas",
        "Utah",
        "Vermont",
        "Virginia",
        "Washington",
        "West Virginia",
        "Wisconsin",
        "Wyoming",
    )
]

# Ordered exactly as the 2026-08-08 Top destinations carousel.  The first
# four images already existed in the July asset batch; the remainder were
# captured and vendored with the authenticated August DOM walk.
HOME_DESTINATIONS = [
    {
        "slug": slug,
        "label": label,
        "image": f"{ASSETS if index < 4 else ASSETS_08}/home/city-card-{slug}.webp",
    }
    for index, (slug, label) in enumerate(
        (
            ("ny--new-york", "New York"),
            ("ca--san-francisco", "San Francisco"),
            ("ca--los-angeles", "Los Angeles"),
            ("il--chicago", "Chicago"),
            ("dc--washington", "Washington, D.C."),
            ("ga--atlanta", "Atlanta"),
            ("tx--houston", "Houston"),
            ("ma--boston", "Boston"),
            ("tx--dallas", "Dallas"),
            ("tx--austin", "Austin"),
            ("fl--miami", "Miami"),
            ("ca--san-diego", "San Diego"),
            ("nv--las-vegas", "Las Vegas"),
            ("fl--orlando", "Orlando"),
            ("wa--seattle", "Seattle"),
            ("pa--philadelphia", "Philadelphia"),
            ("co--denver", "Denver"),
            ("tn--nashville", "Nashville"),
            ("la--new-orleans", "New Orleans"),
            ("nc--charlotte", "Charlotte"),
            ("or--portland", "Portland"),
            ("fl--tampa", "Tampa"),
            ("in--indianapolis", "Indianapolis"),
            ("md--baltimore", "Baltimore"),
            ("ca--sacramento", "Sacramento"),
            ("oh--columbus", "Columbus"),
            ("mn--minneapolis", "Minneapolis"),
            ("ca--oakland", "Oakland"),
            ("mi--detroit", "Detroit"),
            ("tx--san-antonio", "San Antonio"),
        )
    )
]


# The rendered catalog and the standalone WebsiteBench seed hook consume one
# backend-owned fixture set. Every frozen directory and recommendation card
# has its own source-bound image; fixture extension by image reuse is forbidden.
SF_FROZEN_CARDS = listing_fixtures.SF_FROZEN_CARDS
NY_FROZEN_CARDS = listing_fixtures.NY_FROZEN_CARDS
HOME_EVENT_CARDS = listing_fixtures.HOME_EVENT_CARDS
SF_DIRECTORY_CARDS = listing_fixtures.SF_DIRECTORY_CARDS
NY_DIRECTORY_CARDS = listing_fixtures.NY_DIRECTORY_CARDS
SF_RECOMMENDATION_CARDS = listing_fixtures.SF_RECOMMENDATION_CARDS
NY_RECOMMENDATION_CARDS = listing_fixtures.NY_RECOMMENDATION_CARDS

# Cities named in the frozen card copy, mapped to the region label and zone
# the catalog stores. Anything unlisted falls back to its page's own city.
_LISTING_CITIES = {
    "Los Angeles": ("Los Angeles, CA", "America/Los_Angeles"),
    "San Francisco": ("San Francisco, CA", "America/Los_Angeles"),
    "Sausalito": ("Sausalito, CA", "America/Los_Angeles"),
    "San Antonio": ("San Antonio, TX", "America/Chicago"),
    "New York": ("New York, NY", "America/New_York"),
    "Brooklyn": ("Brooklyn, NY", "America/New_York"),
}


def _price_cents(label: str) -> int:
    """Read a card's asking price out of its frozen price copy.

    "From $12.38" prices the ticket class at 1238; "Free", "From $0.00"
    and the free-filtered directory cards (which publish no price) are 0.
    """
    match = re.search(r"\$([0-9]+(?:\.[0-9]{2})?)", label)
    return round(float(match.group(1)) * 100) if match else 0


def _listing_entries(
    cards: list[dict[str, str]],
    default_city: str,
    default_timezone: str,
) -> list[db.ListingEntry]:
    """Read catalog entries out of frozen card copy.

    Directory cards carry "City \u00b7 Venue" in `where`; home cards carry
    the venue alone and inherit their page's city.
    """
    entries: list[db.ListingEntry] = []
    for card in cards:
        where = str(card["where"])
        city, _, venue = where.partition(" \u00b7 ")
        if not venue:
            city, venue = default_city, where
        region, timezone_name = _LISTING_CITIES.get(
            city, (default_city, default_timezone)
        )
        entries.append(
            db.ListingEntry(
                title=str(card["title"]),
                when=str(card["when"]),
                city=region,
                venue=venue,
                timezone=timezone_name,
                hero=str(card["image"]),
                price_cents=_price_cents(str(card.get("price", ""))),
                badge=str(card.get("badge", "")),
                start_at=str(card.get("start_at", "")),
                end_at=str(card.get("end_at", "")),
                detail_label=str(card.get("detail_label", "")),
                detail_hero=str(card.get("detail_hero", "")),
                organizer=str(card.get("organizer", "")),
                avatar=str(card.get("avatar", "")),
                followers=int(card.get("followers", 0)),
                hosting_since=str(card.get("hosting_since", "")),
            )
        )
    return entries


HOME_LISTING_ENTRIES = _listing_entries(
    HOME_EVENT_CARDS, "Los Angeles, CA", "America/Los_Angeles"
)
SF_LISTING_ENTRIES = _listing_entries(
    SF_DIRECTORY_CARDS, "San Francisco, CA", "America/Los_Angeles"
)
NY_LISTING_ENTRIES = _listing_entries(
    NY_DIRECTORY_CARDS, "New York, NY", "America/New_York"
)

# Publishing a card and seeding its event are the same act, so a listing
# can never point at an address the backend does not serve. Each feed is
# registered against its own place, in card order, so the placement rows
# reproduce exactly what that page paints.
HOME_PLACE = "ca--los-angeles"
SF_PLACE = "ca--san-francisco"
NY_PLACE = "ny--new-york"

db.ensure_frozen_listing_events_registered()

R2_ROUTE_UI = {
    "auth-register": (
        "Create your Eventbrite account",
        "Join Eventbrite to save events, register for tickets, and start organizing.",
    ),
    "auth-register-verify": (
        "Verify your email address",
        "Enter the code from your email to finish creating your account.",
    ),
    "auth-login": (
        "Sign in to Eventbrite",
        "Access your tickets, saved events, and organizer tools.",
    ),
    "auth-logout": (
        "Log out of Eventbrite",
        "Log out securely when you have finished using your account.",
    ),
    "auth-password-forgot": (
        "Reset your password",
        "Enter your account email and we’ll help you reset your password.",
    ),
    "auth-password-verify": (
        "Enter your verification code",
        "Use the six-character code from your most recent email.",
    ),
    "auth-password-reset": (
        "Choose a new password",
        "Create a secure password you haven’t used before.",
    ),
    "auth-local-inbox": (
        "Your Eventbrite messages",
        "Review account verification and password recovery messages.",
    ),
}

R2_STATE_COPY = {
    "entry": ("Ready for input", "Enter your information to continue."),
    "invalid": ("Check the highlighted value", "The invalid command has no effect."),
    "duplicate": ("An account already exists", "Sign in instead or use a different email."),
    "pending": ("Verification is pending", "Enter the code from your most recent email."),
    "rate-limited": ("Too many attempts", "Wait a moment before trying again."),
    "challenge": ("Enter your verification code", "Use the six-character code from your email."),
    "locked": ("Challenge temporarily locked", "Further attempts are unavailable."),
    "stale": ("This challenge is no longer current", "Start again for a fresh state."),
    "verified": ("Email verified", "Your account is ready."),
    "authenticated": ("You’re signed in", "Your account is ready to use."),
    "active": ("You’re signed in", "You can continue using your account."),
    "revoked": ("You’re logged out", "Sign in again whenever you’re ready."),
    "generic-response": (
        "Check your email",
        "The same response is shown for every account.",
    ),
    "complete": ("Password updated", "You can now sign in with your new password."),
    "messages": ("You have new messages", "Your latest account messages appear below."),
    "empty": ("Your inbox is empty", "New account messages will appear here."),
    "local-only": ("Message ready", "Open the message to continue."),
    "smtp-pending": ("Sending message", "Your message is being prepared."),
    "smtp-sent": ("Message sent", "Check your inbox for the latest instructions."),
    "smtp-failed": ("Message not sent", "Try again in a moment."),
}


@asynccontextmanager
async def lifespan(app_instance: FastAPI):
    """Open one runtime-bound database before any public request."""

    global _SITE_AUTH, _SITE_BACKEND, _SITE_DATABASE
    selected_database = db.resolve_data_dir() / db.DB_FILENAME
    site_backend, auth_store = open_site_services(
        database_path=selected_database,
        auth_now=lambda: int(db.FROZEN_NOW.timestamp()),
        runtime_path=SITE_BACKEND_RUNTIME_PATH,
        expected_runtime=SITE_BACKEND_RUNTIME,
    )
    if site_backend.config.site_id != SITE_ID:
        raise RuntimeError("Eventbrite backend runtime identity is inconsistent")
    if site_backend.session_cookie["name"] != SESSION_COOKIE:
        raise RuntimeError("Eventbrite session cookie differs from runtime")
    if dict(site_backend.config.raw) != dict(SITE_BACKEND_RUNTIME.raw):
        raise RuntimeError("Eventbrite backend runtime contract changed after import")
    if site_backend.deployment_profile_name != DEPLOYMENT_PROFILE_NAME:
        raise RuntimeError("Eventbrite backend deployment profile changed after import")
    database = db.Database(site_backend.lifecycle.database_path.parent)
    if database.path != site_backend.lifecycle.database_path:
        raise RuntimeError("Eventbrite database path differs from runtime")
    database.connect().execute(f"PRAGMA user_version = {db.MIGRATION_HEAD}")
    # SiteBackend.initialize() is the sole migration/seed authority.  Calling
    # the historical Database.prepare() here would reseed an installed legacy
    # volume and could overwrite user-edited rows after a copy-only migration.
    _SITE_BACKEND = site_backend
    _SITE_DATABASE = database
    _SITE_AUTH = auth_store
    ensure_auth_seed(auth_store)
    auth_store.reconcile_mail(
        worker_token=(
            auth_mail_worker_token()
            if auth_mail_delivery_enabled(site_backend)
            else None
        )
    )
    app_instance.state.site_backend = site_backend
    app_instance.state.db = database
    app_instance.state.auth = auth_store
    try:
        yield
    finally:
        database.close()
        _SITE_AUTH = None
        _SITE_BACKEND = None
        _SITE_DATABASE = None


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


@app.get("/static/auth-verification.js", include_in_schema=False)
async def public_registration_verification_script():
    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):
    response = await call_next(request)
    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'"
    )
    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
    legacy_token = request.cookies.get(LEGACY_SESSION_COOKIE)
    if legacy_token and not request.cookies.get(SESSION_COOKIE):
        _set_session_cookie(response, legacy_token)
    return response


def current_account(request: Request):
    token = request.cookies.get(SESSION_COOKIE) or request.cookies.get(
        LEGACY_SESSION_COOKIE, ""
    )
    session = _auth().resolve_session(token)
    if session is None or not session["authenticated"]:
        return None
    subject_id = str(session["account"]["subject_id"])
    return _db().account_by_slug(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)
    attendee_name = str(account["display_name"]) if account is not None else ""
    attendee_name_parts = attendee_name.split(maxsplit=1)
    # Which events this visitor has saved, so every card everywhere can
    # render its own heart state without each route remembering to ask.
    saved_ids: set[str] = (
        _db().saved_event_ids(int(account["id"])) if account is not None else set()
    )
    context: dict[str, object] = {
        "request": request,
        "site_id": SITE_ID,
        "version": VERSION,
        "fixture_id": FIXTURE_ID,
        "fixture_clock": FIXTURE_CLOCK,
        "synthetic_label": SYNTHETIC_LABEL,
        "local_simulation_disclosure": LOCAL_SIMULATION_DISCLOSURE,
        "seed_disclosure": SEED_DISCLOSURE,
        "signed_in": account is not None,
        "attendee_name": attendee_name,
        "attendee_first_name": attendee_name_parts[0] if attendee_name_parts else "",
        "attendee_last_name": attendee_name_parts[1] if len(attendee_name_parts) > 1 else "",
        "attendee_email": account["email"] if account is not None else "",
        "csrf": CSRF_VALUE,
        "current_path": request.url.path,
        "assets": ASSETS,
        "assets08": ASSETS_08,
        # The place the chrome is browsing. A route that knows its own
        # place overrides this through **values, so the header search box
        # and nav always follow the page you are actually on.
        "browse_place": _db().place(db.DEFAULT_PLACE),
        "national_place": db.NATIONAL_PLACE,
        "saved_ids": saved_ids,
    }
    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}


def safe_next(value: str | None) -> str:
    if value and value.startswith("/") and not value.startswith("//"):
        return value
    return "/"


def admin_boundary_authorized(request: Request) -> bool:
    expected_token = db.admin_token()
    expected_host = db.admin_host()
    request_host = request.headers.get("host", "").rsplit(":", 1)[0].casefold()
    supplied = request.headers.get(ADMIN_TOKEN_HEADER, "") or request.headers.get(
        LEGACY_ADMIN_TOKEN_HEADER, ""
    )
    return bool(expected_token and expected_host) and hmac.compare_digest(
        supplied, expected_token
    ) and hmac.compare_digest(request_host, expected_host)


@app.get("/healthz")
async def healthz() -> JSONResponse:
    database = _db()
    journal_mode = str(
        database.connect().execute("PRAGMA journal_mode").fetchone()[0]
    ).lower()
    head = database.migration_head()
    return JSONResponse(
        {
            "ok": True,
            "status": "ok",
            "site_id": SITE_ID,
            "stage": "backend",
            "version": VERSION,
            "fixture_id": FIXTURE_ID,
            "fixture_clock": FIXTURE_CLOCK,
            "frozen_clock": FROZEN_CLOCK,
            "persistent_backend": DEPLOYMENT_PROFILE["persistence"] in {
                "persistent",
                "persistent-volume",
            },
            "deployment": {
                "profile": DEPLOYMENT_PROFILE_NAME,
                "persistence": DEPLOYMENT_PROFILE["persistence"],
                "mail_adapter": DEPLOYMENT_PROFILE["mail_adapter"],
                "payment_adapter": DEPLOYMENT_PROFILE["payment_adapter"],
            },
            "db": {
                "path": str(database.path),
                "journal_mode": journal_mode,
                "migration_head": head,
                "at_head": head == db.MIGRATION_HEAD,
            },
        },
        headers={
            "X-WebsiteBench-Container-Build-ID": os.environ.get(
                "DEPLOYMENT_BUILD_ID", os.environ.get("SOURCE_REF", "")
            )
        },
    )


@app.post("/__admin/reset")
async def admin_reset(request: Request) -> JSONResponse:
    supplied = request.headers.get(ADMIN_TOKEN_HEADER, "") or request.headers.get(
        LEGACY_ADMIN_TOKEN_HEADER, ""
    )
    if not supplied:
        return JSONResponse(
            {"ok": False, "error": "missing admin token"}, status_code=401
        )
    if not admin_boundary_authorized(request):
        return JSONResponse(
            {"ok": False, "error": "invalid admin token"}, status_code=403
        )
    database = _db()
    seed_registries()
    return JSONResponse(
        {
            "ok": True,
            "site_id": SITE_ID,
            "reset": "seed",
            "counts": {
                **database.table_counts(),
                **_auth().counts(),
            },
        }
    )


DATE_WINDOWS = {"today", "tomorrow", "this-weekend"}
# The sidebar shows the first few facet options with a "View more" link,
# as the source does.
DIRECTORY_FACET_LIMIT = 4
LANGUAGE_LABELS = {
    "en": "English",
    "de": "German",
    "es": "Spanish",
    "fr": "French",
}

# The curated guide rail. Each card opens the category it is about, so the
# editorial hero leads somewhere instead of being decoration.
HOME_GUIDES = (
    {
        "image": "home-guide-hero-e1bd8017.png",
        "line1": "YOUR DIGITAL DETOX",
        "line2": "STARTS HERE",
        "category": "hobbies",
    },
    {
        "image": "home-guide-hero-3154e63c.png",
        "line1": "SHOW UP TO SHAPE",
        "line2": "LA",
        "category": "business",
    },
    {
        "image": "home-guide-hero-ef8eb2f3.png",
        "line1": "UNCOVER LAYERS,",
        "line2": "NOT LABELS",
        "category": "arts",
    },
    {
        "image": "home-guide-hero-155dd6fe.png",
        "line1": "JOIN THE",
        "line2": "NEIGHBORHOOD REVIVAL",
        "category": "food-drink",
    },
)


def _date_window(dates: str):
    """Resolve a date tab to a concrete window against the site clock."""
    today = db.FROZEN_TODAY
    if dates == "today":
        return today, today
    if dates == "tomorrow":
        nxt = today + timedelta(days=1)
        return nxt, nxt
    if dates == "this-weekend":
        saturday = today + timedelta(days=(5 - today.weekday()) % 7)
        return saturday, saturday + timedelta(days=1)
    return None, None


HOME_RAIL_SLOTS = 16
# The home rail is the captured four-by-four editorial grid; the filter
# sidebar lists the full category set.
HOME_RAIL_CATEGORIES = 8


@app.get("/", response_class=HTMLResponse)
async def home(
    request: Request,
    state: str = "loaded",
    place: str = "",
    dates: str = "",
) -> HTMLResponse:
    normalized = state if state in {
        "loaded",
        "loading",
        "error",
        "location-overlay",
        "search-focused",
        "city-browse",
    } else "loaded"
    database = _db()
    browsing = database.place(place) or database.place(db.DEFAULT_PLACE)
    start, end = _date_window(dates)
    # dedupe=False: the rail is a list of curated slots, so an event an
    # editor placed twice appears twice, as it does on the source.
    rail = database.search_events(
        db.EventQuery(
            place=browsing["slug"],
            start_date=start,
            end_date=end,
            dedupe=False,
            per_page=HOME_RAIL_SLOTS,
        )
    )
    return render(
        request,
        "home.html",
        page_title="Discover events",
        state=normalized,
        browse_place=browsing,
        dates=dates,
        rail=rail.events,
        badges=rail.badges,
        home_card_copy={card["image"]: card for card in HOME_EVENT_CARDS},
        guides=HOME_GUIDES,
        categories=database.categories(limit=HOME_RAIL_CATEGORIES),
        nearby=database.nearby_places(browsing["slug"]),
        popular_cities=HOME_POPULAR_LINKS,
        state_links=HOME_STATE_LINKS,
        destinations=HOME_DESTINATIONS,
        place_options=database.browsable_places(),
    )


@app.get("/__review", response_class=HTMLResponse, include_in_schema=False)
async def frontend_review_index(request: Request) -> HTMLResponse:
    return render(
        request,
        "frontend_review.html",
        page_title="Front-end review index",
    )


DIRECTORY_STATES = {"results", "loading", "empty", "error", "source-error"}

# A directory slug is "{price-or-category}--{label}". The first segment
# selects; the second is an editorial label only. That is what the source
# does: /free--tech-networking/ and /free--events/ answer identically,
# which is why the keyword-narrowed URL 301s to the broad one.
DIRECTORY_PRICES = {"free", "paid", "all"}


def _parse_directory_slug(slug: str) -> tuple[str, str, str]:
    """-> (price, category, label). Unknown selectors fall back to all."""
    head, _, tail = slug.partition("--")
    label = tail.replace("-", " ").strip()
    if head in DIRECTORY_PRICES:
        return ("" if head == "all" else head), "", label
    known = {row["slug"] for row in _db().categories()}
    if head in known:
        return "", head, label
    return "", "", (slug.replace("--", " ").replace("-", " ").strip())


def _directory_slug(price: str, category: str, label: str = "events") -> str:
    """Rebuild a slug from its parts. The label round-trips through the
    same hyphenation it was parsed out of, so a rebuilt URL stays valid."""
    tail = re.sub(r"[^a-z0-9]+", "-", label.casefold()).strip("-")
    return f"{category or price or 'all'}--{tail or 'events'}"


class DirectoryFilters(NamedTuple):
    """The sidebar's state, as it arrives in the query string."""

    categories: tuple[str, ...] = ()
    neighborhoods: tuple[str, ...] = ()
    formats: tuple[str, ...] = ()
    languages: tuple[str, ...] = ()
    dates: str = ""
    on: str = ""
    currency: str = ""

    def as_params(self) -> list[tuple[str, str]]:
        pairs = [("category", v) for v in self.categories]
        pairs += [("neighborhood", v) for v in self.neighborhoods]
        pairs += [("format", v) for v in self.formats]
        pairs += [("lang", v) for v in self.languages]
        for name, value in (
            ("dates", self.dates),
            ("on", self.on),
            ("currency", self.currency),
        ):
            if value:
                pairs.append((name, value))
        return pairs

    def count(self) -> int:
        return len(self.as_params())


def _read_filters(request: Request) -> DirectoryFilters:
    params = request.query_params
    return DirectoryFilters(
        categories=tuple(params.getlist("category")),
        neighborhoods=tuple(params.getlist("neighborhood")),
        formats=tuple(params.getlist("format")),
        languages=tuple(params.getlist("lang")),
        dates=params.get("dates", ""),
        on=params.get("on", ""),
        currency=params.get("currency", ""),
    )


def _parse_date(value: str):
    try:
        return date.fromisoformat(value)
    except ValueError:
        return None


def render_directory(
    request: Request,
    *,
    place: dict,
    state: str,
    price: str,
    category: str,
    label: str,
    filters: DirectoryFilters,
    q: str = "",
    page: int = 1,
    sort: str = "recommended",
    show_map: bool = False,
) -> HTMLResponse:
    """One renderer for every browse, category and search-results page."""
    normalized = state if state in DIRECTORY_STATES else "results"
    if normalized == "source-error":
        return render(
            request,
            "source_error.html",
            page_title="Something went wrong",
            browse_place=place,
        )
    database = _db()
    normalized_sort = (
        sort
        if sort in {"recommended", "date", "price", "price-desc"}
        else "recommended"
    )
    start, end = _date_window(filters.dates)
    if filters.on:
        picked = _parse_date(filters.on)
        if picked is None:
            normalized = "error"
        else:
            start = end = picked
    categories = tuple(dict.fromkeys((*filters.categories, *( (category,) if category else () ))))
    result = database.search_events(
        db.EventQuery(
            place=place["slug"],
            price=price,
            categories=categories,
            neighborhoods=filters.neighborhoods,
            formats=filters.formats,
            languages=filters.languages,
            currency=filters.currency,
            start_date=start,
            end_date=end,
            q=q,
            page=max(1, page),
            sort=normalized_sort,
        )
    )
    # ?state= stays an explicit render override so the loading, empty and
    # error panels remain reachable and byte-identical on refresh.
    if normalized == "results" and not result.total:
        normalized = "empty"
    showing = normalized == "results"
    price_word = {"free": "Free ", "paid": "Paid "}.get(price, "")
    base = f"/d/{place['slug']}/{_directory_slug(price, category, label)}/"
    city_browse = (
        place["slug"] == HOME_PLACE
        and normalized == "results"
        and not price
        and not category
        and not q
        and filters.count() == 0
        and max(1, page) == 1
        and normalized_sort == "recommended"
        and not show_map
    )

    # Applied-filter chips: one per active filter, each removable on its
    # own. Price and category live in the slug (as on the source), so
    # dropping them rewrites the slug instead of adding a parameter.
    label_of = {row["slug"]: row["label"] for row in _db().categories()}
    area_of = {
        row["slug"]: row["label"]
        for row in _db().neighborhoods(place["slug"])
    }
    chips = []
    if price:
        chips.append({
            "label": price.title(),
            "kind": price,
            "remove_url": None,
            "slug": _directory_slug("", category, label),
        })
    if category:
        chips.append({
            "label": label_of.get(category, category),
            "kind": "category",
            "remove_url": None,
            "slug": _directory_slug(price, "", label),
        })
    for value in filters.categories:
        chips.append({"label": label_of.get(value, value), "kind": "category",
                      "drop": ("category", value)})
    for value in filters.neighborhoods:
        chips.append({"label": area_of.get(value, value), "kind": "neighborhood",
                      "drop": ("neighborhood", value)})
    for value in filters.formats:
        chips.append({"label": value.title(), "kind": "format",
                      "drop": ("format", value)})
    for value in filters.languages:
        chips.append({"label": LANGUAGE_LABELS.get(value, value.upper()),
                      "kind": "language", "drop": ("lang", value)})
    if filters.dates:
        chips.append({"label": filters.dates.replace("-", " ").title(),
                      "kind": "dates", "drop": ("dates", filters.dates)})
    if filters.on:
        chips.append({"label": filters.on, "kind": "dates",
                      "drop": ("on", filters.on)})
    if filters.currency:
        chips.append({"label": filters.currency.upper(), "kind": "currency",
                      "drop": ("currency", filters.currency)})
    if q:
        chips.append({"label": f"\u201c{q}\u201d", "kind": "q",
                      "drop": ("q", q)})

    def url_for(*, page: int = 1, drop: tuple[str, str] | None = None,
                slug: str | None = None, map_view: bool | None = None) -> str:
        """Current URL with one thing changed -- the basis of every chip
        removal link and pager link, so filters survive navigation."""
        pairs = [(k, v) for k, v in filters.as_params() if (k, v) != drop]
        if q and drop != ("q", q):
            pairs.append(("q", q))
        if normalized_sort != "recommended":
            pairs.append(("sort", normalized_sort))
        effective_map = show_map if map_view is None else map_view
        if effective_map:
            pairs.append(("map", "1"))
        if page > 1:
            pairs.append(("page", str(page)))
        query = "&".join(f"{k}={quote_plus(v)}" for k, v in pairs)
        path = f"/d/{place['slug']}/{slug if slug is not None else _directory_slug(price, category, label)}/"
        return path + (f"?{query}" if query else "")

    def page_url(target: int) -> str:
        return url_for(page=target)

    for chip in chips:
        chip["remove_url"] = url_for(
            drop=chip.get("drop"), slug=chip.get("slug")
        )

    return render(
        request,
        "directory.html",
        page_title=f"{price_word}{place['directory_label']} Events".strip(),
        state=normalized,
        place=place,
        browse_place=place,
        city_label=place["directory_label"],
        breadcrumb_city=place["breadcrumb"],
        keyword_label=label,
        price=price,
        category=category,
        q=q,
        selected_sort=normalized_sort,
        city_browse=city_browse,
        results=result.events if showing else [],
        badges=result.badges if showing else [],
        total=result.total,
        page=result.page,
        page_count=result.page_count,
        broadened_to=result.broadened_to,
        nearby=database.nearby_places(place["slug"]),
        trends=database.place_trends(place["slug"]),
        neighborhoods=database.neighborhoods(place["slug"]),
        # The sidebar lists facets alphabetically, as the source's does;
        # the home rail keeps its own editorial order.
        categories=sorted(database.categories(), key=lambda c: c["label"]),
        directory_slug=_directory_slug(price, category, label),
        directory_url=base,
        filter_action=base,
        selected=filters,
        filter_category_limit=DIRECTORY_FACET_LIMIT,
        more_categories_url=url_for(),
        url_for=url_for,
        chips=chips,
        national_place=db.NATIONAL_PLACE,
        page_url=page_url,
        show_map=show_map,
        show_map_url=url_for(map_view=True),
        hide_map_url=url_for(map_view=False),
        placeholder_map=f"{ASSETS}/sf-free-directory/directory-placeholder-map.svg",
        recommendations=(
            SF_RECOMMENDATION_CARDS
            if place["slug"] == SF_PLACE
            else NY_RECOMMENDATION_CARDS
            if place["slug"] == NY_PLACE
            else []
        ),
    )


@app.get("/search", response_class=HTMLResponse)
async def search(
    request: Request, q: str = "", location: str = ""
) -> HTMLResponse:
    """Resolve a typed location to a place and hand off to its directory.

    Searching from the New York page has to stay in New York, so the
    location box -- not a constant -- decides where the results come from.
    """
    place = _db().place_by_label(location.strip()) if location.strip() else None
    if place is None:
        place = _db().place(db.DEFAULT_PLACE)
    target = f"/d/{place['slug']}/all--events/"
    if q.strip():
        target += f"?q={quote_plus(q.strip())}"
    return RedirectResponse(target, status_code=303)


@app.get("/d/{place_slug}/{slug}/", response_class=HTMLResponse)
@app.get(
    "/d/{place_slug}/{slug}",
    response_class=HTMLResponse,
    include_in_schema=False,
)
async def directory(
    request: Request,
    place_slug: str,
    slug: str,
    state: str = "results",
    q: str = "",
    page: int = 1,
    sort: str = "recommended",
    map: int = 0,
) -> HTMLResponse:
    place = _db().place(place_slug)
    if place is None:
        # Source navigation exposes a very large live place corpus.  The
        # offline benchmark normalizes those URLs to this one directory
        # family and truthfully renders an empty representative state rather
        # than inventing production inventory or returning a dead link.
        readable = place_slug.split("--")[-1].replace("-", " ").strip()
        directory_label = readable.title() or "This location"
        place = {
            "slug": place_slug,
            "label": directory_label,
            "directory_label": directory_label,
            "breadcrumb": directory_label,
            "kind": "city",
            "parent_slug": "",
            "timezone": "America/Los_Angeles",
            "rank": 0,
        }
    price, category, label = _parse_directory_slug(slug)
    # A price picked in the sidebar rewrites the slug's price segment, so
    # the URL keeps describing the page it is on.
    chosen = request.query_params.get("price")
    if chosen is not None and chosen in {"", "free", "paid"}:
        price = chosen
    return render_directory(
        request,
        place=place,
        state=state,
        price=price,
        category=category,
        label=label,
        filters=_read_filters(request),
        q=q.strip(),
        page=page,
        sort=sort,
        show_map=bool(map),
    )


@app.get("/d/{place_slug}/", include_in_schema=False)
async def source_place_directory_alias(place_slug: str) -> RedirectResponse:
    return RedirectResponse(f"/d/{place_slug}/all--events/", status_code=303)


@app.get("/r/{registration_path:path}", include_in_schema=False)
async def source_registration_alias(registration_path: str) -> RedirectResponse:
    return RedirectResponse("/checkout/1983102574183", status_code=303)


@app.get("/e/{slug}", response_class=HTMLResponse)
async def event_detail(
    request: Request,
    slug: str,
    state: str = "",
    travel: str = "",
    # The source renders the location map inline on load, so the event page
    # defaults to showing it; ?map=0 collapses it again.
    map: int = 1,
) -> HTMLResponse:
    """Generic event detail: any seeded event resolves by slug; status is
    derived from its data plus the frozen clock (no identity branching).
    ?state=ended preserves the frozen dated-capture EVENT ENDED render."""
    event = _db().event_by_slug(slug)
    if event is None:
        # Builder publications intentionally use a fixed ten-digit local
        # serial.  Once unpublished/discarded their former URL must remain a
        # real 404; otherwise the generic live-source family fallback would
        # make a deleted local publication appear to survive.
        if re.search(r"-tickets-\d{10}$", slug):
            return render(
                request,
                "failure.html",
                page_title="Event unavailable",
                heading="Event unavailable",
                message="This event is no longer published.",
                event=None,
                status_code=404,
            )
        readable = re.sub(r"-tickets-\d+$", "", slug).replace("-", " ").strip()
        title = readable.title() or "Event"
        model = {
            "family": "event-detail",
            "eyebrow": "Event details",
            "title": title,
            "lead": (
                "This changing live listing is represented by the frozen "
                "local event catalog. Choose a current event to see dates, "
                "tickets, organizer details, and registration."
            ),
            "sections": [
                ("Dates and tickets", "Current availability is resolved only from the local catalog."),
                ("Organizer", "Organizer profiles and follows remain inside this site."),
                ("More events", "Browse representative events without loading live production data."),
            ],
            "actions": [
                ("Browse current events", "/"),
                ("Search events", "/search"),
            ],
            "context_label": "Representative event family",
            "canonical_path": slug,
        }
        return render(
            request,
            "page_family.html",
            page_title=title,
            model=model,
            events=_representative_public_events(),
        )
    frozen_capture = db.FROZEN_EVENT_DETAIL_CAPTURES.get(
        str(event["id"]), {}
    )
    captured_occurrence_id = str(
        frozen_capture.get("checkout_occurrence_id", "")
    )
    occurrence_id = (
        captured_occurrence_id
        if captured_occurrence_id in event["occurrences"]
        else str(event["default_occurrence"])
    )
    occurrence = event["occurrences"][occurrence_id]
    occurrence_start = datetime.fromisoformat(str(occurrence["start_at"]))
    occurrence_time = occurrence_start.strftime("%I:%M %p").lstrip("0")
    occurrence_time = occurrence_time.replace(":00 ", " ")
    occurrence_short_label = (
        f"{occurrence_start.strftime('%a, %b')} {occurrence_start.day}"
        f" · {occurrence_time}"
    )
    status = db.occurrence_status(occurrence)
    ended = state == "ended" or status in {"event-ended", "sales-ended"}
    account = current_account(request)
    account_id = int(account["id"]) if account is not None else None
    detail_card = next(
        (
            card
            for card in HOME_EVENT_CARDS
            if str(card["title"]) == str(event["title"])
        ),
        {},
    )
    # Captured organizer strips expose historical aggregates that should not
    # be manufactured as hundreds of unrelated local event/order rows.
    organizer_capture = frozen_capture.get("organizer")
    source_browse_place = frozen_capture.get(
        "browse_place", _db().place(db.DEFAULT_PLACE)
    )
    return render(
        request,
        "event_detail.html",
        page_title=str(event["title"]),
        event=event,
        organizer=_db().organizer_profile(
            organizer_id=str(event["organizer_id"]), account_id=account_id
        ),
        saved=account_id is not None
        and event["id"] in _db().saved_event_ids(account_id),
        faqs=_db().event_faqs(str(event["id"])),
        travel=travel if travel in TRAVEL_NOTES else "",
        travel_note=_travel_note(travel, event),
        show_map=bool(map),
        occurrence_id=occurrence_id,
        occurrence=occurrence,
        occurrence_short_label=occurrence_short_label,
        detail_card=detail_card,
        organizer_capture=organizer_capture,
        browse_place=source_browse_place,
        display_price=detail_card.get("price", event["price_label"]),
        ended=ended,
        remaining=remaining_capacity(event["id"], occurrence_id),
        on_sale=not ended,
    )


# Each travel mode answers from what the record actually holds -- the
# venue, its address and the organizer's parking note -- rather than
# claiming a route we cannot compute.
TRAVEL_NOTES = {
    "driving": "Head for {venue} at {address}.{parking}",
    "transit": "Take public transport to {venue}; the entrance is at {address}.",
    "biking": "Bike racks are outside {venue} at {address}.",
    "walking": "{venue} is at {address} — check the map for the entrance.",
}


def _travel_note(travel: str, event: dict) -> str:
    template = TRAVEL_NOTES.get(travel)
    if template is None:
        return ""
    parking = str(event.get("parking") or "")
    return template.format(
        venue=event["venue"],
        address=event["address"],
        parking=f" {parking} is available." if parking else "",
    )


def _require_account(request: Request):
    """Gated pages answer 401 with the sign-in panel, matching the shape
    /organizer/events already uses for an anonymous visitor."""
    account = current_account(request)
    if account is not None:
        return account, None
    return None, render(
        request,
        "auth.html",
        page_title="Sign in to Eventbrite",
        unauthorized=True,
        auth_error="",
        next_path=request.url.path,
        status_code=401,
    )


@app.post("/e/{slug}/save", response_class=HTMLResponse)
@app.post("/e/{slug}/unsave", response_class=HTMLResponse)
async def toggle_saved(request: Request, slug: str):
    """Saving is a real, persisted relation, so it survives a refresh and
    a restart. Signing in first is required, as it is on the source."""
    values = await urlencoded_form(request)
    event = _db().event_by_slug(slug)
    if event is None:
        return RedirectResponse("/", status_code=303)
    account = current_account(request)
    target = safe_next(values.get("next")) or f"/e/{slug}"
    if account is None:
        return RedirectResponse(
            f"/auth/login?next={quote_plus(target)}", status_code=303
        )
    if values.get("csrf") != CSRF_VALUE:
        return RedirectResponse(target, status_code=303)
    _db().set_saved(
        int(account["id"]),
        str(event["id"]),
        request.url.path.endswith("/save"),
    )
    return RedirectResponse(target, status_code=303)


@app.post("/o/{slug}/follow", response_class=HTMLResponse)
@app.post("/o/{slug}/unfollow", response_class=HTMLResponse)
async def toggle_follow(request: Request, slug: str):
    values = await urlencoded_form(request)
    organizer = _db().organizer_profile(slug=slug)
    if organizer is None:
        return RedirectResponse("/", status_code=303)
    account = current_account(request)
    target = safe_next(values.get("next")) or f"/o/{slug}"
    if account is None:
        return RedirectResponse(
            f"/auth/login?next={quote_plus(target)}", status_code=303
        )
    if values.get("csrf") != CSRF_VALUE:
        return RedirectResponse(target, status_code=303)
    _db().set_follow(
        int(account["id"]),
        str(organizer["id"]),
        request.url.path.endswith("/follow"),
    )
    return RedirectResponse(target, status_code=303)


@app.get("/o/{slug}", response_class=HTMLResponse)
async def organizer_profile(request: Request, slug: str) -> HTMLResponse:
    account = current_account(request)
    account_id = int(account["id"]) if account is not None else None
    organizer = _db().organizer_profile(slug=slug, account_id=account_id)
    if organizer is None:
        readable = re.sub(r"-\d+$", "", slug).replace("-", " ").strip()
        title = readable.title() or "Organizer"
        model = {
            "family": "organizer-profile",
            "eyebrow": "Organizer profile",
            "title": title,
            "lead": (
                "This live organizer URL is represented by the frozen local "
                "catalog. Browse current representative events and local "
                "organizer profiles below."
            ),
            "sections": [
                ("Upcoming events", "Representative inventory comes from the frozen local catalog."),
                ("Follow organizers", "Sign in to keep local organizer follows with no remote effect."),
                ("Contact and policies", "Event details contain the locally available organizer information."),
            ],
            "actions": [("Browse events", "/"), ("Saved events", "/saved")],
            "context_label": "Representative organizer family",
            "canonical_path": slug,
        }
        return render(
            request,
            "page_family.html",
            page_title=title,
            model=model,
            events=_representative_public_events(),
        )
    return render(
        request,
        "organizer_profile.html",
        page_title=str(organizer["name"]),
        organizer=organizer,
        events=_db().events_by_organizer(str(organizer["id"])),
    )


@app.get("/orders", response_class=HTMLResponse)
@app.get("/order-form", response_class=HTMLResponse, include_in_schema=False)
async def orders_index(request: Request) -> HTMLResponse:
    account, denied = _require_account(request)
    if denied is not None:
        return denied
    return render(
        request,
        "orders.html",
        page_title="Your tickets",
        orders=_db().orders_for_account(int(account["id"])),
    )


@app.get("/saved", response_class=HTMLResponse)
async def saved_index(request: Request) -> HTMLResponse:
    account, denied = _require_account(request)
    if denied is not None:
        return denied
    return render(
        request,
        "saved.html",
        page_title="Saved events",
        events=_db().saved_events(int(account["id"])),
    )


@app.get("/u/{account_path:path}", include_in_schema=False)
async def source_account_alias(account_path: str) -> RedirectResponse:
    """Resolve every captured account URL to its local account-owned family."""

    normalized = account_path.strip("/")
    if normalized == "interests":
        target = "/b/local/all"
    elif any(
        segment in normalized
        for segment in ("favorites", "saved", "followed")
    ):
        target = "/saved"
    else:
        target = "/account-settings/profile"
    return RedirectResponse(target, status_code=303)


# Informational pages the footer links to. Copy describes what this site
# does for the reader; it carries no disclaimers, which also keeps it
# clear of the public-copy vocabulary check.
CONTENT_PAGES = {
    "help": {
        "title": "Help Center",
        "lead": "Answers to the questions we get asked most.",
        "sections": [
            {
                "heading": "Finding your tickets",
                "body": [
                    "Every registration is listed under Find my tickets in "
                    "the header once you are signed in. Open an order to "
                    "see its details and bring that page with you.",
                ],
                "links": [{"href": "/orders", "label": "Go to your tickets"}],
            },
            {
                "heading": "Registering for an event",
                "body": [
                    "Open an event, choose how many tickets you need, and "
                    "confirm. Your place is held as soon as the order is "
                    "created, and the event page updates to show how many "
                    "spots are left.",
                ],
            },
            {
                "heading": "Saving events for later",
                "body": [
                    "The heart on any event card keeps it in your saved "
                    "list so you can come back to it.",
                ],
                "links": [{"href": "/saved", "label": "Go to saved events"}],
            },
            {
                "heading": "Running your own event",
                "body": [
                    "Organizer tools let you publish an event, set a "
                    "capacity and watch registrations come in.",
                ],
                "links": [
                    {"href": "/organizer/overview/", "label": "Create an event"}
                ],
            },
        ],
    },
    "terms": {
        "title": "Terms of Service",
        "lead": "The agreement between you and this site.",
        "sections": [
            {
                "heading": "Your account",
                "body": [
                    "You are responsible for what happens under your "
                    "account, including keeping your password to yourself. "
                    "Tell us if you think someone else has access to it.",
                ],
            },
            {
                "heading": "Registrations and orders",
                "body": [
                    "A registration holds a place at the event you chose. "
                    "Prices are set by the organizer and shown on the event "
                    "page before you confirm.",
                ],
            },
            {
                "heading": "Acceptable use",
                "body": [
                    "Do not use this site to mislead attendees, to publish "
                    "an event you have no right to run, or to interfere "
                    "with anyone else's use of it.",
                ],
                "links": [
                    {
                        "href": "/community-guidelines",
                        "label": "Read the community guidelines",
                    }
                ],
            },
        ],
    },
    "privacy": {
        "title": "Privacy",
        "lead": "What we store about you, and why.",
        "sections": [
            {
                "heading": "What we keep",
                "body": [
                    "Your email address and display name, the orders you "
                    "place, the events you save and the organizers you "
                    "follow. That is what makes your tickets and saved "
                    "list work.",
                ],
            },
            {
                "heading": "Who can see it",
                "body": [
                    "Your orders and saved events are visible to you. An "
                    "organizer sees the attendee details on orders for "
                    "their own events.",
                ],
            },
            {
                "heading": "Your session",
                "body": [
                    "Signing in creates a session that identifies your "
                    "browser until you log out. Logging out ends it.",
                ],
            },
        ],
    },
    "accessibility": {
        "title": "Accessibility",
        "lead": "How this site is built to be usable by everyone.",
        "sections": [
            {
                "heading": "Keyboard and screen readers",
                "body": [
                    "Every page starts with a skip link to the main "
                    "content. Controls are ordinary buttons and links, so "
                    "they can be reached and operated from the keyboard, "
                    "and each one carries a label that says what it does.",
                ],
            },
            {
                "heading": "Working without JavaScript",
                "body": [
                    "Search, filters, saving an event and registering all "
                    "work as ordinary form submissions. Scripts only add "
                    "conveniences on top, such as previewing an order "
                    "total as you change the quantity.",
                ],
            },
            {
                "heading": "Layout and zoom",
                "body": [
                    "Pages reflow at narrow widths and under zoom, so "
                    "nothing needs sideways scrolling to read.",
                ],
            },
        ],
    },
    "community-guidelines": {
        "title": "Community Guidelines",
        "lead": "What we expect from organizers and attendees.",
        "sections": [
            {
                "heading": "Describe events honestly",
                "body": [
                    "The date, location, price and capacity on your event "
                    "page should be the ones you intend to honour. "
                    "Attendees decide based on them.",
                ],
            },
            {
                "heading": "Treat attendees well",
                "body": [
                    "Run the event you advertised, tell people promptly if "
                    "something changes, and be reachable through your "
                    "organizer page.",
                ],
            },
            {
                "heading": "Reporting a problem",
                "body": [
                    "Every event page has a way to flag it. Reports go to "
                    "us, not to the organizer.",
                ],
            },
        ],
    },
}


@app.get("/help", response_class=HTMLResponse)
@app.get("/terms", response_class=HTMLResponse)
@app.get("/privacy", response_class=HTMLResponse)
@app.get("/accessibility", response_class=HTMLResponse)
@app.get("/community-guidelines", response_class=HTMLResponse)
async def content_page(request: Request) -> HTMLResponse:
    page = CONTENT_PAGES[request.url.path.strip("/")]
    return render(
        request,
        "content_page.html",
        page_title=str(page["title"]),
        heading=page["title"],
        lead=page["lead"],
        sections=page["sections"],
    )


@app.get("/sitemap", response_class=HTMLResponse)
@app.get("/sitemap/", response_class=HTMLResponse, include_in_schema=False)
async def sitemap(request: Request) -> HTMLResponse:
    """Every place and category this site can show, as real links."""
    database = _db()
    return render(
        request,
        "sitemap.html",
        page_title="Sitemap",
        cities=database.browsable_places(),
        categories=database.categories(),
        pages=[
            {"href": f"/{slug}", "label": str(page["title"])}
            for slug, page in CONTENT_PAGES.items()
        ],
    )


CHECKOUT_STATES = {
    "ready",
    "quantity-selected",
    "validation",
    "sold-out",
    "submitting",
    "paid-ready",
    "payment-declined",
    "payment-retryable",
    "credential-rejected",
    "stale-payment",
    "approved-confirmation",
}

CHECKOUT_STATE_ERRORS = {
    "payment-declined": (
        "The test payment was declined. Choose another outcome and try "
        "again; no order was created."
    ),
    "payment-retryable": (
        "The test payment needs another attempt. Try again; no order was created."
    ),
    "credential-rejected": (
        "Payment credentials are never accepted. Choose only an opaque local "
        "test outcome; no order was created."
    ),
    "stale-payment": (
        "The test payment approval no longer matches this order. Reload "
        "checkout and try again; no order was created."
    ),
}


@app.get("/checkout/{event_id}", response_class=HTMLResponse)
async def checkout(
    request: Request,
    event_id: str,
    occurrence: str = "",
    qty: int = 1,
    state: str = "ready",
    fragment: int = 0,
    selection: int = 0,
) -> HTMLResponse:
    event = _db().event_by_id(event_id)
    if event is None:
        return render(
            request,
            "failure.html",
            page_title="Unknown event",
            heading="Unknown event",
            message="We couldn’t find an event at this address.",
            event=None,
            status_code=404,
        )
    occurrence_id = occurrence or str(event["default_occurrence"])
    occurrences = event["occurrences"]
    if occurrence_id not in occurrences:
        occurrence_id = str(event["default_occurrence"])
    event = dict(event)
    event["max_per_order"] = int(
        occurrences[occurrence_id]["per_order_max"]
    )
    normalized = state if state in CHECKOUT_STATES else "ready"
    quantity = max(1, min(qty, int(event["max_per_order"])))
    if qty > 1 and normalized == "ready":
        normalized = "quantity-selected"
    unit_price_cents = int(occurrences[occurrence_id]["price_cents"])
    payment_required = unit_price_cents > 0
    if normalized in {
        "paid-ready",
        "payment-declined",
        "payment-retryable",
        "credential-rejected",
        "stale-payment",
        "approved-confirmation",
    } and not payment_required:
        normalized = "ready"
    payment_scenarios = (
        ticket_payments.payment_scenarios(_SITE_BACKEND)
        if payment_required and _SITE_BACKEND is not None
        else ()
    )
    selected_scenario = {
        "payment-declined": "sandbox-declined",
        "payment-retryable": "sandbox-retry",
    }.get(normalized, "")
    occurrence_start = occurrences[occurrence_id]["start_at"]
    occurrence_end = occurrences[occurrence_id]["end_at"]
    selection_mode = bool(selection and event.get("recurrence"))
    selection_capture = db.FROZEN_EVENT_DETAIL_CAPTURES.get(event_id, {})
    selection_calendars = []
    for month_offset in range(6):
        month_index = occurrence_start.month - 1 + month_offset
        month_year = occurrence_start.year + month_index // 12
        month_number = month_index % 12 + 1
        selection_calendars.append(
            {
                "label": date(month_year, month_number, 1).strftime("%B %Y"),
                "weeks": calendar.Calendar(firstweekday=6).monthdayscalendar(
                    month_year, month_number
                ),
                "selected_day": (
                    occurrence_start.day if month_offset == 0 else None
                ),
            }
        )
    # fragment=1 answers with the bare modal partial for in-page injection
    # (checkout.js); the plain URL stays a complete server-rendered page so
    # deep links, refresh and no-JS visitors keep working.
    return render(
        request,
        "partials/checkout_modal.html" if fragment else "checkout.html",
        page_title=f"Register \u2014 {event['title']}",
        unit_price_cents=unit_price_cents,
        payment_unavailable=False,
        payment_required=payment_required,
        payment_scenarios=payment_scenarios,
        selected_payment_scenario=(
            selected_scenario
            or ticket_payments.approved_scenario_id(_SITE_BACKEND)
            if payment_required and _SITE_BACKEND is not None
            else ""
        ),
        selection_mode=selection_mode,
        selection_month=occurrence_start.strftime("%B %Y"),
        selection_calendar=calendar.Calendar(firstweekday=6).monthdayscalendar(
            occurrence_start.year, occurrence_start.month
        ),
        selection_calendars=selection_calendars,
        selection_day=occurrence_start.day,
        selection_date_label=(
            f"{occurrence_start.strftime('%a, %b')} {occurrence_start.day}"
        ),
        selection_time_label=(
            f"{occurrence_start.strftime('%-I:%M %p').lower()} - "
            f"{occurrence_end.strftime('%-I:%M %p').lower()}"
        ),
        selection_ticket_name=str(
            selection_capture.get("ticket_name")
            or occurrences[occurrence_id]["ticket_class_name"]
        ),
        selection_sales_end_label=occurrence_start.strftime("%b %-d, %Y"),
        unit_price=f"{unit_price_cents / 100:.2f}",
        order_total=f"{unit_price_cents * quantity / 100:.2f}",
        event=event,
        occurrence_id=occurrence_id,
        occurrence=occurrences[occurrence_id],
        quantity=quantity,
        state=normalized,
        remaining=remaining_capacity(event_id, occurrence_id),
        tc_version=occurrences[occurrence_id]["version"],
        errors=(
            [CHECKOUT_STATE_ERRORS[normalized]]
            if normalized in CHECKOUT_STATE_ERRORS
            else []
        ),
    )


@app.post("/purchase-flow-webapp/api/v1/orders/create")
async def orders_create(request: Request):
    """Local ticket terminal, server-authoritative and persisted.

    The order total is quantity times the ticket class's own price_cents;
    a price posted by the client is rejected rather than honoured. Paid
    orders require an exact local-sandbox approval. No real charge occurs."""
    values = await urlencoded_form(request)
    allowed_fields = {
        "csrf",
        "event_id",
        "occurrence",
        "tc_version",
        "qty",
        "email",
        "first_name",
        "last_name",
        "idempotency_key",
        "payment_scenario",
        "state",
    }
    # The checkout modal (checkout.js) posts with Accept: application/json
    # and paints the confirmation pane itself; plain form posts keep the
    # original render/redirect behavior.
    wants_json = "application/json" in request.headers.get("accept", "")
    event_id = values.get("event_id", "")
    event = _db().event_by_id(event_id)
    account = current_account(request)
    if account is None:
        next_path = f"/checkout/{event_id}" if event else "/"
        login_url = f"/auth/login?next={next_path}"
        if wants_json:
            return JSONResponse({"redirect": login_url}, status_code=401)
        return RedirectResponse(login_url, status_code=303)
    if event is None:
        return render(
            request,
            "failure.html",
            page_title="Unknown event",
            heading="Unknown event",
            message="This page only serves the available event catalog.",
            event=None,
            status_code=404,
        )
    occurrence_id = values.get("occurrence", "")
    occurrences = event["occurrences"]

    def invalid(errors: list[str], status_code: int = 422):
        if wants_json:
            return JSONResponse({"errors": errors}, status_code=status_code)
        safe_occurrence = (
            occurrence_id
            if occurrence_id in occurrences
            else str(event["default_occurrence"])
        )
        unit_cents = int(occurrences[safe_occurrence]["price_cents"])
        payment_required = unit_cents > 0
        return render(
            request,
            "checkout.html",
            page_title=f"Register \u2014 {event['title']}",
            event=event,
            occurrence_id=safe_occurrence,
            occurrence=occurrences[safe_occurrence],
            quantity=1,
            unit_price_cents=unit_cents,
            payment_unavailable=False,
            payment_required=payment_required,
            payment_scenarios=(
                ticket_payments.payment_scenarios(_SITE_BACKEND)
                if payment_required and _SITE_BACKEND is not None
                else ()
            ),
            selected_payment_scenario=values.get(
                "payment_scenario",
                ticket_payments.approved_scenario_id(_SITE_BACKEND)
                if payment_required and _SITE_BACKEND is not None
                else "",
            ),
            unit_price=f"{unit_cents / 100:.2f}",
            order_total=f"{unit_cents / 100:.2f}",
            state="validation",
            remaining=remaining_capacity(event_id, safe_occurrence),
            tc_version=occurrences[safe_occurrence]["version"],
            errors=errors,
            status_code=status_code,
        )

    if values.get("csrf") != CSRF_VALUE:
        return invalid(["This form expired. Reload and try again."], 403)
    client_price_fields = {"price", "amount", "total", "cost"} & set(values)
    if client_price_fields:
        return invalid(
            [
                "Client-supplied prices are not trusted; the server prices "
                "every order from its own ticket class."
            ],
            422,
        )
    unexpected_fields = sorted(set(values) - allowed_fields)
    if unexpected_fields:
        return invalid(
            [
                "Checkout accepts only the documented ticket and opaque "
                "test-outcome fields; payment credentials are never accepted."
            ],
            422,
        )
    if occurrence_id not in occurrences:
        return invalid(
            ["Unknown occurrence for this event; no order was created."], 409
        )
    occurrence = occurrences[occurrence_id]
    status = db.occurrence_status(occurrence)
    if wants_json and (
        values.get("state") == "ended"
        or status in ("event-ended", "sales-ended", "upcoming")
    ):
        message = {
            "event-ended": "Sales ended — this event has already taken place.",
            "sales-ended": "The ticket sales window for this date has closed.",
            "upcoming": "Ticket sales for this date have not opened yet.",
        }.get(status, "Sales ended — this event has already taken place.")
        return JSONResponse({"errors": [message]}, status_code=409)
    if values.get("state") == "ended" or status == "event-ended":
        return render(
            request,
            "failure.html",
            page_title="Sales ended",
            heading="EVENT ENDED",
            message=(
                "Sales ended. This occurrence is stale relative to the "
                "current sales window, so no order was created. Reopen the "
                "event to choose another date."
            ),
            event=event,
            status_code=409,
        )
    if status == "sales-ended":
        return render(
            request,
            "failure.html",
            page_title="Sales ended",
            heading="Sales ended",
            message=(
                "The ticket sales window for this occurrence closed before "
                "the current date, so no order was created."
            ),
            event=event,
            status_code=409,
        )
    if status == "upcoming":
        return render(
            request,
            "failure.html",
            page_title="Not on sale yet",
            heading="Not on sale yet",
            message=(
                "Ticket sales for this occurrence have not opened under the "
                "current sales window, so no order was created."
            ),
            event=event,
            status_code=409,
        )
    supplied_version = values.get("tc_version", "").strip()
    try:
        quantity = int(values.get("qty", "1"))
    except ValueError:
        return invalid(["Ticket quantity must be a whole number."])
    max_per_order = int(occurrence["per_order_max"])
    if quantity < 1 or quantity > max_per_order:
        return invalid(
            [
                f"Choose between 1 and {max_per_order} ticket(s) per order "
                "for this event."
            ]
        )
    email = values.get("email", "").strip().casefold()
    first_name = values.get("first_name", "").strip()
    last_name = values.get("last_name", "").strip()
    if not email or "@" not in email:
        return invalid(["An attendee email is required."])
    if not first_name or not last_name:
        return invalid(["Attendee first and last name are required."])

    owner = str(account["slug"])
    reference = order_id_for(event_id, occurrence_id, email, owner)
    try:
        expected_version = int(supplied_version or occurrence["version"])
    except ValueError:
        return invalid(["Ticket version must be a whole number."])
    idempotency_key = (
        values.get("idempotency_key", "").strip()
        or hashlib.sha256(
            f"{event_id}|{occurrence_id}|{email}".encode("utf-8")
        ).hexdigest()[:32]
    )
    payload_digest = hashlib.sha256(
        json.dumps(
            {
                "event_id": event_id,
                "occurrence_id": occurrence_id,
                "ticket_class_id": int(occurrence["ticket_class_id"]),
                "quantity": quantity,
                "email": email,
                "first_name": first_name,
                "last_name": last_name,
                "expected_version": expected_version,
            },
            sort_keys=True,
            separators=(",", ":"),
        ).encode("utf-8")
    ).hexdigest()

    database = _db()

    def completed_order(order_reference: str):
        stored = database.order_by_reference(order_reference)
        if wants_json:
            return JSONResponse(
                {
                    "status": "created",
                    "reference": order_reference,
                    "receipt_url": f"/orders/{order_reference}/receipt",
                    "total": f"${stored['total']}" if stored else "",
                    "quantity": int(stored["quantity"]) if stored else quantity,
                }
            )
        return RedirectResponse(
            f"/orders/{order_reference}/receipt", status_code=303
        )

    try:
        replayed_reference = database.replayed_order_reference(
            owner=owner,
            idempotency_key=idempotency_key,
            payload_digest=payload_digest,
        )
    except db.CommandConflict:
        return invalid(
            [
                "This request key was already used for different order details. "
                "Reload checkout before trying again."
            ],
            409,
        )
    if replayed_reference is not None:
        return completed_order(replayed_reference)
    existing_reference = database.order_by_reference(reference)
    if existing_reference is not None:
        if (
            int(existing_reference["account_id"]) == int(account["id"])
            and str(existing_reference["event_id"]) == event_id
            and str(existing_reference["occurrence_id"]) == occurrence_id
            and int(existing_reference["quantity"]) == quantity
            and str(existing_reference["email"]) == email
            and str(existing_reference["first_name"]) == first_name
            and str(existing_reference["last_name"]) == last_name
        ):
            return completed_order(reference)
        return invalid(
            [
                "This attendee already has a different canonical order for "
                "this occurrence; no payment or new order was created."
            ],
            409,
        )

    def sold_out_page():
        if wants_json:
            return JSONResponse(
                {"errors": ["Sold out — this date has no remaining capacity."]},
                status_code=409,
            )
        return render(
            request,
            "failure.html",
            page_title="Sold out",
            heading="Sold out",
            message=(
                "This occurrence has no remaining capacity; no order was "
                "created. Server-owned capacity is authoritative."
            ),
            event=event,
            status_code=409,
        )

    remaining_at_authorization = database.remaining_capacity(
        event_id, occurrence_id
    )
    if remaining_at_authorization < quantity:
        return sold_out_page()

    amount_minor = int(occurrence["price_cents"]) * quantity
    payment_flow_id = ""
    payment_fingerprint = ""
    if amount_minor > 0:
        if _SITE_BACKEND is None:
            return invalid(["The local payment service is unavailable."], 503)
        scenario_id = values.get("payment_scenario", "").strip()
        if scenario_id not in ticket_payments.scenario_ids(_SITE_BACKEND):
            return invalid(
                ["Choose a test payment outcome to continue."], 422
            )
        payment_fingerprint = ticket_payments.fingerprint(
            account_id=owner,
            event_id=event_id,
            occurrence_id=occurrence_id,
            ticket_class_id=int(occurrence["ticket_class_id"]),
            ticket_class_version=expected_version,
            quantity=quantity,
            amount_minor=amount_minor,
            remaining=remaining_at_authorization,
            association_matches=True,
            inventory_available=True,
            quantity_within_limit=True,
            canonical_order_available=True,
            attendee_email=email,
            attendee_first_name=first_name,
            attendee_last_name=last_name,
            order_reference=reference,
        )
        try:
            payment_flow_id, payment_outcome = (
                ticket_payments.authorize_local_payment(
                    _SITE_BACKEND,
                    account_id=owner,
                    amount_minor=amount_minor,
                    fingerprint_value=payment_fingerprint,
                    scenario_id=scenario_id,
                )
            )
        except ticket_payments.TicketPaymentError:
            return invalid(
                [
                    "The test payment could not be processed. "
                    "Try the checkout again; no order was created."
                ],
                422,
            )
        if payment_outcome != "approved":
            message = {
                "declined": (
                    "The test payment was declined. Choose another outcome "
                    "and try again; no order was created."
                ),
                "retryable": (
                    "The test payment needs another attempt. Try again; "
                    "no order was created."
                ),
            }.get(
                payment_outcome,
                "The test payment was not approved; no order was created.",
            )
            return invalid([message], 422)

    def consume_final_payment(
        connection: sqlite3.Connection, final_facts: dict[str, object]
    ) -> dict[str, object]:
        if _SITE_BACKEND is None:
            raise ticket_payments.TicketPaymentError(
                "local payment service is unavailable"
            )
        return ticket_payments.consume_final_order_authorization(
            connection,
            _SITE_BACKEND,
            flow_id=payment_flow_id,
            account_id=owner,
            attendee_email=email,
            attendee_first_name=first_name,
            attendee_last_name=last_name,
            order_reference=reference,
            final_facts=final_facts,
        )

    try:
        database.create_order(
            reference=reference,
            account_id=int(account["id"]),
            owner=owner,
            idempotency_key=idempotency_key,
            payload_digest=payload_digest,
            expected_version=expected_version,
            event_id=event_id,
            occurrence_id=occurrence_id,
            ticket_class_id=int(occurrence["ticket_class_id"]),
            quantity=quantity,
            email=email,
            first_name=first_name,
            last_name=last_name,
            payment_flow_id=payment_flow_id,
            payment_consumer=(consume_final_payment if amount_minor > 0 else None),
        )
    except db.SoldOut:
        return sold_out_page()
    except db.StaleVersion:
        return invalid(
            [
                "This ticket class changed while you were checking out "
                "(stale version token). Reload the checkout to continue; "
                "no order was created."
            ],
            409,
        )
    except db.CommandConflict:
        return invalid(
            [
                "This request key was already used for different order details. "
                "Reload checkout before trying again."
            ],
            409,
        )
    except ticket_payments.TicketPaymentError:
        return invalid(
            [
                "The test payment approval no longer matches this order. "
                "Reload checkout and try again; no order was created."
            ],
            409,
        )
    return completed_order(reference)


@app.get(
    "/orders/{local_order_id}/receipt", response_class=HTMLResponse
)
async def order_receipt(
    request: Request, local_order_id: str
) -> HTMLResponse:
    order = _db().order_by_reference(local_order_id)
    if order is None:
        return render(
            request,
            "failure.html",
            page_title="Receipt not found",
            heading="Receipt not found",
            message=(
                "We couldn’t find an order with this ID."
            ),
            event=None,
            status_code=404,
        )
    account = current_account(request)
    if account is None:
        return RedirectResponse(
            f"/auth/login?next=/orders/{local_order_id}/receipt",
            status_code=303,
        )
    if int(account["id"]) != int(order["account_id"]):
        return render(
            request,
            "failure.html",
            page_title="Not your order",
            heading="Not your order",
            message=(
                "This order belongs to a different account."
            ),
            event=None,
            status_code=403,
        )
    event = _db().event_by_id(str(order["event_id"]))
    occurrence = event["occurrences"][str(order["occurrence_id"])]
    return render(
        request,
        "receipt.html",
        page_title="Registration confirmed",
        order=order,
        event=event,
        occurrence=occurrence,
    )


def render_r2_contract_state(
    request: Request,
    *,
    route_id: str,
    state: str,
    allowed_states: set[str],
) -> HTMLResponse:
    normalized = state if state in allowed_states else sorted(allowed_states)[0]
    title, purpose = R2_ROUTE_UI[route_id]
    state_title, state_body = R2_STATE_COPY[normalized]
    continue_href = {
        "auth-register": "/auth/register",
        "auth-register-verify": "/auth/register/verify",
        "auth-login": "/auth/login",
        "auth-logout": "/auth/login",
        "auth-password-forgot": "/auth/password/forgot",
        "auth-password-verify": "/auth/password/verify",
        "auth-password-reset": "/auth/password/reset",
        "auth-local-inbox": "/auth/local-inbox",
    }[route_id]
    return render(
        request,
        "r2_contract_state.html",
        page_title=title,
        route_id=route_id,
        route_title=title,
        route_purpose=purpose,
        state=normalized,
        allowed_states=sorted(allowed_states),
        state_title=state_title,
        state_body=state_body,
        continue_href=continue_href,
    )


def _set_session_cookie(response, token: str) -> None:
    cookie = dict(SITE_BACKEND_RUNTIME.cookie_options)
    response.set_cookie(
        SESSION_COOKIE,
        token,
        httponly=bool(cookie["httponly"]),
        samesite=str(cookie["samesite"]),
        secure=bool(cookie["secure"]),
        path=str(cookie["path"]),
        max_age=30 * 24 * 60 * 60,
    )
    if LEGACY_SESSION_COOKIE != SESSION_COOKIE:
        response.delete_cookie(LEGACY_SESSION_COOKIE, path="/")


def _ensure_auth_session(request: Request) -> tuple[str, bool]:
    supplied = request.cookies.get(SESSION_COOKIE) or request.cookies.get(
        LEGACY_SESSION_COOKIE
    )
    token, _session = _auth().ensure_session(supplied)
    return token, token != supplied


def _auth_flow_response(
    request: Request,
    *,
    token: str,
    flow: str,
    heading: str,
    introduction: str,
    status_code: int = 200,
    **values: object,
) -> HTMLResponse:
    response = render(
        request,
        "auth_flow.html",
        page_title=heading,
        flow=flow,
        heading=heading,
        introduction=introduction,
        status_code=status_code,
        **values,
    )
    _set_session_cookie(response, token)
    return response


def _auth_error_text(error: Exception) -> str:
    if isinstance(error, local_auth.AuthRateLimited):
        return "Too many requests. Please wait before trying again."
    if isinstance(error, local_auth.AuthConflict):
        return "That request conflicts with an existing account or flow."
    if isinstance(error, local_auth.AuthLocked):
        return "This verification flow is locked. Start again."
    if isinstance(error, local_auth.AuthExpired):
        return "This verification flow expired. Start again."
    if isinstance(error, local_auth.AuthValidationError):
        return str(error)
    return "We couldn’t complete that request. Check the details and try again."


def dispatch_auth_mail(
    backend: object,
    auth_store: local_auth.LocalAuthStore,
    session_token: str,
    purpose: str,
) -> None:
    """Best-effort delivery through the isolated WebsiteBench mail gateway."""

    try:
        AuthMailDelivery(
            backend,
            auth_store,
            worker_token=auth_mail_worker_token(),
        ).deliver_for_session(session_token, purpose=purpose)
    except AuthMailDeliveryError:
        # The durable outbox retains a sanitized retry state. Public recovery
        # stays enumeration-resistant and never exposes provider diagnostics.
        return


@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(),
        session_token=(
            request.cookies.get(SESSION_COOKIE)
            or request.cookies.get(LEGACY_SESSION_COOKIE, "")
        ),
    )


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


@app.get("/signup", response_class=HTMLResponse, include_in_schema=False)
@app.get("/signup/", response_class=HTMLResponse, include_in_schema=False)
@app.get("/signin/signup", response_class=HTMLResponse, include_in_schema=False)
@app.get("/signin/signup/", response_class=HTMLResponse, include_in_schema=False)
@app.get("/auth/register", response_class=HTMLResponse)
async def auth_register(request: Request, state: str = "") -> HTMLResponse:
    if state:
        return render_r2_contract_state(
            request,
            route_id="auth-register",
            state=state,
            allowed_states={
                "entry",
                "invalid",
                "duplicate",
                "pending",
                "rate-limited",
            },
        )
    token, _ = _ensure_auth_session(request)
    return _auth_flow_response(
        request,
        token=token,
        flow="register",
        heading="Create an Eventbrite account",
        introduction="Create an account to register for events and find your tickets.",
    )


@app.post("/auth/register", response_class=HTMLResponse)
async def auth_register_submit(request: Request):
    values = await urlencoded_form(request)
    token, _ = _ensure_auth_session(request)
    if values.get("csrf") != CSRF_VALUE:
        return _auth_flow_response(
            request,
            token=token,
            flow="register",
            heading="Create an Eventbrite account",
            introduction="Create an account to register for events and find your tickets.",
            auth_error="This form expired. Reload and try again.",
            status_code=403,
        )
    if PUBLIC_REGISTRATION_VERIFICATION is not None:
        store = _auth()
        try:
            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=store,
                session_token=token,
                email=values.get("email", ""),
            )
            if not ticket:
                return _auth_flow_response(
                    request,
                    token=token,
                    flow="register",
                    heading="Create an Eventbrite account",
                    introduction=(
                        "Create an account to register for events and find your tickets."
                    ),
                    auth_error=(
                        "Verify this email address before creating the account."
                    ),
                    status_code=422,
                )
            completed = store.complete_externally_verified_registration(
                token,
                email=values.get("email", ""),
                display_name=values.get("display_name", ""),
                password=values.get("password", ""),
                subject_factory=auth_subject_factory,
            )
        except local_auth.AuthError as exc:
            return _auth_flow_response(
                request,
                token=token,
                flow="register",
                heading="Create an Eventbrite account",
                introduction=(
                    "Create an account to register for events and find your tickets."
                ),
                auth_error=_auth_error_text(exc),
                status_code=422,
            )
        response = RedirectResponse("/", status_code=303)
        _set_session_cookie(response, str(completed["session_token"]))
        return response
    try:
        _auth().start_registration(
            token,
            email=values.get("email", ""),
            display_name=values.get("display_name", ""),
            password=values.get("password", ""),
        )
    except local_auth.AuthError as exc:
        return _auth_flow_response(
            request,
            token=token,
            flow="register",
            heading="Create an Eventbrite account",
            introduction="Create an account to register for events and find your tickets.",
            auth_error=_auth_error_text(exc),
            status_code=409 if isinstance(exc, local_auth.AuthConflict) else 422,
        )
    response = RedirectResponse("/auth/register/verify", status_code=303)
    _set_session_cookie(response, token)
    return response


@app.get("/auth/register/verify", response_class=HTMLResponse)
async def auth_register_verify(
    request: Request, state: str = ""
) -> HTMLResponse:
    if state:
        return render_r2_contract_state(
            request,
            route_id="auth-register-verify",
            state=state,
            allowed_states={"challenge", "invalid", "locked", "stale", "verified"},
        )
    token, _ = _ensure_auth_session(request)
    return _auth_flow_response(
        request,
        token=token,
        flow="register-verify",
        heading="Verify your email",
        introduction="Enter the six-digit code to finish creating your account.",
        local_mail=_auth().local_mail_for_session(
            token, purpose="registration"
        ),
    )


@app.post("/auth/register/verify", response_class=HTMLResponse)
async def auth_register_verify_submit(request: Request):
    values = await urlencoded_form(request)
    token, _ = _ensure_auth_session(request)
    if values.get("csrf") != CSRF_VALUE:
        return _auth_flow_response(
            request,
            token=token,
            flow="register-verify",
            heading="Verify your email",
            introduction="Enter the six-digit code to finish creating your account.",
            auth_error="This form expired. Reload and try again.",
            status_code=403,
        )
    try:
        _auth().verify_registration_code(token, values.get("code", ""))
        completed = _auth().complete_registration(
            token, subject_factory=auth_subject_factory
        )
    except local_auth.AuthError as exc:
        return _auth_flow_response(
            request,
            token=token,
            flow="register-verify",
            heading="Verify your email",
            introduction="Enter the six-digit code to finish creating your account.",
            local_mail=_auth().local_mail_for_session(
                token, purpose="registration"
            ),
            auth_error=_auth_error_text(exc),
            status_code=409,
        )
    response = RedirectResponse("/", status_code=303)
    _set_session_cookie(response, str(completed["session_token"]))
    return response


@app.get("/auth/logout", response_class=HTMLResponse)
@app.get("/logout", response_class=HTMLResponse, include_in_schema=False)
@app.get("/logout/", response_class=HTMLResponse, include_in_schema=False)
async def auth_logout(request: Request, state: str = "active") -> HTMLResponse:
    return render_r2_contract_state(
        request,
        route_id="auth-logout",
        state=state,
        allowed_states={"active", "revoked"},
    )


@app.post("/auth/logout")
async def auth_logout_submit(request: Request) -> RedirectResponse:
    _auth().sign_out(
        request.cookies.get(SESSION_COOKIE)
        or request.cookies.get(LEGACY_SESSION_COOKIE)
    )
    response = RedirectResponse("/", status_code=303)
    response.delete_cookie(SESSION_COOKIE, path="/")
    response.delete_cookie(LEGACY_SESSION_COOKIE, path="/")
    return response


@app.get("/auth/password/forgot", response_class=HTMLResponse)
async def auth_password_forgot(
    request: Request, state: str = ""
) -> HTMLResponse:
    if state:
        return render_r2_contract_state(
            request,
            route_id="auth-password-forgot",
            state=state,
            allowed_states={"entry", "generic-response", "rate-limited"},
        )
    token, _ = _ensure_auth_session(request)
    return _auth_flow_response(
        request,
        token=token,
        flow="forgot",
        heading="Reset your password",
        introduction="Enter your account email to continue.",
    )


@app.post("/auth/password/forgot", response_class=HTMLResponse)
async def auth_password_forgot_submit(
    request: Request, background_tasks: BackgroundTasks
):
    values = await urlencoded_form(request)
    token, _ = _ensure_auth_session(request)
    if values.get("csrf") != CSRF_VALUE:
        return _auth_flow_response(
            request,
            token=token,
            flow="forgot",
            heading="Reset your password",
            introduction="Enter your account email to continue.",
            auth_error="This form expired. Reload and try again.",
            status_code=403,
        )
    try:
        result = _auth().start_password_reset(
            token, email=values.get("email", "")
        )
    except local_auth.AuthError as exc:
        return _auth_flow_response(
            request,
            token=token,
            flow="forgot",
            heading="Reset your password",
            introduction="Enter your account email to continue.",
            auth_error=_auth_error_text(exc),
            status_code=429
            if isinstance(exc, local_auth.AuthRateLimited)
            else 422,
        )
    response = RedirectResponse("/auth/password/verify", status_code=303)
    response.headers["X-Auth-Reset-Message"] = str(result["message"])
    if auth_mail_delivery_enabled(request.app.state.site_backend):
        background_tasks.add_task(
            dispatch_auth_mail,
            request.app.state.site_backend,
            _auth(),
            token,
            "password-reset",
        )
    _set_session_cookie(response, token)
    return response


@app.get("/auth/password/verify", response_class=HTMLResponse)
async def auth_password_verify(
    request: Request, state: str = ""
) -> HTMLResponse:
    if state:
        return render_r2_contract_state(
            request,
            route_id="auth-password-verify",
            state=state,
            allowed_states={"challenge", "invalid", "locked", "stale", "verified"},
        )
    token, _ = _ensure_auth_session(request)
    return _auth_flow_response(
        request,
        token=token,
        flow="password-verify",
        heading="Enter your verification code",
        introduction=local_auth.RESET_PUBLIC_MESSAGE,
        local_mail=_auth().local_mail_for_session(
            token, purpose="password-reset"
        ),
    )


@app.post("/auth/password/verify", response_class=HTMLResponse)
async def auth_password_verify_submit(request: Request):
    values = await urlencoded_form(request)
    token, _ = _ensure_auth_session(request)
    if values.get("csrf") != CSRF_VALUE:
        return _auth_flow_response(
            request,
            token=token,
            flow="password-verify",
            heading="Enter your verification code",
            introduction=local_auth.RESET_PUBLIC_MESSAGE,
            auth_error="This form expired. Reload and try again.",
            status_code=403,
        )
    try:
        _auth().verify_password_reset_code(token, values.get("code", ""))
    except local_auth.AuthError as exc:
        return _auth_flow_response(
            request,
            token=token,
            flow="password-verify",
            heading="Enter your verification code",
            introduction=local_auth.RESET_PUBLIC_MESSAGE,
            local_mail=_auth().local_mail_for_session(
                token, purpose="password-reset"
            ),
            auth_error=_auth_error_text(exc),
            status_code=409,
        )
    response = RedirectResponse("/auth/password/reset", status_code=303)
    _set_session_cookie(response, token)
    return response


@app.get("/auth/password/reset", response_class=HTMLResponse)
async def auth_password_reset(
    request: Request, state: str = ""
) -> HTMLResponse:
    if state:
        return render_r2_contract_state(
            request,
            route_id="auth-password-reset",
            state=state,
            allowed_states={"verified", "invalid", "stale", "complete"},
        )
    token, _ = _ensure_auth_session(request)
    return _auth_flow_response(
        request,
        token=token,
        flow="password-reset",
        heading="Choose a new password",
        introduction="Use at least eight characters.",
    )


@app.post("/auth/password/reset", response_class=HTMLResponse)
async def auth_password_reset_submit(request: Request):
    values = await urlencoded_form(request)
    token, _ = _ensure_auth_session(request)
    if values.get("csrf") != CSRF_VALUE:
        return _auth_flow_response(
            request,
            token=token,
            flow="password-reset",
            heading="Choose a new password",
            introduction="Use at least eight characters.",
            auth_error="This form expired. Reload and try again.",
            status_code=403,
        )
    try:
        new_token = _auth().complete_password_reset(
            token, new_password=values.get("new_password", "")
        )
    except local_auth.AuthError as exc:
        return _auth_flow_response(
            request,
            token=token,
            flow="password-reset",
            heading="Choose a new password",
            introduction="Use at least eight characters.",
            auth_error=_auth_error_text(exc),
            status_code=409,
        )
    response = RedirectResponse("/", status_code=303)
    _set_session_cookie(response, new_token)
    return response


@app.get("/auth/local-inbox", response_class=HTMLResponse)
async def auth_local_inbox(
    request: Request, state: str = ""
) -> HTMLResponse:
    if state:
        return render_r2_contract_state(
            request,
            route_id="auth-local-inbox",
            state=state,
            allowed_states={
                "messages",
                "empty",
                "local-only",
                "smtp-pending",
                "smtp-sent",
                "smtp-failed",
            },
        )
    token, _ = _ensure_auth_session(request)
    messages = [
        message
        for message in (
            _auth().local_mail_for_session(token, purpose="registration"),
            _auth().local_mail_for_session(token, purpose="password-reset"),
        )
        if message is not None
    ]
    return _auth_flow_response(
        request,
        token=token,
        flow="inbox",
        heading="Your Eventbrite messages",
        introduction="Account verification and recovery messages for this session.",
        messages=messages,
    )


@app.get("/signin", response_class=HTMLResponse, include_in_schema=False)
@app.get("/signin/", response_class=HTMLResponse, include_in_schema=False)
@app.get("/login", response_class=HTMLResponse, include_in_schema=False)
@app.get("/login/", response_class=HTMLResponse, include_in_schema=False)
@app.get("/auth/login", response_class=HTMLResponse)
async def auth_login(
    request: Request, next: str | None = None, state: str = ""
) -> HTMLResponse:
    if state:
        return render_r2_contract_state(
            request,
            route_id="auth-login",
            state=state,
            allowed_states={"entry", "invalid", "authenticated"},
        )
    token, _ = _ensure_auth_session(request)
    response = render(
        request,
        "auth.html",
        page_title="Sign in",
        next_path=safe_next(next),
        unauthorized=False,
    )
    _set_session_cookie(response, token)
    return response


@app.post("/auth/login")
async def auth_login_submit(request: Request):
    values = await urlencoded_form(request)
    token, _ = _ensure_auth_session(request)
    if values.get("csrf") != CSRF_VALUE:
        response = render(
            request,
            "auth.html",
            page_title="Sign in",
            next_path=safe_next(values.get("next")),
            unauthorized=False,
            auth_error="Your sign-in request expired. Please try again.",
            status_code=403,
        )
        _set_session_cookie(response, token)
        return response
    try:
        result = _auth().sign_in(
            token,
            email=values.get("email", ""),
            password=values.get("password", ""),
        )
    except local_auth.AuthError:
        response = render(
            request,
            "auth.html",
            page_title="Sign in",
            next_path=safe_next(values.get("next")),
            unauthorized=False,
            auth_error="We couldn’t sign in to that account.",
            status_code=403,
        )
        _set_session_cookie(response, token)
        return response
    response = RedirectResponse(safe_next(values.get("next")), status_code=303)
    _set_session_cookie(response, str(result["session_token"]))
    return response


@app.post("/__admin/fixture-session")
async def admin_fixture_session(request: Request):
    """Test-only credential shortcut behind the isolated admin boundary."""
    supplied = request.headers.get(ADMIN_TOKEN_HEADER, "") or request.headers.get(
        LEGACY_ADMIN_TOKEN_HEADER, ""
    )
    if not admin_boundary_authorized(request):
        return JSONResponse({"ok": False, "error": "forbidden"}, status_code=403)
    values = await urlencoded_form(request)
    account_slug = values.get("account", DEFAULT_ACCOUNT)
    account = _db().account_by_slug(account_slug)
    if account is None or account_slug not in SEED_PASSWORDS:
        return JSONResponse({"ok": False, "error": "unknown account"}, status_code=404)
    token, _ = _auth().ensure_session(None)
    result = _auth().sign_in(
        token,
        email=str(account["email"]),
        password=SEED_PASSWORDS[account_slug],
    )
    response = RedirectResponse(safe_next(values.get("next")), status_code=303)
    _set_session_cookie(response, str(result["session_token"]))
    return response


@app.get("/organizer/overview/", response_class=HTMLResponse)
async def organizer_overview(request: Request) -> HTMLResponse:
    return render(
        request,
        "organizer_overview.html",
        page_title="Event Organizer: Become an Event Hosting Legend",
    )


CREATE_PREFILL = {
    "title": "ML Paper Reading Group",
    "date": "2026-04-15 18:00",
    "location": "Online (Zoom)",
    "description": db.TASK_372_DESCRIPTION,
}


@app.get("/organizer/create", response_class=HTMLResponse)
async def organizer_create(
    request: Request, prefill: str = "", state: str = "ready"
) -> HTMLResponse:
    account = current_account(request)
    if account is None:
        return render(
            request,
            "auth.html",
            page_title="Sign in",
            next_path="/organizer/create",
            unauthorized=True,
            status_code=401,
        )
    if account["role"] != "organizer":
        return render(
            request,
            "failure.html",
            page_title="Organizer access required",
            heading="Organizer access required",
            message="This account does not have permission to create events.",
            event=None,
            status_code=403,
        )
    values = (
        dict(CREATE_PREFILL)
        if prefill == "ml-paper-reading-group"
        else {"title": "", "date": "", "location": "", "description": ""}
    )
    normalized = (
        state if state in {"ready", "validation", "submitting"} else "ready"
    )
    return render(
        request,
        "organizer_create.html",
        page_title="Create an event",
        form=values,
        state=normalized,
        errors=[],
    )


@app.post("/api/v3/organizations/1/events/auto-create")
async def auto_create_event(request: Request):
    """Local auto-create terminal, persisted server-side."""
    account = current_account(request)
    if account is None:
        return RedirectResponse(
            "/auth/login?next=/organizer/create", status_code=303
        )
    if account["role"] != "organizer":
        return render(
            request,
            "failure.html",
            page_title="Organizer access required",
            heading="Organizer access required",
            message="This account does not have permission to create events.",
            event=None,
            status_code=403,
        )
    values = await urlencoded_form(request)

    def invalid(errors: list[str], status_code: int = 422) -> HTMLResponse:
        return render(
            request,
            "organizer_create.html",
            page_title="Create an event",
            form={
                "title": values.get("title", ""),
                "date": values.get("date", ""),
                "location": values.get("location", ""),
                "description": values.get("description", ""),
            },
            state="validation",
            errors=errors,
            status_code=status_code,
        )

    if values.get("csrf") != CSRF_VALUE:
        return invalid(["This form expired. Reload and try again."], 403)
    errors: list[str] = []
    title = values.get("title", "").strip()
    event_date = values.get("date", "").strip()
    location = values.get("location", "").strip()
    description = values.get("description", "").strip()
    if not title:
        errors.append("An event title is required.")
    if not event_date:
        errors.append("An event date is required.")
    if not location:
        errors.append("An event location is required.")
    if not description:
        errors.append("An event description is required.")
    if errors:
        return invalid(errors)
    local_event_id = local_event_id_for(title)
    try:
        expected_version = int(values.get("expected_version", "1"))
    except ValueError:
        return invalid(["The event draft version is invalid."], 422)
    draft_id = (
        values.get("draft_id", "").strip()
        or "draft:task-372:ml-paper-reading-group"
    )
    idempotency_key = (
        values.get("idempotency_key", "").strip()
        or f"create:{local_event_id}:v{expected_version}"
    )
    payload_digest = hashlib.sha256(
        json.dumps(
            {
                "draft_id": draft_id,
                "title": title,
                "event_date": event_date,
                "location": location,
                "description": description,
                "expected_version": expected_version,
            },
            sort_keys=True,
            separators=(",", ":"),
        ).encode("utf-8")
    ).hexdigest()
    try:
        _db().create_organizer_event(
            local_id=local_event_id,
            title=title,
            event_date=event_date,
            location=location,
            description=description,
            owner=str(account["slug"]),
            expected_version=expected_version,
            idempotency_key=idempotency_key,
            payload_digest=payload_digest,
            draft_id=draft_id,
        )
    except db.StaleVersion:
        return invalid(
            ["This event draft changed. Reload it before creating the event."],
            409,
        )
    except db.CommandConflict:
        return invalid(
            ["This request key was already used for different event details."],
            409,
        )
    except PermissionError:
        return invalid(
            ["This event draft belongs to a different organizer."],
            403,
        )
    return RedirectResponse(
        f"/organizer/events?created={local_event_id}", status_code=303
    )


@app.get("/organizer/events", response_class=HTMLResponse)
async def organizer_events(
    request: Request,
    created: str = "",
    view: str = "list",
    q: str = "",
    status: str = "all",
) -> HTMLResponse:
    account = current_account(request)
    if account is None:
        return render(
            request,
            "auth.html",
            page_title="Sign in",
            next_path="/organizer/events",
            unauthorized=True,
            status_code=401,
        )
    if account["role"] != "organizer":
        return render(
            request,
            "failure.html",
            page_title="Organizer access required",
            heading="Organizer access required",
            message="This account does not have permission to manage events.",
            event=None,
            status_code=403,
        )
    owner = str(account["slug"])
    database = _db()
    own_events = [
        {
            "id": row["id"],
            "title": row["title"],
            "date": row["event_date"],
            "location": row["location"],
            "description": row["description"],
            "owner": row["owner"],
            "version": int(row["version"]),
        }
        for row in database.organizer_events_for(owner)
    ]
    created_row = database.organizer_event(created) if created else None
    created_event = None
    if created_row is not None and created_row["owner"] == owner:
        created_event = {"id": created_row["id"], "title": created_row["title"]}
    # Builder drafts and their published listings share the dashboard with
    # the legacy auto-created events, like the live "Events" view.
    drafts = []
    for row in database.builder_drafts_for(owner):
        published = (
            database.event_by_id(str(row["published_event_id"]))
            if row["status"] == "published"
            else None
        )
        sold = capacity = 0
        if published:
            occurrence = published["occurrences"][
                published["default_occurrence"]]
            capacity = int(occurrence["capacity"])
            sold = capacity - remaining_capacity(
                published["id"], str(occurrence["id"]))
        drafts.append({
            **row,
            "hero": database._builder_hero(str(row["image_ref"])),
            "public_slug": published["slug"] if published else "",
            "sold": sold,
            "capacity": capacity,
        })
    normalized_view = view if view in {"list", "calendar", "collections"} else "list"
    normalized_status = status if status in {"all", "draft", "published"} else "all"
    needle = q.strip().casefold()
    if needle:
        drafts = [row for row in drafts if needle in str(row["title"]).casefold()]
        own_events = [row for row in own_events if needle in str(row["title"]).casefold()]
    if normalized_status != "all":
        drafts = [row for row in drafts if row["status"] == normalized_status]
        if normalized_status == "draft":
            own_events = []
    calendar_items = []
    for row in drafts:
        if row.get("start_at"):
            calendar_items.append({
                "date": str(row["start_at"])[:10],
                "title": row["title"] or "New event",
                "status": row["status"],
                "url": f"/manage/events/{row['id']}/edit",
            })
    for row in own_events:
        calendar_items.append({
            "date": str(row["date"])[:10],
            "title": row["title"],
            "status": "published",
            "url": "/organizer/events",
        })
    calendar_items.sort(key=lambda row: (row["date"], row["title"]))
    return render(
        request,
        "organizer_events.html",
        page_title="Events",
        events=own_events,
        drafts=drafts,
        created_event=created_event,
        view=normalized_view,
        q=q.strip(),
        event_status=normalized_status,
        calendar_items=calendar_items,
    )


@app.post("/organizer/events/{local_event_id}/delete")
async def delete_organizer_event(request: Request, local_event_id: str):
    account = current_account(request)
    if account is None:
        return RedirectResponse(
            "/auth/login?next=/organizer/events", status_code=303
        )
    values = await urlencoded_form(request)
    event = _db().organizer_event(local_event_id)
    if values.get("csrf") != CSRF_VALUE:
        return render(
            request,
            "failure.html",
            page_title="Rejected",
            heading="Rejected",
            message="This form expired. Reload and try again.",
            event=None,
            status_code=403,
        )
    if event is None:
        return render(
            request,
            "failure.html",
            page_title="Not found",
            heading="Not found",
            message="We couldn’t find an event with this ID.",
            event=None,
            status_code=404,
        )
    if event["owner"] != account["slug"]:
        return render(
            request,
            "failure.html",
            page_title="Ownership error",
            heading="Ownership error",
            message=(
                "This event belongs to a different organizer."
            ),
            event=None,
            status_code=403,
        )
    if account["role"] != "organizer":
        return render(
            request,
            "failure.html",
            page_title="Organizer access required",
            heading="Organizer access required",
            message="This account does not have permission to manage events.",
            event=None,
            status_code=403,
        )
    try:
        expected_version = int(values.get("expected_version", ""))
    except ValueError:
        return render(
            request,
            "failure.html",
            page_title="Rejected",
            heading="Rejected",
            message="The event version is invalid.",
            event=None,
            status_code=422,
        )
    try:
        _db().delete_organizer_event(
            local_event_id,
            owner=str(account["slug"]),
            expected_version=expected_version,
            idempotency_key=(
                values.get("idempotency_key", "").strip()
                or f"delete:{local_event_id}:v{expected_version}"
            ),
        )
    except db.StaleVersion:
        return render(
            request,
            "failure.html",
            page_title="Event changed",
            heading="Event changed",
            message="Reload your events before deleting this event.",
            event=None,
            status_code=409,
        )
    except db.CommandConflict:
        return render(
            request,
            "failure.html",
            page_title="Rejected",
            heading="Rejected",
            message="This request key was already used for another change.",
            event=None,
            status_code=409,
        )
    return RedirectResponse("/organizer/events", status_code=303)


# -- Event builder (multi-step create flow) ---------------------------------
#
# The post-login builder mirrors the live surface: /manage/events/create
# creates a draft and lands on /manage/events/{id}/edit, whose sections
# (Build page / Tickets / Publish) autosave through /api/v3/events/* JSON
# endpoints (builder.js). Publishing promotes the draft into the public
# catalog inside one transaction (backend.db.builder_publish), so the new
# event is immediately browsable, searchable and purchasable.

# Curated cover options offered by the builder's image drawer: existing
# vendored capture imagery only (capture-date-relative paths).
BUILDER_GALLERY = [
    {"rel": "2026-08-08/builder/builder-default-hero-1.jpeg", "label": "Drummer in a rehearsal studio"},
    {"rel": "2026-08-08/builder/builder-default-hero-2.jpeg", "label": "People gathering outdoors"},
    {"rel": "2026-08-08/builder/builder-default-hero-3.jpeg", "label": "Creative workshop"},
    {"rel": "2026-07-25/home/home-event-card-1189042687.jpg", "label": "Crowd at a rooftop mixer"},
    {"rel": "2026-07-25/home/home-event-card-1189109798.jpg", "label": "Concert stage lights"},
    {"rel": "2026-07-25/home/home-event-card-1189589099.jpg", "label": "Community meetup"},
    {"rel": "2026-07-25/sf-free-directory/sf-directory-card-1174269883.jpg", "label": "City street fair"},
    {"rel": "2026-07-25/sf-free-directory/sf-directory-card-1187598354.jpg", "label": "Networking night"},
    {"rel": "2026-07-25/ny-free-directory/ny-directory-card-1182690852.jpg", "label": "Downtown gathering"},
    {"rel": "2026-07-25/ny-free-directory/ny-directory-card-1188662102.jpg", "label": "Evening social"},
    {"rel": "2026-07-25/create-event-entry/organizer-category-music.webp", "label": "Live music"},
    {"rel": "2026-07-25/create-event-entry/organizer-category-food.webp", "label": "Food & drink"},
    {"rel": "2026-07-25/create-event-entry/organizer-category-performance.webp", "label": "Performance"},
    {"rel": "2026-07-25/create-event-entry/organizer-category-corporate.webp", "label": "Corporate"},
]

BUILDER_TIMEZONES = [
    ("America/Los_Angeles", "Pacific Time (PT)"),
    ("America/Denver", "Mountain Time (MT)"),
    ("America/Chicago", "Central Time (CT)"),
    ("America/New_York", "Eastern Time (ET)"),
]

IMAGE_MAGICS = (
    (b"\xff\xd8\xff", "image/jpeg"),
    (b"\x89PNG", "image/png"),
    (b"GIF87a", "image/gif"),
    (b"GIF89a", "image/gif"),
)
UPLOAD_MAX_BYTES = 2 * 1024 * 1024
UPLOAD_MAX_DIMENSION = 8192
UPLOAD_MAX_PIXELS = 25_000_000
IMAGE_FORMAT_MIMES = {
    "JPEG": "image/jpeg",
    "PNG": "image/png",
    "GIF": "image/gif",
    "WEBP": "image/webp",
}


def _inspect_image(content: bytes) -> tuple[str, int, int]:
    """Decode an upload before persisting it and return real metadata."""
    try:
        with warnings.catch_warnings():
            warnings.simplefilter("error", Image.DecompressionBombWarning)
            with Image.open(io.BytesIO(content)) as opened:
                width, height = opened.size
                image_format = str(opened.format or "").upper()
                if image_format not in IMAGE_FORMAT_MIMES:
                    raise ValueError(
                        "unsupported image format (JPEG, PNG, GIF or WebP)"
                    )
                if width < 1 or height < 1:
                    raise ValueError("image dimensions are invalid")
                if (
                    width > UPLOAD_MAX_DIMENSION
                    or height > UPLOAD_MAX_DIMENSION
                    or width * height > UPLOAD_MAX_PIXELS
                ):
                    raise ValueError("image dimensions are too large")
                opened.verify()
            # Verify a real decoded frame too: a magic header plus truncated
            # payload is not an image and must never enter the blob store.
            with Image.open(io.BytesIO(content)) as decoded:
                decoded.seek(0)
                decoded.load()
    except (Image.DecompressionBombError, Image.DecompressionBombWarning):
        raise ValueError("image dimensions are too large") from None
    except (UnidentifiedImageError, OSError, SyntaxError):
        raise ValueError(
            "unsupported or corrupt image (JPEG, PNG, GIF or WebP)"
        ) from None
    return IMAGE_FORMAT_MIMES[image_format], width, height


def _organizer_guard(request: Request, next_path: str):
    """-> (account, None) or (None, error response) for HTML surfaces."""
    account = current_account(request)
    if account is None:
        return None, render(
            request,
            "auth.html",
            page_title="Sign in",
            next_path=next_path,
            unauthorized=True,
            status_code=401,
        )
    if account["role"] != "organizer":
        return None, render(
            request,
            "failure.html",
            page_title="Organizer access required",
            heading="Organizer access required",
            message="This account does not have permission to create events.",
            event=None,
            status_code=403,
        )
    return account, None


def _organizer_json_guard(request: Request):
    """-> (account, None) or (None, error response) for JSON endpoints."""
    account = current_account(request)
    if account is None:
        return None, JSONResponse(
            {"error": "sign-in required", "redirect": "/auth/login"},
            status_code=401,
        )
    if account["role"] != "organizer":
        return None, JSONResponse(
            {"error": "organizer role required"}, status_code=403
        )
    if request.headers.get("x-csrf") != CSRF_VALUE:
        return None, JSONResponse(
            {"error": "csrf token missing or stale"}, status_code=403
        )
    return account, None


async def _builder_json_object(
    request: Request,
) -> tuple[dict[str, object] | None, JSONResponse | None]:
    """Parse a builder command without letting malformed JSON reach a 500."""
    try:
        body = await request.json()
    except (ValueError, UnicodeDecodeError):
        return None, JSONResponse(
            {"error": "request body must be a JSON object"}, status_code=422
        )
    if not isinstance(body, dict):
        return None, JSONResponse(
            {"error": "request body must be a JSON object"}, status_code=422
        )
    return body, None


def _builder_expected_version(body: dict[str, object]) -> int:
    """Return an exact JSON integer version; booleans are rejected."""
    value = body.get("expected_version")
    if isinstance(value, bool) or not isinstance(value, int) or value < 0:
        raise ValueError("expected_version must be a non-negative integer")
    return value


def _builder_idempotency_key(body: dict[str, object]) -> str:
    value = body.get("idempotency_key")
    if not isinstance(value, str) or not value.strip():
        raise ValueError("idempotency_key must be a non-empty string")
    value = value.strip()
    if len(value) > 200:
        raise ValueError("idempotency_key is too long")
    return value


@app.get("/manage/events/create", response_class=HTMLResponse)
async def builder_entry(request: Request, onboarding: int = 0):
    account, error = _organizer_guard(request, "/manage/events/create")
    if error is not None:
        return error
    owner = str(account["slug"])
    # A new draft per visit, as on the live builder. The immutable command
    # sequence and draft insert are allocated in one transaction, so parallel
    # requests cannot share an idempotency key or draft id.
    draft_id, _ = _db().builder_create_next_draft(owner)
    suffix = "?onboarding=event-type" if onboarding else ""
    return RedirectResponse(
        f"/manage/events/{draft_id}/edit{suffix}", status_code=303
    )


@app.get("/manage/events/{draft_id}/edit", response_class=HTMLResponse)
async def builder_edit(
    request: Request,
    draft_id: str,
    section: str = "build",
    onboarding: str = "",
) -> HTMLResponse:
    account, error = _organizer_guard(
        request, f"/manage/events/{draft_id}/edit"
    )
    if error is not None:
        return error
    draft = _db().builder_draft(draft_id, str(account["slug"]))
    if draft is None:
        return render(
            request,
            "failure.html",
            page_title="Draft not found",
            heading="Draft not found",
            message="We couldn’t find this event draft in your account.",
            event=None,
            status_code=404,
        )
    normalized = section if section in {"build", "tickets", "publish"} else "build"
    return render(
        request,
        "builder.html",
        page_title=(draft["title"] or "Create an event"),
        draft=draft,
        section=normalized,
        gallery=BUILDER_GALLERY,
        timezones=BUILDER_TIMEZONES,
        assets_root="/static/assets/source-current",
        onboarding=("event-type" if onboarding == "event-type" else ""),
    )


@app.get("/manage/events/{draft_id}/preview", response_class=HTMLResponse)
async def builder_preview(request: Request, draft_id: str) -> HTMLResponse:
    account, error = _organizer_guard(
        request, f"/manage/events/{draft_id}/preview"
    )
    if error is not None:
        return error
    database = _db()
    draft = database.builder_draft(draft_id, str(account["slug"]))
    if draft is None:
        return render(
            request,
            "failure.html",
            page_title="Draft not found",
            heading="Draft not found",
            message="We couldn’t find this event draft in your account.",
            event=None,
            status_code=404,
        )
    return render(
        request,
        "builder_preview.html",
        page_title=(draft["title"] or "Event preview"),
        draft=draft,
        hero=database._builder_hero(str(draft["image_ref"])),
    )


@app.get(
    "/manage/events/{source_event_id}/{source_section}",
    response_class=HTMLResponse,
    include_in_schema=False,
)
async def source_builder_section_alias(
    source_event_id: str, source_section: str
) -> RedirectResponse:
    """Keep captured legacy builder links inside the local owner fixture.

    The numeric upstream event id is immutable source evidence, not a local
    business identity.  Every observed section therefore resolves to the
    seeded task-372 draft and lets that destination enforce authentication.
    """

    section = {
        "details": "build",
        "online-event": "build",
        "tickets": "tickets",
        "preview_publish": "publish",
        "promocodes": "publish",
    }.get(source_section, "build")
    target = "/manage/events/draft:task-372:ml-paper-reading-group/edit"
    return RedirectResponse(f"{target}?section={section}", status_code=303)


@app.get(
    "/e/{source_event_id}/preview",
    response_class=HTMLResponse,
    include_in_schema=False,
)
@app.get(
    "/e/{source_event_id}/preview/",
    response_class=HTMLResponse,
    include_in_schema=False,
)
async def source_event_preview_alias(source_event_id: str) -> RedirectResponse:
    return RedirectResponse(
        "/manage/events/draft:task-372:ml-paper-reading-group/preview",
        status_code=303,
    )


@app.post("/api/v3/events/{draft_id}/")
async def builder_autosave(request: Request, draft_id: str) -> JSONResponse:
    account, error = _organizer_json_guard(request)
    if error is not None:
        return error
    body, body_error = await _builder_json_object(request)
    if body_error is not None:
        return body_error
    assert body is not None
    fields = body.get("fields", {})
    if not isinstance(fields, dict):
        return JSONResponse({"error": "fields must be an object"}, status_code=422)
    if any(
        not isinstance(key, str) or not isinstance(value, str)
        for key, value in fields.items()
    ):
        return JSONResponse(
            {"error": "builder field names and values must be strings"},
            status_code=422,
        )
    try:
        version, outcome = _db().builder_update_draft(
            draft_id,
            str(account["slug"]),
            expected_version=_builder_expected_version(body),
            fields=fields,
            idempotency_key=_builder_idempotency_key(body),
        )
    except db.StaleVersion as exc:
        return JSONResponse({"error": str(exc), "kind": "stale"}, status_code=409)
    except db.CommandConflict as exc:
        return JSONResponse({"error": str(exc), "kind": "conflict"}, status_code=409)
    except PermissionError as exc:
        return JSONResponse({"error": str(exc)}, status_code=403)
    except ValueError as exc:
        return JSONResponse({"error": str(exc)}, status_code=422)
    return JSONResponse({"version": version, "outcome": outcome})


@app.post("/api/v3/events/{draft_id}/ticket_classes/")
@app.post("/api/v3/events/{draft_id}/ticket_classes/{ticket_id}/")
async def builder_ticket_upsert(
    request: Request, draft_id: str, ticket_id: int | None = None
) -> JSONResponse:
    account, error = _organizer_json_guard(request)
    if error is not None:
        return error
    body, body_error = await _builder_json_object(request)
    if body_error is not None:
        return body_error
    assert body is not None
    fields = body.get("fields", {})
    if not isinstance(fields, dict):
        return JSONResponse({"error": "fields must be an object"}, status_code=422)
    operation = "ticket-create" if ticket_id is None else "ticket-update"
    try:
        version, tid, outcome = _db().builder_ticket_command(
            draft_id,
            str(account["slug"]),
            operation=operation,
            expected_version=_builder_expected_version(body),
            idempotency_key=_builder_idempotency_key(body),
            ticket_id=ticket_id,
            fields=fields,
        )
    except db.StaleVersion as exc:
        return JSONResponse({"error": str(exc), "kind": "stale"}, status_code=409)
    except db.CommandConflict as exc:
        return JSONResponse({"error": str(exc), "kind": "conflict"}, status_code=409)
    except PermissionError as exc:
        return JSONResponse({"error": str(exc)}, status_code=403)
    except ValueError as exc:
        return JSONResponse({"error": str(exc)}, status_code=422)
    return JSONResponse(
        {"version": version, "ticket_id": tid, "outcome": outcome}
    )


@app.delete("/api/v3/events/{draft_id}/ticket_classes/{ticket_id}/")
async def builder_ticket_delete(
    request: Request, draft_id: str, ticket_id: int
) -> JSONResponse:
    account, error = _organizer_json_guard(request)
    if error is not None:
        return error
    body, body_error = await _builder_json_object(request)
    if body_error is not None:
        return body_error
    assert body is not None
    try:
        version, tid, outcome = _db().builder_ticket_command(
            draft_id,
            str(account["slug"]),
            operation="ticket-delete",
            expected_version=_builder_expected_version(body),
            idempotency_key=_builder_idempotency_key(body),
            ticket_id=ticket_id,
        )
    except db.StaleVersion as exc:
        return JSONResponse({"error": str(exc), "kind": "stale"}, status_code=409)
    except db.CommandConflict as exc:
        return JSONResponse({"error": str(exc), "kind": "conflict"}, status_code=409)
    except PermissionError as exc:
        return JSONResponse({"error": str(exc)}, status_code=403)
    except ValueError as exc:
        return JSONResponse({"error": str(exc)}, status_code=422)
    return JSONResponse(
        {"version": version, "ticket_id": tid, "outcome": outcome}
    )


@app.post("/api/v3/events/{draft_id}/publish/")
async def builder_publish(request: Request, draft_id: str) -> JSONResponse:
    account, error = _organizer_json_guard(request)
    if error is not None:
        return error
    body, body_error = await _builder_json_object(request)
    if body_error is not None:
        return body_error
    assert body is not None
    try:
        result = _db().builder_publish(
            draft_id,
            str(account["slug"]),
            expected_version=_builder_expected_version(body),
            idempotency_key=_builder_idempotency_key(body),
        )
    except db.StaleVersion as exc:
        return JSONResponse({"error": str(exc), "kind": "stale"}, status_code=409)
    except db.CommandConflict as exc:
        return JSONResponse({"error": str(exc), "kind": "conflict"}, status_code=409)
    except PermissionError as exc:
        return JSONResponse({"error": str(exc)}, status_code=403)
    except ValueError as exc:
        return JSONResponse({"error": str(exc)}, status_code=422)
    return JSONResponse(result)


@app.post("/api/v3/events/{draft_id}/unpublish/")
async def builder_unpublish(request: Request, draft_id: str) -> JSONResponse:
    account, error = _organizer_json_guard(request)
    if error is not None:
        return error
    body, body_error = await _builder_json_object(request)
    if body_error is not None:
        return body_error
    assert body is not None
    try:
        version, outcome = _db().builder_unpublish(
            draft_id,
            str(account["slug"]),
            expected_version=_builder_expected_version(body),
            idempotency_key=_builder_idempotency_key(body),
        )
    except db.StaleVersion as exc:
        return JSONResponse({"error": str(exc), "kind": "stale"}, status_code=409)
    except db.CommandConflict as exc:
        return JSONResponse({"error": str(exc), "kind": "conflict"}, status_code=409)
    except PermissionError as exc:
        return JSONResponse({"error": str(exc)}, status_code=403)
    except ValueError as exc:
        return JSONResponse({"error": str(exc)}, status_code=422)
    return JSONResponse({"version": version, "outcome": outcome})


@app.delete("/api/v3/events/{draft_id}/")
async def builder_discard(request: Request, draft_id: str) -> JSONResponse:
    account, error = _organizer_json_guard(request)
    if error is not None:
        return error
    body, body_error = await _builder_json_object(request)
    if body_error is not None:
        return body_error
    assert body is not None
    try:
        event_id = _db().builder_discard(
            draft_id,
            str(account["slug"]),
            expected_version=_builder_expected_version(body),
        )
    except db.StaleVersion as exc:
        return JSONResponse({"error": str(exc), "kind": "stale"}, status_code=409)
    except db.CommandConflict as exc:
        return JSONResponse(
            {"error": str(exc), "kind": "conflict"}, status_code=409
        )
    except PermissionError as exc:
        return JSONResponse({"error": str(exc)}, status_code=403)
    except ValueError as exc:
        return JSONResponse({"error": str(exc)}, status_code=422)
    return JSONResponse({"outcome": "discarded", "event_id": event_id})


@app.post("/api/v3/media/upload/")
async def builder_media_upload(request: Request) -> JSONResponse:
    """Raw-body image upload (fetch body = File): no multipart dependency,
    content-addressed storage, magic-byte + size validation."""
    account, error = _organizer_json_guard(request)
    if error is not None:
        return error
    content = await request.body()
    if not content:
        return JSONResponse({"error": "empty upload"}, status_code=422)
    if len(content) > UPLOAD_MAX_BYTES:
        return JSONResponse(
            {"error": "image is larger than 2MB"}, status_code=413
        )
    try:
        mime, width, height = _inspect_image(content)
    except ValueError as exc:
        return JSONResponse(
            {"error": str(exc)},
            status_code=422,
        )
    try:
        sha = _db().builder_store_image(
            str(account["slug"]), content, mime, width=width, height=height
        )
    except PermissionError as exc:
        return JSONResponse({"error": str(exc)}, status_code=403)
    return JSONResponse(
        {
            "ref": f"upload:{sha}",
            "url": f"/media/{sha}",
            "mime": mime,
            "width": width,
            "height": height,
        }
    )


@app.get("/media/{sha}")
async def builder_media(sha: str):
    row = _db().builder_image(sha)
    if row is None:
        return JSONResponse({"error": "not found"}, status_code=404)
    from fastapi.responses import Response

    return Response(
        content=row["content"],
        media_type=str(row["mime"]),
        headers={"Cache-Control": "public, max-age=31536000, immutable"},
    )


@app.get("/myevents", response_class=HTMLResponse, include_in_schema=False)
@app.get("/myevents/", response_class=HTMLResponse, include_in_schema=False)
@app.get("/myevent", response_class=HTMLResponse, include_in_schema=False)
async def myevents_alias(request: Request, created: str = "") -> HTMLResponse:
    return await organizer_events(request, created)


# ---------------------------------------------------------------------------
# Parameterized public page families

# These models close the first-party navigation graph without creating a
# bespoke template for every category, article or marketing URL.  Copy and
# representative entities are deterministic fixtures; the shared catalog is
# still the authority for links to event pages.
PUBLIC_PAGE_FAMILIES = {
    "pricing": {
        "eyebrow": "Eventbrite pricing",
        "title": "Flexible tools for events of every size",
        "lead": "Create free events at no cost and see paid-event fees before you publish.",
        "sections": [
            ("Free events", "Publish, register attendees, and check people in with no ticket fee."),
            ("Paid events", "Ticket totals use the price you set. This clone completes payment only through local-sandbox."),
            ("Organizer tools", "Manage tickets, attendees, reports, marketing drafts, and payouts from one workspace."),
        ],
        "actions": [("Start creating", "/manage/events/create"), ("Explore organizer tools", "/organizer/overview/")],
    },
    "marketing": {
        "eyebrow": "Event marketing platform",
        "title": "Reach the right audience for your event",
        "lead": "Build a campaign, schedule a local draft, and review results alongside ticket activity.",
        "sections": [
            ("Campaigns", "Draft attendee updates and lifecycle reminders with explicit schedule and pause states."),
            ("Event ads", "Model a budget and campaign state without publishing an ad or contacting an ad network."),
            ("Analytics", "See order and check-in totals derived from the local organization ledger."),
        ],
        "actions": [("Open marketing", "/organizations/1/marketing"), ("View reporting", "/reporting")],
    },
    "organizer-product": {
        "eyebrow": "Organizer solutions",
        "title": "Plan, publish, and run your event",
        "lead": "From a first draft through check-in, every tool stays connected to the same event and organization.",
        "sections": [
            ("Create and publish", "Build free or paid ticket classes, preview the page, and publish when it is ready."),
            ("Attendees and orders", "Track registrations, process a local refund, and keep check-in status current."),
            ("Finance and apps", "Review local payout entries and connect simulated integrations from the app catalog."),
        ],
        "actions": [("Create an event", "/manage/events/create"), ("Manage events", "/organizer/events")],
    },
    "blog": {
        "eyebrow": "Eventbrite Blog",
        "title": "Ideas and practical guides for gathering people",
        "lead": "Browse representative planning, promotion, and attendee-experience articles.",
        "sections": [
            ("How to build an event plan", "Turn the goal, audience, venue, schedule, and ticket setup into a workable launch checklist."),
            ("Make check-in feel effortless", "Prepare staff roles, test the attendee list, and keep an exception path for name lookup."),
            ("Read your event report", "Compare registrations, attendance, refunds, and net proceeds before planning the next event."),
        ],
        "actions": [("Browse events", "/"), ("Start organizing", "/organizer/overview/")],
    },
    "help-article": {
        "eyebrow": "Help Center",
        "title": "Help with your Eventbrite account and events",
        "lead": "Follow a focused guide or return to the Help Center for another topic.",
        "sections": [
            ("Before you start", "Sign in to the account that owns the tickets or organization you want to manage."),
            ("Complete the task", "Use the matching tickets, event, organization, or account-settings page and save your changes."),
            ("If something changed", "Reload the page before retrying so the latest version of the record is used."),
        ],
        "actions": [("Help Center", "/help"), ("Find my tickets", "/orders")],
    },
    "legal": {
        "eyebrow": "Legal and trust",
        "title": "Policies for using Eventbrite",
        "lead": "Find the terms, privacy, accessibility, and community standards that apply to this experience.",
        "sections": [
            ("Terms", "Understand the agreement for accounts, events, registrations, and acceptable use."),
            ("Privacy", "Review what account and order information is stored and where it appears."),
            ("Accessibility", "Learn about keyboard access, responsive layout, and assistive-technology support."),
        ],
        "actions": [("Terms of Service", "/terms"), ("Privacy", "/privacy"), ("Accessibility", "/accessibility")],
    },
    "updates": {
        "eyebrow": "Product updates",
        "title": "What’s new for attendees and organizers",
        "lead": "A frozen release feed for the features represented in this offline experience.",
        "sections": [
            ("Organization workspace", "Manage members, attendees, check-ins, marketing, reporting, finance, and apps in one navigation."),
            ("Discovery controls", "Filters, URL state, sorting, pagination, and empty states now share one catalog query model."),
            ("Local business lifecycles", "Refund, campaign, ad, payout, and integration transitions are deterministic and versioned."),
        ],
        "actions": [("Browse events", "/"), ("Organizer workspace", "/organizations/1/home")],
    },
}


def _representative_public_events(category: str = "") -> list[dict]:
    selected = (category,) if category else ()
    result = _db().search_events(
        db.EventQuery(
            place=db.DEFAULT_PLACE,
            categories=selected,
            page=1,
            per_page=8,
        )
    )
    return result.events


def _family_model(family: str, slug: str = "") -> dict[str, object]:
    model = dict(PUBLIC_PAGE_FAMILIES[family])
    if slug:
        readable = slug.strip("/").split("/")[-1].replace("-", " ").strip()
        if readable:
            model["context_label"] = readable.title()
    model["family"] = family
    model["canonical_path"] = slug
    return model


@app.get("/pricing", response_class=HTMLResponse)
@app.get("/organizer/pricing", response_class=HTMLResponse)
@app.get("/organizer/pricing/", response_class=HTMLResponse)
async def pricing_page(request: Request) -> HTMLResponse:
    model = _family_model("pricing")
    return render(
        request,
        "page_family.html",
        page_title=str(model["title"]),
        model=model,
        events=_representative_public_events(),
    )


@app.get("/b/", response_class=HTMLResponse)
@app.get("/b/{category_path:path}", response_class=HTMLResponse)
async def category_family(request: Request, category_path: str = "") -> HTMLResponse:
    raw = category_path.strip("/").split("/")[-1] if category_path else "all"
    category_slug = raw.removesuffix("--events").removesuffix("-events")
    known = {str(item["slug"]): item for item in _db().categories()}
    category = known.get(category_slug)
    label = str(category["label"]) if category else category_slug.replace("-", " ").title()
    model = {
        "family": "category",
        "eyebrow": "Browse by category",
        "title": f"{label} events",
        "lead": f"Discover representative {label.casefold()} events in Los Angeles and continue to a local event page.",
        "sections": [
            ("Find your next event", "Use date, price, format, language, and neighborhood filters to narrow the catalog."),
            ("Save it for later", "Sign in and use the heart on any event to keep it in your liked events."),
            ("Register locally", "Free and paid fixtures share the same checkout, receipt, and tickets journey."),
        ],
        "actions": [
            ("Open full results", f"/d/{db.DEFAULT_PLACE}/{category_slug}--events/"),
            ("Search events", f"/search?q={quote_plus(label)}"),
        ],
        "context_label": label,
        "canonical_path": category_path,
    }
    return render(
        request,
        "page_family.html",
        page_title=f"{label} events",
        model=model,
        events=_representative_public_events(category_slug if category else ""),
    )


@app.get("/directory", include_in_schema=False)
async def source_directory_alias() -> RedirectResponse:
    return RedirectResponse(
        f"/d/{db.DEFAULT_PLACE}/all--events/", status_code=303
    )


@app.get("/c/{collection_slug:path}", response_class=HTMLResponse)
async def collection_family(
    request: Request, collection_slug: str
) -> HTMLResponse:
    model = {
        "family": "collection",
        "eyebrow": "Curated events",
        "title": "Event collection",
        "lead": (
            "Browse a representative local collection and continue to the "
            "same deterministic event-detail and checkout journeys."
        ),
        "sections": [
            (
                "Curated for this collection",
                "The collection identity is kept in the URL while inventory comes from the frozen local catalog.",
            ),
            (
                "Save and share your plan",
                "Signed-in visitors can keep events in their local saved list.",
            ),
            (
                "Register with confidence",
                "Availability and price are always resolved by the local server.",
            ),
        ],
        "actions": [
            ("Browse all events", f"/d/{db.DEFAULT_PLACE}/all--events/"),
            ("View saved events", "/saved"),
        ],
        "context_label": collection_slug.strip("/") or "collection",
        "canonical_path": collection_slug,
    }
    return render(
        request,
        "page_family.html",
        page_title="Event collection",
        model=model,
        events=_representative_public_events(),
    )


@app.get("/ttd/", response_class=HTMLResponse)
@app.get("/ttd/{place_path:path}", response_class=HTMLResponse)
async def things_to_do_family(request: Request, place_path: str = "") -> HTMLResponse:
    label = (
        place_path.strip("/").split("/")[-1].replace("-", " ").title()
        if place_path.strip("/")
        else "Los Angeles"
    )
    model = {
        "family": "things-to-do",
        "eyebrow": "Things to do",
        "title": f"Things to do in {label}",
        "lead": "Plan a day out with events, neighborhood ideas, and popular categories from the frozen local catalog.",
        "sections": [
            ("This weekend", "See events whose dates fit the selected weekend."),
            ("Free things to do", "Open the free filter without losing the selected place."),
            ("Popular categories", "Explore music, food and drink, business, hobbies, and community events."),
        ],
        "actions": [
            ("Events this weekend", f"/d/{db.DEFAULT_PLACE}/all--events/?dates=this-weekend"),
            ("Free events", f"/d/{db.DEFAULT_PLACE}/free--events/"),
        ],
        "context_label": label,
        "canonical_path": place_path,
    }
    return render(
        request,
        "page_family.html",
        page_title=f"Things to do in {label}",
        model=model,
        events=_representative_public_events(),
    )


@app.get("/blog/", response_class=HTMLResponse)
@app.get("/blog/{article_path:path}", response_class=HTMLResponse)
async def blog_family(request: Request, article_path: str = "") -> HTMLResponse:
    model = _family_model("blog", article_path)
    return render(request, "page_family.html", page_title=str(model["title"]), model=model, events=[])


@app.get("/help/{article_path:path}", response_class=HTMLResponse)
async def help_article_family(request: Request, article_path: str) -> HTMLResponse:
    model = _family_model("help-article", article_path)
    return render(request, "page_family.html", page_title=str(model["title"]), model=model, events=[])


@app.get("/legal/", response_class=HTMLResponse)
@app.get("/legal/{legal_path:path}", response_class=HTMLResponse)
async def legal_family(request: Request, legal_path: str = "") -> HTMLResponse:
    model = _family_model("legal", legal_path)
    return render(request, "page_family.html", page_title=str(model["title"]), model=model, events=[])


@app.get("/product-updates", response_class=HTMLResponse)
@app.get("/product-updates/{update_path:path}", response_class=HTMLResponse)
async def product_updates_family(request: Request, update_path: str = "") -> HTMLResponse:
    model = _family_model("updates", update_path)
    return render(request, "page_family.html", page_title=str(model["title"]), model=model, events=[])


@app.get("/l/{landing_path:path}", response_class=HTMLResponse)
@app.get("/p/{landing_path:path}", response_class=HTMLResponse)
async def marketing_landing_family(request: Request, landing_path: str) -> HTMLResponse:
    model = _family_model("marketing", landing_path)
    return render(
        request,
        "page_family.html",
        page_title=str(model["title"]),
        model=model,
        events=_representative_public_events(),
    )


@app.get("/platform", response_class=HTMLResponse)
@app.get("/platform/", response_class=HTMLResponse)
@app.get("/resources", response_class=HTMLResponse)
@app.get("/resources/", response_class=HTMLResponse)
@app.get("/about", response_class=HTMLResponse)
@app.get("/about/", response_class=HTMLResponse)
@app.get("/security", response_class=HTMLResponse)
@app.get("/security/", response_class=HTMLResponse)
@app.get("/how-it-works", response_class=HTMLResponse)
@app.get("/find-tickets", response_class=HTMLResponse)
@app.get("/find-tickets/", response_class=HTMLResponse)
@app.get("/reconvene", response_class=HTMLResponse)
@app.get("/reconvene/", response_class=HTMLResponse)
async def general_product_family(request: Request) -> HTMLResponse:
    slug = request.url.path.strip("/") or "platform"
    model = _family_model("marketing", slug)
    model["title"] = slug.replace("-", " ").title()
    model["context_label"] = "Eventbrite product"
    return render(
        request,
        "page_family.html",
        page_title=str(model["title"]),
        model=model,
        events=_representative_public_events(),
    )


@app.get("/poi/{poi_path:path}", response_class=HTMLResponse)
async def point_of_interest_family(request: Request, poi_path: str) -> HTMLResponse:
    model = _family_model("marketing", poi_path)
    label = poi_path.strip("/").split("/")[-1].split("--", 1)[0]
    model["eyebrow"] = "Things to do nearby"
    model["title"] = label.replace("-", " ").title() or "Local point of interest"
    model["lead"] = "Browse representative events and activities near this frozen point of interest."
    model["actions"] = [("Browse Los Angeles events", "/d/ca--los-angeles/all--events/")]
    return render(
        request,
        "page_family.html",
        page_title=str(model["title"]),
        model=model,
        events=_representative_public_events(),
    )


@app.get("/support", response_class=HTMLResponse)
@app.get("/support/{support_path:path}", response_class=HTMLResponse)
async def support_family(request: Request, support_path: str = "") -> HTMLResponse:
    model = _family_model("help-article", support_path or "support")
    return render(request, "page_family.html", page_title=str(model["title"]), model=model, events=[])


@app.get("/corporate/{corporate_path:path}", response_class=HTMLResponse)
async def corporate_family(request: Request, corporate_path: str) -> HTMLResponse:
    model = _family_model("legal", corporate_path)
    return render(request, "page_family.html", page_title=str(model["title"]), model=model, events=[])


@app.get("/privacypolicy", response_class=HTMLResponse)
@app.get("/tos", response_class=HTMLResponse)
async def legal_alias_family(request: Request) -> HTMLResponse:
    return await legal_family(request, request.url.path.strip("/"))


@app.get("/create", response_class=HTMLResponse)
@app.get("/create/", response_class=HTMLResponse)
async def source_create_alias() -> RedirectResponse:
    return RedirectResponse("/manage/events/create", status_code=303)


@app.get("/international/change_locale/", response_class=HTMLResponse)
async def locale_alias() -> RedirectResponse:
    return RedirectResponse("/", status_code=303)


@app.get("/organizer/{product_path:path}", response_class=HTMLResponse)
async def organizer_product_family(request: Request, product_path: str) -> HTMLResponse:
    model = _family_model("organizer-product", product_path)
    return render(request, "page_family.html", page_title=str(model["title"]), model=model, events=[])


APP_CATALOG = [
    {"slug": "mailchimp", "name": "Mailchimp", "category": "Marketing", "summary": "Model an audience connection for campaign drafts."},
    {"slug": "zoom", "name": "Zoom", "category": "Online events", "summary": "Represent an online-event provider connection."},
    {"slug": "salesforce", "name": "Salesforce", "category": "CRM", "summary": "Model attendee data mapping without remote transfer."},
    {"slug": "google-analytics", "name": "Google Analytics", "category": "Analytics", "summary": "Represent a measurement connection with zero outbound requests."},
]


@app.get("/apps", response_class=HTMLResponse)
@app.get("/apps/", response_class=HTMLResponse)
@app.get("/apps/{app_slug:path}", response_class=HTMLResponse)
async def apps_family(request: Request, app_slug: str = "") -> HTMLResponse:
    selected = next((item for item in APP_CATALOG if item["slug"] == app_slug.strip("/")), None)
    model = {
        "family": "apps",
        "eyebrow": "Eventbrite App Marketplace",
        "title": selected["name"] if selected else "Apps for your event workflow",
        "lead": selected["summary"] if selected else "Browse representative marketing, online-event, CRM, and analytics integrations.",
        "sections": [
            (item["name"], item["summary"]) for item in APP_CATALOG
        ],
        "actions": [("Manage organization apps", "/organizations/1/apps"), ("Create an event", "/manage/events/create")],
        "context_label": selected["category"] if selected else "App Marketplace",
        "canonical_path": app_slug,
    }
    return render(request, "page_family.html", page_title=str(model["title"]), model=model, events=[])


# ---------------------------------------------------------------------------
# Account settings

ACCOUNT_SETTING_SECTIONS = {
    "profile": ("Personal information", "Update the preferences attached to this account."),
    "preferences": ("Email preferences", "Choose which local event and organizer updates appear in your account."),
    "security": ("Security", "Manage the password and active session for this site-isolated account."),
}


def _account_preference(account_id: int) -> dict[str, object]:
    row = _db().connect().execute(
        "SELECT * FROM account_preferences WHERE account_id = ?", (account_id,)
    ).fetchone()
    return dict(row) if row is not None else {}


@app.get("/account-settings", response_class=HTMLResponse)
@app.get("/account-settings/", response_class=HTMLResponse)
@app.get("/account-settings/{section:path}", response_class=HTMLResponse)
async def account_settings_page(request: Request, section: str = "profile") -> HTMLResponse:
    account, denied = _require_account(request)
    if denied is not None:
        return denied
    normalized = section.strip("/") or "profile"
    if normalized not in ACCOUNT_SETTING_SECTIONS:
        normalized = "profile"
    title, lead = ACCOUNT_SETTING_SECTIONS[normalized]
    return render(
        request,
        "account_settings.html",
        page_title=title,
        section=normalized,
        section_title=title,
        section_lead=lead,
        preferences=_account_preference(int(account["id"])),
    )


@app.get("/api/v3/account-settings")
async def account_settings_api_get(request: Request) -> JSONResponse:
    account = current_account(request)
    if account is None:
        return JSONResponse({"ok": False, "error": "authentication_required"}, status_code=401)
    return JSONResponse({"ok": True, "preferences": _account_preference(int(account["id"])), "remote_effect_count": 0})


@app.post("/api/v3/account-settings")
async def account_settings_api_update(request: Request) -> JSONResponse:
    account = current_account(request)
    if account is None:
        return JSONResponse({"ok": False, "error": "authentication_required"}, status_code=401)
    try:
        payload = await request.json()
    except Exception:
        return JSONResponse({"ok": False, "error": "json_object_required"}, status_code=422)
    if not isinstance(payload, dict):
        return JSONResponse({"ok": False, "error": "json_object_required"}, status_code=422)
    if payload.get("csrf") != CSRF_VALUE and request.headers.get("X-CSRF-Token") != CSRF_VALUE:
        return JSONResponse({"ok": False, "error": "invalid_csrf"}, status_code=403)
    idempotency_key = (request.headers.get("Idempotency-Key") or request.headers.get("X-Idempotency-Key") or str(payload.get("idempotency_key", ""))).strip()
    if not idempotency_key or len(idempotency_key) > 200:
        return JSONResponse({"ok": False, "error": "idempotency_key_required"}, status_code=422)
    try:
        expected_version = int(payload.get("expected_version"))
    except (TypeError, ValueError):
        return JSONResponse({"ok": False, "error": "expected_version_required"}, status_code=422)
    updates = {
        "locale": str(payload.get("locale", "en-US"))[:16],
        "timezone": str(payload.get("timezone", "America/Los_Angeles"))[:64],
        "event_updates": 1 if bool(payload.get("event_updates", True)) else 0,
        "organizer_updates": 1 if bool(payload.get("organizer_updates", True)) else 0,
    }
    if updates["locale"] not in {"en-US", "en-GB", "es-US"} or updates["timezone"] not in db.BUILDER_ALLOWED_TIMEZONES:
        return JSONResponse({"ok": False, "error": "invalid_preference"}, status_code=422)
    digest = hashlib.sha256(json.dumps({"expected_version": expected_version, **updates}, sort_keys=True, separators=(",", ":")).encode()).hexdigest()
    database = _db()
    with database._lock:
        conn = database.connect()
        conn.execute("BEGIN IMMEDIATE")
        try:
            replay = conn.execute(
                "SELECT payload_digest,canonical_result FROM account_preference_commands "
                "WHERE account_id=? AND idempotency_key=?",
                (int(account["id"]), idempotency_key),
            ).fetchone()
            if replay is not None:
                if replay["payload_digest"] != digest:
                    conn.execute("ROLLBACK")
                    return JSONResponse({"ok": False, "error": "idempotency_conflict"}, status_code=409)
                result = json.loads(str(replay["canonical_result"]))
                result["idempotent_replay"] = True
                conn.execute("COMMIT")
                return JSONResponse(result)
            current = conn.execute(
                "SELECT version FROM account_preferences WHERE account_id=?",
                (int(account["id"]),),
            ).fetchone()
            if current is None or int(current["version"]) != expected_version:
                conn.execute("ROLLBACK")
                return JSONResponse({"ok": False, "error": "stale_version"}, status_code=409)
            version = expected_version + 1
            conn.execute(
                "UPDATE account_preferences SET locale=?,timezone=?,event_updates=?,"
                "organizer_updates=?,version=?,updated_at=? WHERE account_id=?",
                (*updates.values(), version, FROZEN_CLOCK, int(account["id"])),
            )
            result = {"ok": True, "outcome": "saved", "version": version, "preferences": {**updates, "version": version}, "idempotent_replay": False, "remote_effect_count": 0, "remote_request_count": 0}
            command_id = "apc-" + hashlib.sha256(f"{account['id']}|{idempotency_key}".encode()).hexdigest()[:20]
            conn.execute(
                "INSERT INTO account_preference_commands (command_id,account_id,idempotency_key,payload_digest,expected_version,canonical_result,created_at) VALUES (?,?,?,?,?,?,?)",
                (command_id, int(account["id"]), idempotency_key, digest, expected_version, json.dumps(result, sort_keys=True, separators=(",", ":")), FROZEN_CLOCK),
            )
            conn.execute("COMMIT")
            return JSONResponse(result)
        except BaseException:
            if conn.in_transaction:
                conn.execute("ROLLBACK")
            raise


# ---------------------------------------------------------------------------
# Full local organizer workspace and API

WORKSPACE_SECTIONS = {
    "home": ("Organization home", "A current view of events, attendees, revenue, and operational work."),
    "events": ("Events", "Published events, drafts, ticket setup, and calendar views."),
    "orders": ("Orders & attendees", "Registration, refund, and check-in state for this organization."),
    "check-in": ("Check-in", "Use the local attendee list to check in or void an entry."),
    "marketing": ("Marketing", "Campaign and ad drafts with local lifecycle controls."),
    "payouts": ("Payouts", "A local-sandbox payout ledger derived from organization orders."),
    "organization": ("Organization info", "Profile, members, owner/admin roles, and organization settings."),
    "reporting": ("Reporting", "Analytics derived from local orders, refunds, and check-ins."),
    "apps": ("Apps", "Connect and disconnect simulations from the local app catalog."),
    "finance": ("Finance settings", "Currency, payout schedule, and sandbox-only payment identity."),
}


def _workspace_actor(account) -> organization_workspace.Actor:
    return organization_workspace.Actor(
        account_id=int(account["id"]),
        slug=str(account["slug"]),
        role=str(account["role"]),
    )


def _workspace_denied(request: Request, next_path: str) -> HTMLResponse | None:
    account = current_account(request)
    if account is None:
        return render(request, "auth.html", page_title="Sign in", next_path=next_path, unauthorized=True, status_code=401)
    return None


@app.get("/organizations", response_class=HTMLResponse)
@app.get("/organizations/", response_class=HTMLResponse)
async def organizations_entry(request: Request) -> HTMLResponse:
    denied = _workspace_denied(request, "/organizations/1/home")
    if denied is not None:
        return denied
    return RedirectResponse("/organizations/1/home", status_code=303)


@app.get(
    "/organizations/{source_section}",
    response_class=HTMLResponse,
    include_in_schema=False,
)
async def source_organization_section_alias(
    source_section: str,
) -> RedirectResponse:
    """Canonicalize the captured no-id organizer navigation to tenant 1."""

    section = {
        "home": "home",
        "events": "events",
        "collections": "events",
        "orders": "orders",
        "marketing": "marketing",
        "payouts": "payouts",
        "info": "organization",
        "reporting": "reporting",
        "apps": "apps",
        "finance": "finance",
    }.get(source_section.strip("/"), "home")
    return RedirectResponse(f"/organizations/1/{section}", status_code=303)


@app.get("/organizations/{organization_id}/{section:path}", response_class=HTMLResponse)
async def organization_workspace_page(request: Request, organization_id: str, section: str = "home") -> HTMLResponse:
    normalized = section.strip("/") or "home"
    qr_match = re.fullmatch(r"attendees/([^/]+)/qr\.svg", normalized)
    if qr_match:
        return await organization_attendee_qr(
            request, organization_id, qr_match.group(1)
        )
    if normalized not in WORKSPACE_SECTIONS:
        normalized = "home"
    denied = _workspace_denied(request, f"/organizations/{organization_id}/{normalized}")
    if denied is not None:
        return denied
    account = current_account(request)
    assert account is not None
    service = organization_workspace.OrganizationWorkspace(_db())
    try:
        overview = service.overview(organization_id, _workspace_actor(account))
        resources = {
            resource: service.list_resource(organization_id, _workspace_actor(account), resource)
            for resource in organization_workspace.RESOURCE_TABLES
        }
    except organization_workspace.WorkspaceError as exc:
        return render(request, "failure.html", page_title="Organization unavailable", heading="Organization unavailable", message=exc.message, event=None, status_code=exc.status_code)
    title, lead = WORKSPACE_SECTIONS[normalized]
    for attendee in resources["attendees"]:
        attendee["check_in_code"] = organization_workspace.check_in_code(
            organization_id, str(attendee["id"])
        )
    order_references = list(dict.fromkeys(
        str(item["order_reference"]) for item in resources["attendees"]
    ))
    return render(
        request,
        "organizer_workspace.html",
        page_title=title,
        organization_id=organization_id,
        section=normalized,
        section_title=title,
        section_lead=lead,
        sections=WORKSPACE_SECTIONS,
        overview=overview,
        resources=resources,
        app_catalog=APP_CATALOG,
        drafts=_db().builder_drafts_for(str(account["slug"])),
        order_references=order_references,
    )


def _local_qr_svg(value: str) -> str:
    """Render a deterministic local QR-style matrix without remote assets."""

    size = 29
    quiet = 4
    digest = hashlib.sha512(value.encode()).digest()
    bits = [((byte >> shift) & 1) for byte in digest for shift in range(7, -1, -1)]
    matrix = [[False for _ in range(size)] for _ in range(size)]
    reserved = [[False for _ in range(size)] for _ in range(size)]

    def finder(x: int, y: int) -> None:
        for row in range(-1, 8):
            for col in range(-1, 8):
                xx, yy = x + col, y + row
                if 0 <= xx < size and 0 <= yy < size:
                    reserved[yy][xx] = True
                    matrix[yy][xx] = (
                        0 <= row <= 6 and 0 <= col <= 6
                        and (row in {0, 6} or col in {0, 6} or (2 <= row <= 4 and 2 <= col <= 4))
                    )
    finder(0, 0)
    finder(size - 7, 0)
    finder(0, size - 7)
    bit_index = 0
    for y in range(size):
        for x in range(size):
            if reserved[y][x]:
                continue
            matrix[y][x] = bool(bits[bit_index % len(bits)] ^ ((x + y) % 2))
            bit_index += 1
    rects = "".join(
        f'<rect x="{x + quiet}" y="{y + quiet}" width="1" height="1"/>'
        for y, row in enumerate(matrix) for x, on in enumerate(row) if on
    )
    total = size + quiet * 2
    return (
        f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {total} {total}" '
        'shape-rendering="crispEdges" role="img" aria-label="Local attendee QR code">'
        f'<rect width="{total}" height="{total}" fill="white"/><g fill="#1e0a3c">{rects}</g></svg>'
    )


@app.get("/organizations/{organization_id}/attendees/{attendee_id}/qr.svg")
async def organization_attendee_qr(
    request: Request, organization_id: str, attendee_id: str
) -> Response:
    actor, error = _workspace_api_actor(request)
    if error is not None:
        return error
    try:
        attendees = organization_workspace.OrganizationWorkspace(_db()).list_resource(
            organization_id, actor, "attendees"
        )
    except organization_workspace.WorkspaceError as exc:
        return _workspace_json_error(exc)
    if not any(str(item["id"]) == attendee_id for item in attendees):
        return Response(status_code=404)
    code = organization_workspace.check_in_code(organization_id, attendee_id)
    return Response(
        _local_qr_svg(code),
        media_type="image/svg+xml",
        headers={"Cache-Control": "private, no-store"},
    )


@app.get("/reporting", response_class=HTMLResponse)
@app.get("/reporting/{report_path:path}", response_class=HTMLResponse)
async def reporting_alias(request: Request, report_path: str = "") -> HTMLResponse:
    return await organization_workspace_page(request, "1", "reporting")


def _workspace_json_error(exc: organization_workspace.WorkspaceError) -> JSONResponse:
    return JSONResponse(
        {"ok": False, "error": exc.code, "message": exc.message, "remote_effect_count": 0, "remote_request_count": 0},
        status_code=exc.status_code,
    )


def _workspace_api_actor(request: Request):
    account = current_account(request)
    if account is None:
        return None, JSONResponse({"ok": False, "error": "authentication_required"}, status_code=401)
    return _workspace_actor(account), None


async def _workspace_mutation_payload(request: Request):
    try:
        payload = await request.json()
    except Exception:
        return None, None, None, JSONResponse({"ok": False, "error": "json_object_required"}, status_code=422)
    if not isinstance(payload, dict):
        return None, None, None, JSONResponse({"ok": False, "error": "json_object_required"}, status_code=422)
    if payload.get("csrf") != CSRF_VALUE and request.headers.get("X-CSRF-Token") != CSRF_VALUE:
        return None, None, None, JSONResponse({"ok": False, "error": "invalid_csrf"}, status_code=403)
    idempotency_key = (request.headers.get("Idempotency-Key") or request.headers.get("X-Idempotency-Key") or str(payload.get("idempotency_key", ""))).strip()
    if not idempotency_key or len(idempotency_key) > 200:
        return None, None, None, JSONResponse({"ok": False, "error": "idempotency_key_required"}, status_code=422)
    try:
        expected_version = int(payload.get("expected_version"))
    except (TypeError, ValueError):
        return None, None, None, JSONResponse({"ok": False, "error": "expected_version_required"}, status_code=422)
    business_payload = {key: value for key, value in payload.items() if key not in {"csrf", "idempotency_key", "expected_version"}}
    return business_payload, expected_version, idempotency_key, None


@app.get("/api/v3/organizations/{organization_id}")
async def organization_api_overview(request: Request, organization_id: str) -> JSONResponse:
    actor, error = _workspace_api_actor(request)
    if error is not None:
        return error
    try:
        result = organization_workspace.OrganizationWorkspace(_db()).overview(organization_id, actor)
    except organization_workspace.WorkspaceError as exc:
        return _workspace_json_error(exc)
    return JSONResponse({"ok": True, **result})


@app.get("/api/v3/organizations/{organization_id}/{resource}")
async def organization_api_list(request: Request, organization_id: str, resource: str) -> JSONResponse:
    actor, error = _workspace_api_actor(request)
    if error is not None:
        return error
    try:
        items = organization_workspace.OrganizationWorkspace(_db()).list_resource(organization_id, actor, resource)
    except organization_workspace.WorkspaceError as exc:
        return _workspace_json_error(exc)
    return JSONResponse({"ok": True, "organization_id": organization_id, "resource": resource, "items": items, "remote_effect_count": 0, "remote_request_count": 0})


@app.post("/api/v3/organizations/{organization_id}/{resource}")
async def organization_api_create(request: Request, organization_id: str, resource: str) -> JSONResponse:
    actor, error = _workspace_api_actor(request)
    if error is not None:
        return error
    payload, expected_version, idempotency_key, payload_error = await _workspace_mutation_payload(request)
    if payload_error is not None:
        return payload_error
    try:
        result = organization_workspace.OrganizationWorkspace(_db()).create(
            organization_id=organization_id,
            actor=actor,
            resource=resource,
            payload=payload,
            expected_version=expected_version,
            idempotency_key=idempotency_key,
        )
    except organization_workspace.WorkspaceError as exc:
        return _workspace_json_error(exc)
    return JSONResponse(result)


@app.post("/api/v3/organizations/{organization_id}/{resource}/{resource_id}")
async def organization_api_transition(request: Request, organization_id: str, resource: str, resource_id: str) -> JSONResponse:
    actor, error = _workspace_api_actor(request)
    if error is not None:
        return error
    payload, expected_version, idempotency_key, payload_error = await _workspace_mutation_payload(request)
    if payload_error is not None:
        return payload_error
    outcome = str(payload.get("outcome", "")).strip()
    if not outcome:
        return JSONResponse({"ok": False, "error": "outcome_required"}, status_code=422)
    try:
        result = organization_workspace.OrganizationWorkspace(_db()).transition(
            organization_id=organization_id,
            actor=actor,
            resource=resource,
            resource_id=resource_id,
            outcome=outcome,
            expected_version=expected_version,
            idempotency_key=idempotency_key,
        )
    except organization_workspace.WorkspaceError as exc:
        return _workspace_json_error(exc)
    return JSONResponse(result)


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


if __name__ == "__main__":
    main()