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

Owns the WAL-mode connection, the ordered migration history recorded in
``schema_migrations``, the deterministic fixture seed, and the domain
primitives: 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.

All state lives in the data directory (env ``CLAWBENCH_DATA_DIR``, default
the ``data`` directory that is a SIBLING of ``clone/`` so the uvicorn
reload watcher never sees database churn).

Benchmark constants (event IDs, slugs, titles) exist here ONLY as ordinary
seed rows; no query or state transition branches on them.
"""

from __future__ import annotations

import calendar
import hashlib
import os
import re
import sqlite3
import threading
from datetime import date, datetime, timedelta, timezone
from collections.abc import Callable, Iterable
from pathlib import Path
from typing import NamedTuple

SITE_ID = "eventbrite"
DB_FILENAME = "eventbrite.sqlite3"

FROZEN_CLOCK = "2026-06-01T12:00:00-05:00"
FROZEN_NOW = datetime(2026, 6, 1, 12, 0, tzinfo=timezone(timedelta(hours=-5)))
FROZEN_TODAY = FROZEN_NOW.date()

DATABASE_PATH_ENV = "WEBSITEBENCH_SITE_BACKEND_DATABASE"
# Read-only compatibility for already-created local runners and historical
# test commands. New deployments use the runtime-bound database path above.
DATA_DIR_ENV = "WEBSITEBENCH_DATA_DIR"
ADMIN_TOKEN_ENV = "WEBSITEBENCH_ADMIN_TOKEN"
LEGACY_ADMIN_TOKEN_ENV = "CLAWBENCH_ADMIN_TOKEN"
ADMIN_HOST_ENV = "WEBSITEBENCH_ADMIN_HOST"

CLONE_ROOT = Path(__file__).resolve().parents[1]

ASSET_BASE = "/static/assets/source-current/2026-07-25"

SYNTHETIC_LABEL = "Community event preview \u2014 not a published Eventbrite listing"

TICKET_CLASS_NAME = "General Admission"


def resolve_next_fourth_tuesday(after: date) -> date:
    """Server-owned occurrence resolution: strictly the next 4th Tuesday."""
    year, month = after.year, after.month
    while True:
        cal = calendar.Calendar()
        tuesdays = [
            day
            for day in cal.itermonthdates(year, month)
            if day.month == month and day.weekday() == calendar.TUESDAY
        ]
        candidate = tuesdays[3]
        if candidate >= after:
            return candidate
        if month == 12:
            year, month = year + 1, 1
        else:
            month += 1


H2H_NEXT_DATE = resolve_next_fourth_tuesday(FROZEN_TODAY)
H2H_OCCURRENCE_ID = f"h2h-{H2H_NEXT_DATE.isoformat()}"
# The current direct checkout capture was taken on 2026-08-09 and exposed
# the next recurring session on the fourth Tuesday, August 25.  Keep the
# historical task occurrence above for immutable task compatibility while
# giving the public captured route its own authoritative occurrence.
H2H_SOURCE_CURRENT_DATE = resolve_next_fourth_tuesday(date(2026, 8, 9))
H2H_SOURCE_OCCURRENCE_ID = f"h2h-{H2H_SOURCE_CURRENT_DATE.isoformat()}"


def admin_token() -> str:
    return (
        os.environ.get(ADMIN_TOKEN_ENV, "").strip()
        or os.environ.get(LEGACY_ADMIN_TOKEN_ENV, "").strip()
    )


def admin_host() -> str:
    return os.environ.get(ADMIN_HOST_ENV, "").strip().casefold()


def order_reference_for(event_id: str, occurrence_id: str, email: str) -> str:
    """Deterministic order reference: duplicate submits of the same draft
    (same event + occurrence + attendee email) map to the same reference."""
    digest = hashlib.sha256(
        f"{event_id}|{occurrence_id}|{email}".encode("utf-8")
    ).hexdigest()
    return f"local-{digest[:12]}"


class Migration(NamedTuple):
    version: int
    name: str
    sql: str


MIGRATIONS: list[Migration] = [
    Migration(
        1,
        "core-catalog",
        """
        CREATE TABLE IF NOT EXISTS organizers (
            id TEXT PRIMARY KEY,
            name TEXT NOT NULL
        );
        CREATE TABLE IF NOT EXISTS accounts (
            id INTEGER PRIMARY KEY,
            slug TEXT NOT NULL UNIQUE,
            display_name TEXT NOT NULL,
            email TEXT NOT NULL
        );
        CREATE TABLE IF NOT EXISTS events (
            id TEXT PRIMARY KEY,
            slug TEXT NOT NULL UNIQUE,
            title TEXT NOT NULL,
            organizer_id TEXT NOT NULL REFERENCES organizers(id),
            venue TEXT NOT NULL,
            address TEXT NOT NULL,
            city TEXT NOT NULL,
            timezone TEXT NOT NULL,
            synthetic INTEGER NOT NULL DEFAULT 0,
            recurrence TEXT,
            hero TEXT NOT NULL,
            hero_2x TEXT NOT NULL,
            avatar TEXT,
            map_asset TEXT,
            overview TEXT NOT NULL DEFAULT ''
        );
        CREATE TABLE IF NOT EXISTS occurrences (
            id TEXT PRIMARY KEY,
            event_id TEXT NOT NULL REFERENCES events(id) ON DELETE CASCADE,
            start_at TEXT NOT NULL,
            end_at TEXT NOT NULL,
            label TEXT NOT NULL
        );
        CREATE TABLE IF NOT EXISTS ticket_classes (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            occurrence_id TEXT NOT NULL
                REFERENCES occurrences(id) ON DELETE CASCADE,
            name TEXT NOT NULL,
            price_cents INTEGER NOT NULL CHECK (price_cents >= 0),
            capacity INTEGER NOT NULL CHECK (capacity >= 0),
            per_order_max INTEGER NOT NULL CHECK (per_order_max >= 1),
            sales_start_at TEXT NOT NULL,
            sales_end_at TEXT NOT NULL,
            version INTEGER NOT NULL DEFAULT 1
        );
        """,
    ),
    Migration(
        2,
        "orders-registrations-organizer-events",
        """
        CREATE TABLE IF NOT EXISTS orders (
            reference TEXT PRIMARY KEY,
            account_id INTEGER NOT NULL
                REFERENCES accounts(id) ON DELETE CASCADE,
            event_id TEXT NOT NULL REFERENCES events(id),
            occurrence_id TEXT NOT NULL REFERENCES occurrences(id),
            email TEXT NOT NULL,
            first_name TEXT NOT NULL,
            last_name TEXT NOT NULL,
            total_cents INTEGER NOT NULL CHECK (total_cents >= 0),
            created_at TEXT NOT NULL
        );
        CREATE TABLE IF NOT EXISTS order_lines (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            order_reference TEXT NOT NULL
                REFERENCES orders(reference) ON DELETE CASCADE,
            ticket_class_id INTEGER NOT NULL REFERENCES ticket_classes(id),
            quantity INTEGER NOT NULL CHECK (quantity >= 1),
            unit_price_cents INTEGER NOT NULL CHECK (unit_price_cents >= 0)
        );
        CREATE TABLE IF NOT EXISTS registrations (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            order_reference TEXT NOT NULL
                REFERENCES orders(reference) ON DELETE CASCADE,
            ticket_class_id INTEGER NOT NULL REFERENCES ticket_classes(id),
            seq INTEGER NOT NULL,
            first_name TEXT NOT NULL,
            last_name TEXT NOT NULL,
            email TEXT NOT NULL
        );
        CREATE TABLE IF NOT EXISTS organizer_events (
            id TEXT PRIMARY KEY,
            title TEXT NOT NULL,
            event_date TEXT NOT NULL,
            location TEXT NOT NULL,
            description TEXT NOT NULL,
            owner TEXT NOT NULL,
            created_at TEXT NOT NULL
        );
        """,
    ),
    Migration(
        3,
        "persistent-sessions",
        """
        CREATE TABLE IF NOT EXISTS sessions (
            token TEXT PRIMARY KEY,
            account_id INTEGER NOT NULL
                REFERENCES accounts(id) ON DELETE CASCADE,
            created_at TEXT NOT NULL
        );
        """,
    ),
    Migration(
        4,
        "command-authority-and-organizer-roles",
        """
        ALTER TABLE accounts ADD COLUMN role TEXT NOT NULL DEFAULT 'attendee'
            CHECK (role IN ('attendee','organizer'));
        UPDATE accounts SET role='organizer' WHERE slug='jordan-rivera';

        ALTER TABLE organizer_events ADD COLUMN version INTEGER NOT NULL DEFAULT 1;
        ALTER TABLE organizer_events ADD COLUMN status TEXT NOT NULL DEFAULT 'published-local'
            CHECK (status IN ('published-local','deleted'));

        CREATE TABLE IF NOT EXISTS organizer_event_drafts (
            id TEXT PRIMARY KEY,
            owner TEXT NOT NULL,
            version INTEGER NOT NULL CHECK (version >= 1),
            title TEXT NOT NULL,
            event_date TEXT NOT NULL,
            location TEXT NOT NULL,
            description TEXT NOT NULL
        );
        CREATE TABLE IF NOT EXISTS ticket_order_commands (
            command_id TEXT PRIMARY KEY,
            owner TEXT NOT NULL,
            idempotency_key TEXT NOT NULL,
            payload_digest TEXT NOT NULL,
            order_reference TEXT NOT NULL REFERENCES orders(reference),
            expected_version INTEGER NOT NULL,
            canonical_result TEXT NOT NULL,
            created_at TEXT NOT NULL,
            UNIQUE(owner, idempotency_key)
        );
        CREATE TABLE IF NOT EXISTS ticket_order_version_journal (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            ticket_class_id INTEGER NOT NULL REFERENCES ticket_classes(id),
            prior_version INTEGER NOT NULL,
            version INTEGER NOT NULL,
            command_id TEXT NOT NULL UNIQUE REFERENCES ticket_order_commands(command_id),
            outcome_digest TEXT NOT NULL,
            created_at TEXT NOT NULL
        );
        CREATE TABLE IF NOT EXISTS organizer_event_commands (
            command_id TEXT PRIMARY KEY,
            owner TEXT NOT NULL,
            idempotency_key TEXT NOT NULL,
            payload_digest TEXT NOT NULL,
            operation TEXT NOT NULL CHECK (operation IN ('create','delete')),
            event_id TEXT NOT NULL,
            expected_version INTEGER NOT NULL,
            canonical_result TEXT NOT NULL,
            created_at TEXT NOT NULL,
            UNIQUE(owner, idempotency_key)
        );
        CREATE TABLE IF NOT EXISTS organizer_event_version_journal (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            event_id TEXT NOT NULL,
            prior_version INTEGER NOT NULL,
            version INTEGER NOT NULL,
            command_id TEXT NOT NULL UNIQUE REFERENCES organizer_event_commands(command_id),
            outcome_digest TEXT NOT NULL,
            created_at TEXT NOT NULL
        );
        """,
    ),
    Migration(
        5,
        "discovery-taxonomy-and-social",
        """
        CREATE TABLE IF NOT EXISTS places (
            slug TEXT PRIMARY KEY,
            label TEXT NOT NULL,
            directory_label TEXT NOT NULL,
            breadcrumb TEXT NOT NULL,
            kind TEXT NOT NULL DEFAULT 'city'
                CHECK (kind IN ('city','metro','region','online')),
            parent_slug TEXT,
            timezone TEXT NOT NULL,
            rank INTEGER NOT NULL DEFAULT 0
        );
        CREATE TABLE IF NOT EXISTS categories (
            slug TEXT PRIMARY KEY,
            label TEXT NOT NULL,
            icon TEXT NOT NULL DEFAULT '',
            rank INTEGER NOT NULL DEFAULT 0
        );
        -- A feed is an ordered list of PLACEMENTS, not a set of events: the
        -- real home page lists the same event twice, at different ranks and
        -- with different urgency badges. The primary key carries rank so
        -- that stays representable.
        CREATE TABLE IF NOT EXISTS event_placements (
            place_slug TEXT NOT NULL REFERENCES places(slug) ON DELETE CASCADE,
            event_id TEXT NOT NULL REFERENCES events(id) ON DELETE CASCADE,
            rank INTEGER NOT NULL,
            source TEXT NOT NULL DEFAULT 'publication'
                CHECK (source IN ('publication','geography')),
            badge TEXT NOT NULL DEFAULT '',
            PRIMARY KEY (place_slug, source, rank)
        );
        CREATE TABLE IF NOT EXISTS neighborhoods (
            slug TEXT PRIMARY KEY,
            place_slug TEXT NOT NULL REFERENCES places(slug) ON DELETE CASCADE,
            label TEXT NOT NULL,
            rank INTEGER NOT NULL DEFAULT 0
        );
        CREATE TABLE IF NOT EXISTS event_neighborhoods (
            event_id TEXT NOT NULL REFERENCES events(id) ON DELETE CASCADE,
            neighborhood_slug TEXT NOT NULL
                REFERENCES neighborhoods(slug) ON DELETE CASCADE,
            PRIMARY KEY (event_id, neighborhood_slug)
        );
        CREATE TABLE IF NOT EXISTS place_trends (
            place_slug TEXT NOT NULL REFERENCES places(slug) ON DELETE CASCADE,
            rank INTEGER NOT NULL,
            label TEXT NOT NULL,
            PRIMARY KEY (place_slug, rank)
        );
        CREATE TABLE IF NOT EXISTS event_faqs (
            event_id TEXT NOT NULL REFERENCES events(id) ON DELETE CASCADE,
            seq INTEGER NOT NULL,
            question TEXT NOT NULL,
            answer TEXT NOT NULL,
            PRIMARY KEY (event_id, seq)
        );
        CREATE TABLE IF NOT EXISTS saved_events (
            account_id INTEGER NOT NULL
                REFERENCES accounts(id) ON DELETE CASCADE,
            event_id TEXT NOT NULL REFERENCES events(id) ON DELETE CASCADE,
            created_at TEXT NOT NULL,
            PRIMARY KEY (account_id, event_id)
        );
        CREATE TABLE IF NOT EXISTS organizer_follows (
            account_id INTEGER NOT NULL
                REFERENCES accounts(id) ON DELETE CASCADE,
            organizer_id TEXT NOT NULL
                REFERENCES organizers(id) ON DELETE CASCADE,
            created_at TEXT NOT NULL,
            PRIMARY KEY (account_id, organizer_id)
        );

        ALTER TABLE events ADD COLUMN category_slug TEXT NOT NULL DEFAULT 'other';
        ALTER TABLE events ADD COLUMN format_slug TEXT NOT NULL DEFAULT 'other';
        ALTER TABLE events ADD COLUMN is_online INTEGER NOT NULL DEFAULT 0;
        ALTER TABLE events ADD COLUMN age_restriction TEXT NOT NULL DEFAULT '';
        ALTER TABLE events ADD COLUMN parking TEXT NOT NULL DEFAULT '';
        ALTER TABLE events ADD COLUMN language TEXT NOT NULL DEFAULT 'en';
        ALTER TABLE ticket_classes ADD COLUMN currency TEXT NOT NULL DEFAULT 'usd';
        -- Tickets already sold before this catalog snapshot. A live
        -- listing is never empty, and availability has to reflect that
        -- for "N spots remaining" and the urgency badges to mean anything.
        ALTER TABLE ticket_classes ADD COLUMN sold_baseline INTEGER NOT NULL
            DEFAULT 0 CHECK (sold_baseline >= 0);
        ALTER TABLE organizers ADD COLUMN slug TEXT NOT NULL DEFAULT '';
        ALTER TABLE organizers ADD COLUMN hosting_since TEXT NOT NULL DEFAULT '';
        ALTER TABLE organizers ADD COLUMN follower_count INTEGER NOT NULL DEFAULT 0;
        ALTER TABLE ticket_classes ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;
        """,
    ),
    Migration(
        6,
        "builder-v2",
        """
        -- The multi-step event builder works on a structured draft. The
        -- legacy event_date/location/description columns stay authoritative
        -- for the old auto-create flow; the builder keeps them mirrored so
        -- either surface can render any draft.
        ALTER TABLE organizer_event_drafts ADD COLUMN summary TEXT NOT NULL DEFAULT '';
        ALTER TABLE organizer_event_drafts ADD COLUMN start_at TEXT NOT NULL DEFAULT '';
        ALTER TABLE organizer_event_drafts ADD COLUMN end_at TEXT NOT NULL DEFAULT '';
        ALTER TABLE organizer_event_drafts ADD COLUMN timezone TEXT NOT NULL DEFAULT 'America/Los_Angeles';
        ALTER TABLE organizer_event_drafts ADD COLUMN location_type TEXT NOT NULL DEFAULT 'venue'
            CHECK (location_type IN ('venue','online','tbd'));
        ALTER TABLE organizer_event_drafts ADD COLUMN venue_name TEXT NOT NULL DEFAULT '';
        ALTER TABLE organizer_event_drafts ADD COLUMN venue_address TEXT NOT NULL DEFAULT '';
        ALTER TABLE organizer_event_drafts ADD COLUMN venue_city TEXT NOT NULL DEFAULT '';
        ALTER TABLE organizer_event_drafts ADD COLUMN image_ref TEXT NOT NULL DEFAULT '';
        ALTER TABLE organizer_event_drafts ADD COLUMN overview TEXT NOT NULL DEFAULT '';
        ALTER TABLE organizer_event_drafts ADD COLUMN category_slug TEXT NOT NULL DEFAULT 'other';
        ALTER TABLE organizer_event_drafts ADD COLUMN status TEXT NOT NULL DEFAULT 'draft'
            CHECK (status IN ('draft','published'));
        ALTER TABLE organizer_event_drafts ADD COLUMN published_event_id TEXT NOT NULL DEFAULT '';
        -- Deterministic monotonic edit counter (no wall clock): drives the
        -- Saving/Saved indicator ordering and dashboard sort.
        ALTER TABLE organizer_event_drafts ADD COLUMN updated_seq INTEGER NOT NULL DEFAULT 0;

        CREATE TABLE IF NOT EXISTS draft_ticket_classes (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            draft_id TEXT NOT NULL
                REFERENCES organizer_event_drafts(id) ON DELETE CASCADE,
            name TEXT NOT NULL,
            kind TEXT NOT NULL DEFAULT 'free'
                CHECK (kind IN ('free','paid','donation')),
            price_cents INTEGER NOT NULL DEFAULT 0 CHECK (price_cents >= 0),
            quantity INTEGER NOT NULL DEFAULT 100 CHECK (quantity >= 1),
            per_order_max INTEGER NOT NULL DEFAULT 10
                CHECK (per_order_max >= 1),
            sales_start_at TEXT NOT NULL DEFAULT '',
            sales_end_at TEXT NOT NULL DEFAULT '',
            rank INTEGER NOT NULL DEFAULT 0
        );
        -- Uploaded event images keyed by content hash: the same bytes always
        -- produce the same id, so uploads are naturally idempotent.
        CREATE TABLE IF NOT EXISTS uploaded_images (
            sha TEXT PRIMARY KEY,
            owner TEXT NOT NULL,
            mime TEXT NOT NULL,
            bytes INTEGER NOT NULL CHECK (bytes > 0),
            width INTEGER NOT NULL DEFAULT 0,
            height INTEGER NOT NULL DEFAULT 0,
            content BLOB NOT NULL,
            created_at TEXT NOT NULL
        );
        -- organizer_event_commands has a frozen CHECK(operation IN
        -- ('create','delete')) that SQLite cannot widen, so the builder
        -- carries its own command ledger with the same idempotency and
        -- journal semantics.
        CREATE TABLE IF NOT EXISTS builder_commands (
            command_id TEXT PRIMARY KEY,
            owner TEXT NOT NULL,
            idempotency_key TEXT NOT NULL,
            payload_digest TEXT NOT NULL,
            operation TEXT NOT NULL CHECK (operation IN (
                'draft-create','draft-update','ticket-create','ticket-update',
                'ticket-delete','publish','unpublish')),
            draft_id TEXT NOT NULL,
            expected_version INTEGER NOT NULL,
            canonical_result TEXT NOT NULL,
            created_at TEXT NOT NULL,
            UNIQUE(owner, idempotency_key)
        );
        CREATE TABLE IF NOT EXISTS builder_version_journal (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            draft_id TEXT NOT NULL,
            prior_version INTEGER NOT NULL,
            version INTEGER NOT NULL,
            command_id TEXT NOT NULL UNIQUE
                REFERENCES builder_commands(command_id),
            outcome_digest TEXT NOT NULL,
            created_at TEXT NOT NULL
        );
        """,
    ),
    Migration(
        7,
        "builder-online-and-organizer-details",
        """
        -- Online events need the named delivery platform even though join
        -- URLs remain private, and an event's public organizer name may
        -- differ from the owning account's display name.
        ALTER TABLE organizer_event_drafts ADD COLUMN online_platform TEXT NOT NULL DEFAULT '';
        ALTER TABLE organizer_event_drafts ADD COLUMN organizer_name TEXT NOT NULL DEFAULT '';

        -- Keep an untouched deployed fixture account aligned with the exact
        -- historical task organizer. The full guard leaves user-edited
        -- account names intact.
        UPDATE accounts
           SET display_name='Alex Green'
         WHERE id=1
           AND slug='jordan-rivera'
           AND display_name='Jordan Rivera'
           AND email='jordan.rivera@example.test'
           AND role='organizer';

        -- Repair only the untouched historical task seed. User-edited
        -- drafts have a different version or values and are never reset by
        -- a forward migration.
        UPDATE organizer_event_drafts
           SET event_date='2026-04-15 18:00',
               location='Online (Zoom)',
               description='Weekly paper reading group focusing on recent ML research. This week: attention mechanisms and transformer architectures. All levels welcome.',
               summary='Weekly paper reading group focusing on recent ML research.',
               start_at='2026-04-15T18:00',
               end_at='2026-04-15T20:00',
               timezone='America/New_York',
               location_type='online',
               venue_name='', venue_address='', venue_city='',
               online_platform='Zoom', organizer_name='Alex Green',
               overview='Weekly paper reading group focusing on recent ML research. This week: attention mechanisms and transformer architectures. All levels welcome.',
               category_slug='science-and-tech'
         WHERE id='draft:task-372:ml-paper-reading-group'
           AND version=1
           AND event_date='2026-09-10 18:00'
           AND location='Community Hall, Room 2'
           AND description='Weekly reading group walking through one machine-learning paper per session.';

        INSERT INTO draft_ticket_classes
            (draft_id, name, kind, price_cents, quantity, per_order_max,
             sales_start_at, sales_end_at, rank)
        SELECT id, 'General Admission', 'free', 0, 50, 10,
               '2026-01-01T00:00:00-05:00',
               '2026-04-15T18:00:00-04:00', 0
          FROM organizer_event_drafts d
         WHERE d.id='draft:task-372:ml-paper-reading-group'
           AND d.version=1
           AND d.event_date='2026-04-15 18:00'
           AND d.location='Online (Zoom)'
           AND NOT EXISTS (
               SELECT 1 FROM draft_ticket_classes t
                WHERE t.draft_id=d.id
           );
        """,
    ),
    Migration(
        8,
        "ticket-payment-binding",
        """
        -- Paid orders retain the opaque local-sandbox authorization identity.
        -- These are deliberately not foreign keys: the shared payment ledger
        -- owns its schema and validates/consumes the flow inside the same
        -- transaction that inserts the order.
        ALTER TABLE orders ADD COLUMN payment_flow_id TEXT NOT NULL DEFAULT '';
        ALTER TABLE orders ADD COLUMN payment_fingerprint TEXT NOT NULL DEFAULT '';
        """,
    ),
    Migration(
        9,
        "organization-workspace",
        """
        -- One local organization owns every organizer-workspace resource.
        -- The account and event links are explicit so tenant/owner checks do
        -- not depend on a user-supplied organization id.
        CREATE TABLE IF NOT EXISTS organizations (
            id TEXT PRIMARY KEY,
            name TEXT NOT NULL,
            owner_account_id INTEGER NOT NULL REFERENCES accounts(id),
            timezone TEXT NOT NULL DEFAULT 'America/Los_Angeles',
            currency TEXT NOT NULL DEFAULT 'USD',
            payout_schedule TEXT NOT NULL DEFAULT 'monthly',
            version INTEGER NOT NULL DEFAULT 1 CHECK (version >= 1),
            created_at TEXT NOT NULL,
            updated_at TEXT NOT NULL
        );
        CREATE TABLE IF NOT EXISTS memberships (
            id TEXT PRIMARY KEY,
            organization_id TEXT NOT NULL
                REFERENCES organizations(id) ON DELETE CASCADE,
            account_id INTEGER REFERENCES accounts(id) ON DELETE SET NULL,
            email TEXT NOT NULL,
            role TEXT NOT NULL CHECK (role IN (
                'owner','admin','marketing','finance','check-in','reporting','viewer'
            )),
            status TEXT NOT NULL CHECK (status IN ('invited','active','revoked')),
            version INTEGER NOT NULL DEFAULT 1 CHECK (version >= 1),
            invited_by INTEGER REFERENCES accounts(id),
            created_at TEXT NOT NULL,
            updated_at TEXT NOT NULL,
            UNIQUE(organization_id, email)
        );
        CREATE TABLE IF NOT EXISTS organization_event_links (
            organization_id TEXT NOT NULL
                REFERENCES organizations(id) ON DELETE CASCADE,
            event_id TEXT NOT NULL REFERENCES events(id) ON DELETE CASCADE,
            created_at TEXT NOT NULL,
            PRIMARY KEY (organization_id, event_id)
        );
        CREATE TABLE IF NOT EXISTS organization_attendees (
            id TEXT PRIMARY KEY,
            organization_id TEXT NOT NULL
                REFERENCES organizations(id) ON DELETE CASCADE,
            event_id TEXT NOT NULL REFERENCES events(id) ON DELETE CASCADE,
            order_reference TEXT NOT NULL REFERENCES orders(reference) ON DELETE CASCADE,
            registration_id INTEGER NOT NULL
                REFERENCES registrations(id) ON DELETE CASCADE,
            first_name TEXT NOT NULL,
            last_name TEXT NOT NULL,
            email TEXT NOT NULL,
            check_in_status TEXT NOT NULL DEFAULT 'not-checked-in'
                CHECK (check_in_status IN ('not-checked-in','checked-in','voided')),
            version INTEGER NOT NULL DEFAULT 1 CHECK (version >= 1),
            created_at TEXT NOT NULL,
            updated_at TEXT NOT NULL,
            UNIQUE(organization_id, registration_id)
        );
        CREATE TABLE IF NOT EXISTS check_ins (
            id TEXT PRIMARY KEY,
            organization_id TEXT NOT NULL
                REFERENCES organizations(id) ON DELETE CASCADE,
            attendee_id TEXT NOT NULL
                REFERENCES organization_attendees(id) ON DELETE CASCADE,
            operation TEXT NOT NULL CHECK (operation IN ('check-in','void')),
            status TEXT NOT NULL CHECK (status IN ('checked-in','voided')),
            version INTEGER NOT NULL DEFAULT 1 CHECK (version >= 1),
            remote_effect_count INTEGER NOT NULL DEFAULT 0 CHECK (remote_effect_count = 0),
            actor_account_id INTEGER NOT NULL REFERENCES accounts(id),
            created_at TEXT NOT NULL
        );
        CREATE TABLE IF NOT EXISTS refunds (
            id TEXT PRIMARY KEY,
            organization_id TEXT NOT NULL
                REFERENCES organizations(id) ON DELETE CASCADE,
            order_reference TEXT NOT NULL REFERENCES orders(reference),
            amount_cents INTEGER NOT NULL CHECK (amount_cents >= 0),
            currency TEXT NOT NULL DEFAULT 'USD',
            reason TEXT NOT NULL,
            status TEXT NOT NULL
                CHECK (status IN ('requested','approved','rejected','completed')),
            payment_adapter TEXT NOT NULL CHECK (payment_adapter = 'local-sandbox'),
            version INTEGER NOT NULL DEFAULT 1 CHECK (version >= 1),
            remote_effect_count INTEGER NOT NULL DEFAULT 0 CHECK (remote_effect_count = 0),
            created_by INTEGER NOT NULL REFERENCES accounts(id),
            created_at TEXT NOT NULL,
            updated_at TEXT NOT NULL
        );
        CREATE TABLE IF NOT EXISTS campaigns (
            id TEXT PRIMARY KEY,
            organization_id TEXT NOT NULL
                REFERENCES organizations(id) ON DELETE CASCADE,
            name TEXT NOT NULL,
            status TEXT NOT NULL CHECK (status IN (
                'draft','scheduled','running','paused','completed','canceled'
            )),
            budget_cents INTEGER NOT NULL DEFAULT 0 CHECK (budget_cents >= 0),
            scheduled_for TEXT NOT NULL DEFAULT '',
            result_summary TEXT NOT NULL DEFAULT '',
            version INTEGER NOT NULL DEFAULT 1 CHECK (version >= 1),
            remote_effect_count INTEGER NOT NULL DEFAULT 0 CHECK (remote_effect_count = 0),
            created_by INTEGER NOT NULL REFERENCES accounts(id),
            created_at TEXT NOT NULL,
            updated_at TEXT NOT NULL
        );
        CREATE TABLE IF NOT EXISTS ads (
            id TEXT PRIMARY KEY,
            organization_id TEXT NOT NULL
                REFERENCES organizations(id) ON DELETE CASCADE,
            name TEXT NOT NULL,
            status TEXT NOT NULL CHECK (status IN (
                'draft','scheduled','running','paused','completed','canceled'
            )),
            budget_cents INTEGER NOT NULL DEFAULT 0 CHECK (budget_cents >= 0),
            scheduled_for TEXT NOT NULL DEFAULT '',
            result_summary TEXT NOT NULL DEFAULT '',
            version INTEGER NOT NULL DEFAULT 1 CHECK (version >= 1),
            remote_effect_count INTEGER NOT NULL DEFAULT 0 CHECK (remote_effect_count = 0),
            created_by INTEGER NOT NULL REFERENCES accounts(id),
            created_at TEXT NOT NULL,
            updated_at TEXT NOT NULL
        );
        CREATE TABLE IF NOT EXISTS analytics_snapshots (
            id TEXT PRIMARY KEY,
            organization_id TEXT NOT NULL
                REFERENCES organizations(id) ON DELETE CASCADE,
            gross_cents INTEGER NOT NULL DEFAULT 0 CHECK (gross_cents >= 0),
            order_count INTEGER NOT NULL DEFAULT 0 CHECK (order_count >= 0),
            attendee_count INTEGER NOT NULL DEFAULT 0 CHECK (attendee_count >= 0),
            checked_in_count INTEGER NOT NULL DEFAULT 0 CHECK (checked_in_count >= 0),
            refunded_cents INTEGER NOT NULL DEFAULT 0 CHECK (refunded_cents >= 0),
            source TEXT NOT NULL CHECK (source = 'local-derived'),
            captured_at TEXT NOT NULL
        );
        CREATE TABLE IF NOT EXISTS payout_ledger (
            id TEXT PRIMARY KEY,
            organization_id TEXT NOT NULL
                REFERENCES organizations(id) ON DELETE CASCADE,
            amount_cents INTEGER NOT NULL CHECK (amount_cents >= 0),
            currency TEXT NOT NULL DEFAULT 'USD',
            schedule TEXT NOT NULL DEFAULT 'monthly',
            status TEXT NOT NULL
                CHECK (status IN ('scheduled','processing','paid','failed','canceled')),
            payment_adapter TEXT NOT NULL CHECK (payment_adapter = 'local-sandbox'),
            version INTEGER NOT NULL DEFAULT 1 CHECK (version >= 1),
            remote_effect_count INTEGER NOT NULL DEFAULT 0 CHECK (remote_effect_count = 0),
            created_by INTEGER NOT NULL REFERENCES accounts(id),
            created_at TEXT NOT NULL,
            updated_at TEXT NOT NULL
        );
        CREATE TABLE IF NOT EXISTS integration_connections (
            id TEXT PRIMARY KEY,
            organization_id TEXT NOT NULL
                REFERENCES organizations(id) ON DELETE CASCADE,
            integration_slug TEXT NOT NULL,
            display_name TEXT NOT NULL,
            status TEXT NOT NULL CHECK (status IN ('connected','disconnected')),
            connection_mode TEXT NOT NULL CHECK (connection_mode = 'local-simulation'),
            version INTEGER NOT NULL DEFAULT 1 CHECK (version >= 1),
            remote_effect_count INTEGER NOT NULL DEFAULT 0 CHECK (remote_effect_count = 0),
            created_by INTEGER NOT NULL REFERENCES accounts(id),
            created_at TEXT NOT NULL,
            updated_at TEXT NOT NULL,
            UNIQUE(organization_id, integration_slug)
        );
        CREATE TABLE IF NOT EXISTS account_preferences (
            account_id INTEGER PRIMARY KEY REFERENCES accounts(id) ON DELETE CASCADE,
            locale TEXT NOT NULL DEFAULT 'en-US',
            timezone TEXT NOT NULL DEFAULT 'America/Los_Angeles',
            event_updates INTEGER NOT NULL DEFAULT 1 CHECK (event_updates IN (0,1)),
            organizer_updates INTEGER NOT NULL DEFAULT 1 CHECK (organizer_updates IN (0,1)),
            version INTEGER NOT NULL DEFAULT 1 CHECK (version >= 1),
            updated_at TEXT NOT NULL
        );
        CREATE TABLE IF NOT EXISTS account_preference_commands (
            command_id TEXT PRIMARY KEY,
            account_id INTEGER NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
            idempotency_key TEXT NOT NULL,
            payload_digest TEXT NOT NULL,
            expected_version INTEGER NOT NULL,
            canonical_result TEXT NOT NULL,
            created_at TEXT NOT NULL,
            UNIQUE(account_id, idempotency_key)
        );
        CREATE TABLE IF NOT EXISTS organization_commands (
            command_id TEXT PRIMARY KEY,
            organization_id TEXT NOT NULL
                REFERENCES organizations(id) ON DELETE CASCADE,
            actor_account_id INTEGER NOT NULL REFERENCES accounts(id),
            idempotency_key TEXT NOT NULL,
            payload_digest TEXT NOT NULL,
            resource TEXT NOT NULL,
            operation TEXT NOT NULL,
            resource_id TEXT NOT NULL,
            expected_version INTEGER NOT NULL,
            canonical_result TEXT NOT NULL,
            created_at TEXT NOT NULL,
            UNIQUE(organization_id, actor_account_id, idempotency_key)
        );
        """,
    ),
]

MIGRATION_HEAD = MIGRATIONS[-1].version

# Deletion order respects foreign keys (children first).
BUSINESS_TABLES = (
    "organization_commands",
    "account_preference_commands",
    "check_ins",
    "refunds",
    "campaigns",
    "ads",
    "analytics_snapshots",
    "payout_ledger",
    "integration_connections",
    "organization_attendees",
    "organization_event_links",
    "memberships",
    "organizations",
    "account_preferences",
    "builder_version_journal",
    "builder_commands",
    "organizer_event_version_journal",
    "organizer_event_commands",
    "ticket_order_version_journal",
    "ticket_order_commands",
    "registrations",
    "order_lines",
    "orders",
    "sessions",
    "organizer_events",
    "draft_ticket_classes",
    "uploaded_images",
    "organizer_event_drafts",
    "saved_events",
    "organizer_follows",
    "event_faqs",
    "event_neighborhoods",
    "event_placements",
    "ticket_classes",
    "occurrences",
    "events",
    "accounts",
    "neighborhoods",
    "place_trends",
    "places",
    "categories",
    "organizers",
)

LOCAL_ORGANIZER = "org-local-benchmark"
FOREIGN_ORGANIZER = "org-foreign"

# (id, name, followers, hosting since). Follower counts and tenure come
# from the captured organizer strips; they are a starting balance that
# real follows move, not a decoration.
SEED_ORGANIZERS = (
    ("org-hearts2heal", "Hearts 2 Heal", 43, "2020-01-01"),
    ("org-latin-city", "Latin City", 8700, "2011-01-01"),
    ("org-clawbench", "Community Events Collective", 128, "2019-01-01"),
)

SEED_ACCOUNTS = (
    (
        1,
        "jordan-rivera",
        "Alex Green",
        "jordan.rivera@example.test",
        "organizer",
    ),
    (2, "casey-kim", "Casey Kim", "casey.kim@example.test", "attendee"),
)

PRIMARY_ACCOUNT_SLUG = "jordan-rivera"
SECONDARY_ACCOUNT_SLUG = "casey-kim"

_SYNTHETIC_OVERVIEW = (
    f"{SYNTHETIC_LABEL}. This event, its venue, and its schedule are wholly "
    "illustrative and have no corresponding published Eventbrite listing."
)

# (id, slug, title, organizer_id, venue, address, city, timezone,
#  synthetic, recurrence, hero, hero_2x, avatar, map_asset, overview)
SEED_EVENTS = (
    (
        "1983102574183",
        "hearts2heal-monthly-wellness-meetup-tickets-1983102574183",
        "Hearts2Heal Monthly Wellness Meetup",
        "org-hearts2heal",
        "Capital Factory",
        "701 Brazos St, Austin, TX 78701",
        "Austin, TX",
        "America/Chicago",
        0,
        "every 4th Tuesday",
        f"{ASSET_BASE}/hearts2heal-event/hearts2heal-hero-940.jpg",
        f"{ASSET_BASE}/hearts2heal-event/hearts2heal-hero-1880.jpg",
        f"{ASSET_BASE}/hearts2heal-event/hearts2heal-organizer-avatar-128.jpg",
        f"{ASSET_BASE}/hearts2heal-event/event-location-map-384.png",
        (
            "Join Hearts2Heal every 4th Tuesday, explore mental wellness "
            "with engaging topics, speakers, and fellow professionals & "
            "entrepreneurs. Sessions run 6:30 to 8:00 p.m. at Capital "
            "Factory, 16th Floor (Antone\u2019s), 701 Brazos St, Austin, "
            "TX 78701."
        ),
    ),
    (
        "1980904085444",
        "sazon-latin-food-festival-2026-chicagos-taste-of-latin-american-"
        "food-tickets-1980904085444",
        "Saz\u00f3n Latin Food Festival 2026: Chicago\u2019s Taste of Latin "
        "American Food",
        "org-latin-city",
        "KOVAL Store",
        "KOVAL Store, Chicago, IL",
        "Chicago, IL",
        "America/Chicago",
        0,
        None,
        f"{ASSET_BASE}/sazon-festival-event/sazon-hero-940.jpg",
        f"{ASSET_BASE}/sazon-festival-event/sazon-hero-1880.jpg",
        f"{ASSET_BASE}/sazon-festival-event/sazon-organizer-avatar-128.png",
        None,
        (
            "Chicago\u2019s taste of Latin American food, hosted by Latin "
            "City at the KOVAL Store. One fixed occurrence: Sunday, June "
            "14, 2026, 12 PM - 5 PM."
        ),
    ),
    (
        "synthetic-sf-tech-networking-night",
        "sf-tech-networking-night-tickets-0000000560",
        "SF Tech Networking Night",
        "org-clawbench",
        "Foundry Hall",
        "123 Mission St, San Francisco, CA",
        "San Francisco, CA",
        "America/Los_Angeles",
        1,
        None,
        "/static/art/synthetic-sf-card.svg",
        "/static/art/synthetic-sf-card.svg",
        None,
        None,
        _SYNTHETIC_OVERVIEW,
    ),
    (
        "synthetic-ny-startup-pitch-night",
        "ny-startup-pitch-night-tickets-0000000564",
        "NY Startup Pitch Night",
        "org-clawbench",
        "Hudson Works Loft",
        "Hudson Works Loft, New York, NY",
        "New York, NY",
        "America/New_York",
        1,
        None,
        "/static/art/synthetic-ny-card.svg",
        "/static/art/synthetic-ny-card.svg",
        None,
        None,
        _SYNTHETIC_OVERVIEW,
    ),
    (
        "synthetic-austin-vinyl-swap",
        "austin-vinyl-swap-tickets-0000000570",
        "Austin Vinyl Swap Meet",
        "org-clawbench",
        "Eastside Warehouse",
        "Eastside Warehouse, Austin, TX",
        "Austin, TX",
        "America/Chicago",
        1,
        None,
        "/static/art/synthetic-sf-card.svg",
        "/static/art/synthetic-sf-card.svg",
        None,
        None,
        _SYNTHETIC_OVERVIEW,
    ),
    (
        "synthetic-chicago-riverwalk-gala",
        "chicago-riverwalk-gala-tickets-0000000571",
        "Chicago Riverwalk Gala",
        "org-clawbench",
        "Riverwalk Pavilion",
        "Riverwalk Pavilion, Chicago, IL",
        "Chicago, IL",
        "America/Chicago",
        1,
        None,
        "/static/art/synthetic-ny-card.svg",
        "/static/art/synthetic-ny-card.svg",
        None,
        None,
        _SYNTHETIC_OVERVIEW,
    ),
    (
        "synthetic-atx-coffee-crawl",
        "atx-coffee-crawl-tickets-0000000572",
        "ATX Coffee Crawl",
        "org-clawbench",
        "South Congress Meetpoint",
        "South Congress Meetpoint, Austin, TX",
        "Austin, TX",
        "America/Chicago",
        1,
        None,
        "/static/art/synthetic-sf-card.svg",
        "/static/art/synthetic-sf-card.svg",
        None,
        None,
        _SYNTHETIC_OVERVIEW,
    ),
)

_H2H_NEXT_LABEL = (
    f"{H2H_NEXT_DATE.strftime('%A, %B')} {H2H_NEXT_DATE.day}, "
    f"{H2H_NEXT_DATE.year} \u00b7 6:30 - 8:00 PM CDT"
)

# (occurrence_id, event_id, start_at, end_at, label,
#  capacity, per_order_max, sales_start_at, sales_end_at)
SEED_OCCURRENCES = (
    (
        H2H_OCCURRENCE_ID,
        "1983102574183",
        f"{H2H_NEXT_DATE.isoformat()}T18:30:00-05:00",
        f"{H2H_NEXT_DATE.isoformat()}T20:00:00-05:00",
        _H2H_NEXT_LABEL,
        24,
        2,
        "2026-01-01T00:00:00-06:00",
        f"{H2H_NEXT_DATE.isoformat()}T18:30:00-05:00",
    ),
    (
        H2H_SOURCE_OCCURRENCE_ID,
        "1983102574183",
        f"{H2H_SOURCE_CURRENT_DATE.isoformat()}T18:30:00-05:00",
        f"{H2H_SOURCE_CURRENT_DATE.isoformat()}T20:00:00-05:00",
        "Tuesday, August 25, 2026 \u00b7 6:30 - 8:00 PM CDT",
        50,
        10,
        "2026-01-01T00:00:00-06:00",
        f"{H2H_SOURCE_CURRENT_DATE.isoformat()}T18:30:00-05:00",
        0,
        18,
    ),
    (
        "h2h-2026-05-26",
        "1983102574183",
        "2026-05-26T18:30:00-05:00",
        "2026-05-26T20:00:00-05:00",
        "Tuesday, May 26, 2026 \u00b7 6:30 - 8:00 PM CDT",
        24,
        2,
        "2026-01-01T00:00:00-06:00",
        "2026-05-26T18:30:00-05:00",
    ),
    (
        "sazon-2026-06-14",
        "1980904085444",
        "2026-06-14T12:00:00-05:00",
        "2026-06-14T17:00:00-05:00",
        "Sunday, June 14 \u00b7 12 PM - 5 PM CDT",
        40,
        2,
        "2026-01-01T00:00:00-06:00",
        "2026-06-14T12:00:00-05:00",
    ),
    (
        "sfnet-2026-08-06",
        "synthetic-sf-tech-networking-night",
        "2026-08-06T18:30:00-07:00",
        "2026-08-06T21:00:00-07:00",
        "Thursday, August 6, 2026 \u00b7 6:30 - 9:00 PM PT",
        2,
        1,
        "2026-01-01T00:00:00-08:00",
        "2026-08-06T18:30:00-07:00",
    ),
    (
        "nypitch-2026-08-05",
        "synthetic-ny-startup-pitch-night",
        "2026-08-05T19:00:00-04:00",
        "2026-08-05T22:00:00-04:00",
        "Wednesday, August 5, 2026 \u00b7 7:00 - 10:00 PM ET",
        2,
        2,
        "2026-01-01T00:00:00-05:00",
        "2026-08-05T19:00:00-04:00",
    ),
    # Already-ended event: real rejection data for the event-ended path.
    (
        "vinyl-2026-05-15",
        "synthetic-austin-vinyl-swap",
        "2026-05-15T15:00:00-05:00",
        "2026-05-15T19:00:00-05:00",
        "Friday, May 15, 2026 \u00b7 3:00 - 7:00 PM CDT",
        30,
        2,
        "2026-01-01T00:00:00-06:00",
        "2026-05-15T15:00:00-05:00",
    ),
    # Future event whose ticket sales window already closed: real
    # rejection data for the sales-window-closed path.
    (
        "gala-2026-07-10",
        "synthetic-chicago-riverwalk-gala",
        "2026-07-10T18:00:00-05:00",
        "2026-07-10T22:00:00-05:00",
        "Friday, July 10, 2026 \u00b7 6:00 - 10:00 PM CDT",
        60,
        4,
        "2026-01-01T00:00:00-06:00",
        "2026-05-30T23:59:00-05:00",
    ),
    # On-sale occurrence whose only ticket class is sold out via a seed
    # order: real rejection data for the sold-out path.
    (
        "coffee-2026-06-20",
        "synthetic-atx-coffee-crawl",
        "2026-06-20T09:00:00-05:00",
        "2026-06-20T12:00:00-05:00",
        "Saturday, June 20, 2026 \u00b7 9:00 AM - 12:00 PM CDT",
        1,
        1,
        "2026-01-01T00:00:00-06:00",
        "2026-06-20T09:00:00-05:00",
    ),
)

# Seed order that fills the ATX Coffee Crawl ticket class (capacity 1).
SEED_ORDER = {
    "event_id": "synthetic-atx-coffee-crawl",
    "occurrence_id": "coffee-2026-06-20",
    "account_slug": SECONDARY_ACCOUNT_SLUG,
    "email": "casey.kim@example.test",
    "first_name": "Casey",
    "last_name": "Kim",
    "quantity": 1,
}

SEED_ORGANIZER_EVENT = (
    "local-evt-f0r319n001",
    "Partner Organizer Event",
    "2026-09-01 18:00",
    "Elsewhere Hall",
    "Owned by a foreign organizer for boundary tests.",
    FOREIGN_ORGANIZER,
)

# Feed slots that no source listing card supplies. Rank 17 preserves the
# benchmark community event on the first page; source cards at rank 17 and
# above are shifted one position when registered so no primary-key collision
# can silently remove either identity.
SEED_PLACEMENTS = (
    ("ca--san-francisco", "synthetic-sf-tech-networking-night", 17, ""),
    ("ny--new-york", "synthetic-ny-startup-pitch-night", 17, ""),
)

# "Good to know" facts an organizer filled in, keyed by event.
# {event_id: (age_restriction, parking)}
SEED_EVENT_DETAILS = {
    "1983102574183": ("All ages", "Paid parking"),
    "1980904085444": ("All ages", "Street parking"),
}

# Read-only aggregates and browse location captured with two frozen event
# pages. They are presentation facts, not fabricated organizer rows or a
# branch in event behavior.
FROZEN_EVENT_DETAIL_CAPTURES = {
    "1983102574183": {
        "browse_place": {"slug": "or--boardman", "label": "Boardman"},
        "checkout_occurrence_id": H2H_SOURCE_OCCURRENCE_ID,
        "ticket_name": "Free Ticket",
        "organizer": {
            "top": False,
            "followers": "44",
            "events": "40",
            "hosting": "6y hosting",
            "attendees": "367 total attendees",
        },
    },
    "1980904085444": {
        "browse_place": {"slug": "or--boardman", "label": "Boardman"},
        "organizer": {
            "top": True,
            "followers": "8.9k",
            "events": "363",
            "hosting": "10y hosting",
            "attendees": "223.4k total attendees",
        },
    },
}

# Questions an organizer answered on their own event page. Only events
# whose organizer wrote them show the section, as on the source.
SEED_EVENT_FAQS = {
    "1983102574183": (
        (
            "Is parking available?",
            "Paid parking is available in the building; allow a few extra "
            "minutes to find a space.",
        ),
        (
            "Who should attend?",
            "Professionals and entrepreneurs interested in mental "
            "wellness. No background in the topic is needed.",
        ),
        (
            "Do I need to bring anything?",
            "Just yourself. Bring your order confirmation to check in at "
            "the door.",
        ),
        (
            "Can I attend if I missed a previous session?",
            "Yes. Each meetup stands on its own, so you can join at any "
            "session.",
        ),
        (
            "Can I bring guests?",
            "You can register more than one ticket in a single order, up "
            "to the per-order limit shown at checkout.",
        ),
        (
            "Are children allowed?",
            "This meetup is open to all ages, though the discussion is "
            "aimed at adults.",
        ),
    ),
}

TASK_372_DESCRIPTION = (
    "Weekly paper reading group focusing on recent ML research. This week: "
    "attention mechanisms and transformer architectures. All levels welcome."
)

SEED_ORGANIZER_DRAFT = (
    "draft:task-372:ml-paper-reading-group",
    PRIMARY_ACCOUNT_SLUG,
    1,
    "ML Paper Reading Group",
    "2026-04-15 18:00",
    "Online (Zoom)",
    TASK_372_DESCRIPTION,
)


# -- Discovery taxonomy ---------------------------------------------------
# Places are a tree: every city hangs off a metro, so one relation gives
# both "nearby cities" (siblings) and the fallback a thin city needs to
# show inventory instead of an empty page. City rosters and their order
# come from the captured directory pages.

_STATE_TIMEZONES = {
    "CA": "America/Los_Angeles",
    "WA": "America/Los_Angeles",
    "AZ": "America/Phoenix",
    "CO": "America/Denver",
    "TX": "America/Chicago",
    "IL": "America/Chicago",
    "TN": "America/Chicago",
    "IN": "America/New_York",
    "MI": "America/New_York",
    "NY": "America/New_York",
    "NJ": "America/New_York",
    "CT": "America/New_York",
    "MA": "America/New_York",
    "PA": "America/New_York",
    "DE": "America/New_York",
    "NC": "America/New_York",
    "MD": "America/New_York",
}

# The root of the place tree. Every metro and every standalone city hangs
# off it, so a city with no inventory of its own still has somewhere to
# fall back to instead of rendering an empty page.
NATIONAL_PLACE = "region--united-states"

# (metro slug, metro label, timezone)
SEED_METROS = (
    ("metro--bay-area", "Bay Area", "America/Los_Angeles"),
    ("metro--southern-california", "Southern California", "America/Los_Angeles"),
    ("metro--tri-state", "New York Tri-State", "America/New_York"),
)

# (label, state, metro slug or "") in the order the captured pages list them.
_PLACE_ROWS = (
    ("San Francisco", "CA", "metro--bay-area"),
    ("San Jose", "CA", "metro--bay-area"),
    ("Sacramento", "CA", "metro--bay-area"),
    ("Oakland", "CA", "metro--bay-area"),
    ("Santa Rosa", "CA", "metro--bay-area"),
    ("Elk Grove", "CA", "metro--bay-area"),
    ("Berkeley", "CA", "metro--bay-area"),
    ("Roseville", "CA", "metro--bay-area"),
    ("El Dorado Hills", "CA", "metro--bay-area"),
    ("Concord", "CA", "metro--bay-area"),
    ("Napa", "CA", "metro--bay-area"),
    ("Santa Clara", "CA", "metro--bay-area"),
    ("Palo Alto", "CA", "metro--bay-area"),
    ("Sausalito", "CA", "metro--bay-area"),
    ("Daly City", "CA", "metro--bay-area"),
    ("Los Angeles", "CA", "metro--southern-california"),
    ("San Diego", "CA", "metro--southern-california"),
    ("Santa Ana", "CA", "metro--southern-california"),
    ("Long Beach", "CA", "metro--southern-california"),
    ("Commerce", "CA", "metro--southern-california"),
    ("Riverside", "CA", "metro--southern-california"),
    ("Ontario", "CA", "metro--southern-california"),
    ("Pasadena", "CA", "metro--southern-california"),
    ("Palm Springs", "CA", "metro--southern-california"),
    ("Santa Monica", "CA", "metro--southern-california"),
    ("Santa Clarita", "CA", "metro--southern-california"),
    ("Irvine", "CA", "metro--southern-california"),
    ("Bakersfield", "CA", "metro--southern-california"),
    ("Anaheim", "CA", "metro--southern-california"),
    ("New York", "NY", "metro--tri-state"),
    ("Brooklyn", "NY", "metro--tri-state"),
    ("Philadelphia", "PA", "metro--tri-state"),
    ("Jersey City", "NJ", "metro--tri-state"),
    ("Albany", "NY", "metro--tri-state"),
    ("Hartford", "CT", "metro--tri-state"),
    ("New Haven", "CT", "metro--tri-state"),
    ("Newark", "NJ", "metro--tri-state"),
    ("Bridgeport", "CT", "metro--tri-state"),
    ("Springfield", "MA", "metro--tri-state"),
    ("Wilmington", "DE", "metro--tri-state"),
    ("Upper Montclair", "NJ", "metro--tri-state"),
    ("Yonkers", "NY", "metro--tri-state"),
    ("Danbury", "CT", "metro--tri-state"),
    ("Austin", "TX", ""),
    ("Abilene", "TX", ""),
    ("San Antonio", "TX", ""),
    ("Dallas", "TX", ""),
    ("Chicago", "IL", ""),
    ("Denver", "CO", ""),
    ("Seattle", "WA", ""),
    ("Phoenix", "AZ", ""),
    ("Detroit", "MI", ""),
    ("Raleigh", "NC", ""),
    ("Baltimore", "MD", ""),
    ("Nashville", "TN", ""),
    ("Indianapolis", "IN", ""),
)

# (slug, label, icon, rank) -- the home page's own category rail.
SEED_CATEGORIES = (
    ("music", "Music", "♬", 0),
    ("nightlife", "Nightlife", "◉", 1),
    ("arts", "Performing & Visual Arts", "◒", 2),
    ("holidays", "Holidays", "▧", 3),
    ("dating", "Dating", "♡", 4),
    ("hobbies", "Hobbies", "⌘", 5),
    ("business", "Business", "▣", 6),
    ("food-drink", "Food & Drink", "♨", 7),
    ("health", "Health", "✚", 8),
    ("other", "Other", "○", 9),
)

# Ordinary English keywords, matched at seed time. Nothing here names an
# event: the same table classifies any title the catalog ever grows.
_CATEGORY_KEYWORDS = (
    ("music", ("dj ", "afrobeats", "vinyl", "cumbia", "r&b", "music", "band",
               "concert", "sade", "album", "rodeo", "hilson", "spalding")),
    ("nightlife", ("night", "party", "rooftop", "club", "lounge", "mixer",
                   "day party", "bar")),
    ("arts", ("art", "gallery", "museum", "exhibit", "theatre", "theater",
              "reception", "typefounding", "acting", "shadows", "ball")),
    ("food-drink", ("food", "taste", "coffee", "juice", "swap meet",
                    "festival", "brunch", "dinner", "cumbia con")),
    ("business", ("job fair", "career", "conference", "networking", "summit",
                  "wealth", "pitch", "hackathon", "qualifier", "training",
                  "wholesale", "fabric show")),
    ("health", ("yoga", "pilates", "hiit", "wellness", "health", "fitness",
                "walk", "run club", "5k", "mental")),
    ("hobbies", ("class", "workshop", "reading", "lecture", "swap", "crawl",
                 "clothing swap", "book")),
    ("dating", ("singles", "dating", "speed dating")),
    ("holidays", ("holiday", "memorial day", "cinco de mayo", "new year")),
)

# (place slug, label) -- captured from each directory's filter sidebar.
SEED_NEIGHBORHOODS = (
    ("ca--san-francisco", "South Beach"),
    ("ca--san-francisco", "Soma"),
    ("ca--san-francisco", "Mission Bay"),
    ("ca--san-francisco", "Inner Mission"),
    ("ny--new-york", "Manhattan"),
    ("ny--new-york", "Brooklyn"),
    ("ny--new-york", "Queens"),
    ("ny--new-york", "The Bronx"),
)

# Captured "Trends in <city>" lists, in rank order. The real New York list
# carried one spam entry at rank 5; it is dropped rather than reproduced.
SEED_PLACE_TRENDS = {
    "ca--san-francisco": (
        "Memorial day weekend events", "May events", "Bay area",
        "Cinco de mayo", "Mothers day", "Live music", "Events june",
        "Rave events", "Hackathon", "Tech", "Dj events",
        "Artificial intelligence",
    ),
    "ny--new-york": (
        "Memorial day weekend", "Mothers day", "Job fairs", "May",
        "Brooklyn", "Cinco de mayo", "June", "Dating", "Rave party",
        "Bollywood", "Boat party",
    ),
}

DEFAULT_PLACE = "ca--los-angeles"


def _place_slug(label: str, state: str) -> str:
    return f"{state.lower()}--{_slugify(label)}"


def place_slug_for_city(city: str) -> str:
    """Map a stored city string ("San Francisco, CA") to its place slug."""
    label, _, state = city.rpartition(",")
    return _place_slug(label.strip() or city.strip(), state.strip() or "us")


# The captured Format facet. Same idea as the category table: ordinary
# words, matched at seed time, so the facet genuinely narrows a result set.
_FORMAT_KEYWORDS = (
    ("class", ("class", "workshop", "training", "lesson", "yoga", "pilates",
               "hiit", "reading", "audition")),
    ("conference", ("conference", "summit", "job fair", "career fair",
                    "expo", "show", "fair", "qualifier")),
    ("festival", ("festival", "fest", "block party", "parade", "carnival",
                  "swap meet", "crawl", "market")),
    ("party", ("party", "night", "mixer", "rooftop", "day party", "ball",
               "celebration", "gala", "social")),
)


def _classify_category(title: str, venue: str) -> str:
    haystack = f"{title} {venue}".casefold()
    for slug, keywords in _CATEGORY_KEYWORDS:
        if any(word in haystack for word in keywords):
            return slug
    return "other"


def _classify_format(title: str, venue: str) -> str:
    haystack = f"{title} {venue}".casefold()
    for slug, keywords in _FORMAT_KEYWORDS:
        if any(word in haystack for word in keywords):
            return slug
    return "other"


def seed_places() -> tuple[tuple, ...]:
    """(slug, label, directory_label, breadcrumb, kind, parent, tz, rank)."""
    rows = [
        (
            NATIONAL_PLACE,
            "United States",
            "United States",
            "United States",
            "region",
            None,
            "America/New_York",
            0,
        )
    ]
    rows += [
        (slug, label, label, label, "metro", NATIONAL_PLACE, tz, index)
        for index, (slug, label, tz) in enumerate(SEED_METROS)
    ]
    for index, (label, state, metro) in enumerate(_PLACE_ROWS):
        rows.append(
            (
                _place_slug(label, state),
                label,
                f"{label}, {state}",
                label,
                "city",
                metro or NATIONAL_PLACE,
                _STATE_TIMEZONES[state],
                index,
            )
        )
    return tuple(rows)


# -- Listing catalog ------------------------------------------------------
# Every card the home page and the city directories paint is an ordinary
# catalog row: a real event with one occurrence and one free ticket class.
# Rows are DERIVED from the frozen card copy (title, date label, city,
# venue) rather than hand-written, so a listing and its detail page cannot
# drift apart and no card is a dead end. Callers register their cards with
# register_listing_events(); seed() then owns them like any other row.

# Every derived occurrence lands in summer 2026, so a fixed daylight-time
# offset per zone is exact here and keeps the seed free of a tz database.
_LISTING_UTC_OFFSETS = {
    "America/Los_Angeles": timedelta(hours=-7),
    "America/Denver": timedelta(hours=-6),
    "America/Chicago": timedelta(hours=-5),
    "America/New_York": timedelta(hours=-4),
}
_LISTING_TZ_LABELS = {
    "America/Los_Angeles": "PDT",
    "America/Denver": "MDT",
    "America/Chicago": "CDT",
    "America/New_York": "EDT",
}
_WEEKDAY_INDEX = {
    "monday": 0,
    "tuesday": 1,
    "wednesday": 2,
    "thursday": 3,
    "friday": 4,
    "saturday": 5,
    "sunday": 6,
}
_MONTH_INDEX = {
    "jan": 1,
    "feb": 2,
    "mar": 3,
    "apr": 4,
    "may": 5,
    "jun": 6,
    "jul": 7,
    "aug": 8,
    "sep": 9,
    "oct": 10,
    "nov": 11,
    "dec": 12,
}
_LISTING_DURATION = timedelta(hours=2)
_LISTING_DEFAULT_HOUR = 19
# Cards whose frozen copy carries no date ("This week", "Sales end soon")
# resolve to a fixed near-future day so their status stays deterministic.
_LISTING_UNDATED_OFFSET = timedelta(days=7)


class ListingEntry(NamedTuple):
    """One frozen listing card, as published by the frontend."""

    title: str
    when: str
    city: str
    venue: str
    timezone: str
    hero: str
    price_cents: int = 0
    badge: str = ""
    start_at: str = ""
    end_at: str = ""
    detail_label: str = ""
    detail_hero: str = ""
    organizer: str = ""
    avatar: str = ""
    followers: int = 0
    hosting_since: str = ""


def _listing_digest(title: str, city: str) -> str:
    key = f"{title.strip().casefold()}|{city.strip().casefold()}"
    return hashlib.sha256(key.encode("utf-8")).hexdigest()


def listing_event_id_for(title: str, city: str) -> str:
    return f"listing-evt-{_listing_digest(title, city)[:12]}"


def _slugify(text: str) -> str:
    return re.sub(r"[^a-z0-9]+", "-", text.casefold()).strip("-")[:72].strip(
        "-"
    ) or "event"


def listing_slug_for(title: str, city: str) -> str:
    """Eventbrite-shaped public slug, stable for a given title and city."""
    serial = int(_listing_digest(title, city)[:12], 16) % 10_000_000_000
    return f"{_slugify(title)}-tickets-{serial:010d}"


def _listing_date(text: str) -> date:
    """Resolve a card's date label against the frozen clock."""
    cleaned = text.strip().rstrip(",").casefold()
    if cleaned == "today":
        return FROZEN_TODAY
    if cleaned == "tomorrow":
        return FROZEN_TODAY + timedelta(days=1)
    if cleaned in _WEEKDAY_INDEX:
        ahead = (_WEEKDAY_INDEX[cleaned] - FROZEN_TODAY.weekday()) % 7 or 7
        return FROZEN_TODAY + timedelta(days=ahead)
    match = re.search(r"([a-z]{3})[a-z]*\.?\s+(\d{1,2})\b", cleaned)
    if match is not None and match.group(1) in _MONTH_INDEX:
        month = _MONTH_INDEX[match.group(1)]
        day = int(match.group(2))
        candidate = date(FROZEN_TODAY.year, month, day)
        if candidate < FROZEN_TODAY:
            candidate = date(FROZEN_TODAY.year + 1, month, day)
        return candidate
    return FROZEN_TODAY + _LISTING_UNDATED_OFFSET


def _listing_time(text: str) -> tuple[int, int] | None:
    match = re.match(r"(\d{1,2}):(\d{2})\s*(am|pm)", text.strip().casefold())
    if match is None:
        return None
    hour = int(match.group(1)) % 12
    if match.group(3) == "pm":
        hour += 12
    return hour, int(match.group(2))


def _clock_label(moment: datetime, meridiem: bool) -> str:
    label = f"{moment.hour % 12 or 12}:{moment.minute:02d}"
    return f"{label} {'AM' if moment.hour < 12 else 'PM'}" if meridiem else label


def _listing_label(start: datetime, end: datetime, tz_name: str) -> str:
    same_half = (start.hour < 12) == (end.hour < 12)
    return (
        f"{start.strftime('%A, %B')} {start.day}, {start.year} \u00b7 "
        f"{_clock_label(start, not same_half)} - {_clock_label(end, True)} "
        f"{_LISTING_TZ_LABELS[tz_name]}"
    )


def _listing_window(when: str, tz_name: str) -> tuple[datetime, datetime, str]:
    parts = [part.strip() for part in when.split("\u2022")]
    day = _listing_date(parts[0])
    hour, minute = (
        _listing_time(parts[1])
        if len(parts) > 1 and _listing_time(parts[1]) is not None
        else (_LISTING_DEFAULT_HOUR, 0)
    )
    tz = timezone(_LISTING_UTC_OFFSETS[tz_name])
    start = datetime(day.year, day.month, day.day, hour, minute, tzinfo=tz)
    end = start + _LISTING_DURATION
    return start, end, _listing_label(start, end, tz_name)


def _listing_overview(
    title: str, venue: str, city: str, price_cents: int
) -> str:
    admission = (
        "Admission is free"
        if price_cents == 0
        else f"Tickets start at ${price_cents / 100:.2f}"
    )
    return (
        f"{title} is hosted at {venue} in {city}. {admission} and "
        "every spot is confirmed here \u2014 register for the date listed "
        "above and bring your confirmation to check in at the door."
    )


def _listing_organizer_name(venue: str, city: str) -> str:
    """Who is hosting a listing.

    A named venue genuinely hosts its own small events, so it becomes the
    organizer. A bare street address does not host anything, so those fall
    to the city's community programme rather than printing an address
    where a person's name belongs.
    """
    name = venue.strip()
    looks_like_an_address = bool(re.match(r"^\d", name)) or bool(
        re.search(r"\b(st|ave|blvd|rd|road|street|avenue|plaza)\b", name.casefold())
    )
    if not name or looks_like_an_address:
        return f"{city.split(',')[0].strip()} Community Events"
    return name


LISTING_ORGANIZERS: dict[str, str] = {}
LISTING_ORGANIZER_PROFILES: dict[str, tuple[int, str]] = {}
LISTING_EVENTS: dict[str, tuple] = {}
LISTING_OCCURRENCES: dict[str, tuple] = {}
# (place_slug, event_id, rank, badge) -- one row per card slot. A feed is
# an ordered list of slots, not a set: the real home page lists the same
# event at two ranks with two different urgency badges.
LISTING_PLACEMENTS: list[tuple[str, str, int, str]] = []
# A placement may use a different captured crop/artwork for the same event.
# This is presentation evidence, not a second business identity.
LISTING_PLACEMENT_HERO: dict[tuple[str, str, int], str] = {}


def register_listing_events(
    entries: Iterable[ListingEntry], *, place_slug: str
) -> None:
    """Promote frozen listing copy into real catalog rows and feed slots.

    The catalog row is idempotent per (title, city) -- a card repeated
    across pages is one event with one detail page -- but every card gets
    its own placement, so a feed can legitimately show it twice.
    """
    reserved_ranks = {
        reserved_rank
        for reserved_place, _event_id, reserved_rank, _badge in SEED_PLACEMENTS
        if reserved_place == place_slug
    }
    for rank, entry in enumerate(entries):
        placement_rank = rank
        for reserved_rank in sorted(reserved_ranks):
            if placement_rank >= reserved_rank:
                placement_rank += 1
        event_id = listing_event_id_for(entry.title, entry.city)
        LISTING_PLACEMENTS.append(
            (place_slug, event_id, placement_rank, entry.badge)
        )
        LISTING_PLACEMENT_HERO[
            (place_slug, event_id, placement_rank)
        ] = entry.hero
        if event_id in LISTING_EVENTS:
            continue
        digest = _listing_digest(entry.title, entry.city)
        organizer_name = entry.organizer or _listing_organizer_name(
            entry.venue, entry.city
        )
        organizer_id = "org-listing-" + hashlib.sha256(
            organizer_name.casefold().encode("utf-8")
        ).hexdigest()[:10]
        LISTING_ORGANIZERS[organizer_id] = organizer_name
        if entry.followers or entry.hosting_since:
            LISTING_ORGANIZER_PROFILES[organizer_id] = (
                entry.followers,
                entry.hosting_since,
            )
        if entry.start_at:
            start = datetime.fromisoformat(entry.start_at)
            end = (
                datetime.fromisoformat(entry.end_at)
                if entry.end_at
                else start + _LISTING_DURATION
            )
            label = entry.detail_label or _listing_label(
                start, end, entry.timezone
            )
        else:
            start, end, label = _listing_window(entry.when, entry.timezone)
        LISTING_EVENTS[event_id] = (
            event_id,
            listing_slug_for(entry.title, entry.city),
            entry.title,
            organizer_id,
            entry.venue,
            f"{entry.venue}, {entry.city}",
            entry.city,
            entry.timezone,
            0,
            None,
            entry.detail_hero or entry.hero,
            entry.detail_hero or entry.hero,
            entry.avatar or None,
            None,
            _listing_overview(
                entry.title, entry.venue, entry.city, entry.price_cents
            ),
            _classify_category(entry.title, entry.venue),
        )
        occurrence_id = f"{event_id}-occ"
        LISTING_OCCURRENCES[occurrence_id] = (
            occurrence_id,
            event_id,
            start.isoformat(),
            end.isoformat(),
            label,
            20 + int(digest[12:16], 16) % 41,
            2 + int(digest[16:18], 16) % 3,
            datetime(
                2026, 1, 1, tzinfo=timezone(_LISTING_UTC_OFFSETS[entry.timezone])
            ).isoformat(),
            start.isoformat(),
            entry.price_cents,
            # 15%-90% of the house already sold, spread deterministically
            # so availability, urgency badges and "spots remaining" differ
            # per listing the way a real catalog's do.
            (15 + int(digest[18:20], 16) % 76),
        )


def ensure_frozen_listing_events_registered() -> None:
    """Load the complete frozen discovery catalog exactly once.

    Runtime lifecycle tools import this module without importing ``app``.
    The fixture module is therefore backend-owned and deliberately free of
    FastAPI or process-global application state.
    """

    if LISTING_PLACEMENTS:
        return
    from backend.listing_fixtures import listing_entries

    for place_slug, entries in listing_entries(ListingEntry):
        register_listing_events(entries, place_slug=place_slug)


def listing_slugs_by_title(city: str, titles: Iterable[str]) -> dict[str, str]:
    """Slug lookup for the frontend, keyed by the frozen card title."""
    return {title: listing_slug_for(title, city) for title in titles}


DEFAULT_PER_PAGE = 18


class EventQuery(NamedTuple):
    """Everything a browse, search or category page can ask the catalog."""

    place: str
    price: str = ""
    keyword: str = ""
    q: str = ""
    categories: tuple[str, ...] = ()
    neighborhoods: tuple[str, ...] = ()
    formats: tuple[str, ...] = ()
    languages: tuple[str, ...] = ()
    currency: str = ""
    start_date: date | None = None
    end_date: date | None = None
    follows_only: bool = False
    account_id: int | None = None
    page: int = 1
    per_page: int = DEFAULT_PER_PAGE
    sort: str = "recommended"
    # A curated rail keeps repeated slots; a directory lists each event once.
    dedupe: bool = True

    @property
    def is_narrowed(self) -> bool:
        """True once the visitor has narrowed the query themselves.

        A thin place may be widened to its parent, but a filter the
        visitor applied must never be: widening it would make applying a
        filter look like it ADDED results.
        """
        return bool(
            self.q
            or self.categories
            or self.formats
            or self.languages
            or self.neighborhoods
            or self.currency
            or self.start_date
            or self.end_date
            or self.follows_only
        )


class SearchResult(NamedTuple):
    events: list[dict]
    badges: list[str]
    total: int
    page: int
    page_count: int
    broadened_to: dict | None = None
    dropped_keyword: bool = False


# Draft fields the builder autosave may write. Everything else on the row
# (version, status, published_event_id, updated_seq) is server-owned.
BUILDER_UPDATABLE_FIELDS = frozenset({
    "title", "summary", "overview", "start_at", "end_at", "timezone",
    "location_type", "venue_name", "venue_address", "venue_city",
    "online_platform", "organizer_name", "image_ref", "category_slug",
})
BUILDER_TICKET_FIELDS = frozenset({
    "name", "kind", "price_cents", "quantity", "per_order_max",
    "sales_start_at", "sales_end_at", "rank",
})
BUILDER_FIELD_LIMITS = {
    "title": 75,
    "summary": 140,
    "overview": 10_000,
    "start_at": 40,
    "end_at": 40,
    "timezone": 64,
    "location_type": 16,
    "venue_name": 200,
    "venue_address": 300,
    "venue_city": 120,
    "online_platform": 100,
    "organizer_name": 100,
    "image_ref": 255,
    "category_slug": 100,
}
BUILDER_ALLOWED_TIMEZONES = frozenset({
    "America/Los_Angeles",
    "America/Denver",
    "America/Chicago",
    "America/New_York",
})


class SoldOut(Exception):
    """Raised when a transactional order insert would oversell capacity."""


class StaleVersion(Exception):
    """Raised when a server-owned entity version no longer matches."""


class CommandConflict(Exception):
    """Raised when an idempotency key is reused with a different payload."""


SALES_CLOSING_SOON = timedelta(hours=72)


def _duration_label(occ: dict | None) -> str:
    if occ is None:
        return ""
    minutes = int((occ["end_at"] - occ["start_at"]).total_seconds() // 60)
    if minutes <= 0:
        return ""
    hours, rest = divmod(minutes, 60)
    if hours and rest:
        return f"{hours}h {rest}m"
    return f"{hours}h" if hours else f"{rest}m"


def urgency_signal(
    occ: dict, remaining: int, now: datetime | None = None
) -> str:
    """The badge a card carries, derived from the event's own numbers.

    The source computes these server-side too (/e/api/<id>/urgency-signals),
    so a card that says "Almost full" is making a checkable claim: register
    enough tickets and the badge changes.
    """
    moment = now or FROZEN_NOW
    capacity = max(1, int(occ["capacity"]))
    share = remaining / capacity
    if remaining <= 0:
        return "Sold out"
    if share <= 0.10:
        return "Almost full"
    if share <= 0.30:
        return "Going fast"
    if occ["sales_end_at"] - moment <= SALES_CLOSING_SOON:
        return "Sales end soon"
    return ""


def occurrence_status(occ: dict, now: datetime | None = None) -> str:
    """Derive upcoming / on-sale / sales-ended / event-ended from data
    plus the frozen clock. Never branches on identity."""
    moment = now or FROZEN_NOW
    if occ["end_at"] < moment:
        return "event-ended"
    if moment < occ["sales_start_at"]:
        return "upcoming"
    if occ["sales_end_at"] < moment:
        return "sales-ended"
    return "on-sale"


def _execute_statements(
    connection: sqlite3.Connection, script: str
) -> None:
    """Execute migration SQL without taking over the caller's transaction."""

    statement = ""
    for line in script.splitlines(keepends=True):
        statement += line
        if sqlite3.complete_statement(statement):
            connection.execute(statement)
            statement = ""
    if statement.strip():
        raise RuntimeError("business migration contains incomplete SQL")


def apply_site_backend_migrations(connection: sqlite3.Connection) -> None:
    """Apply the Eventbrite business schema through the WebsiteBench seam."""

    if not connection.in_transaction:
        raise RuntimeError("site-backend migration hook requires a transaction")
    connection.execute(
        "CREATE TABLE IF NOT EXISTS schema_migrations ("
        "version INTEGER PRIMARY KEY, name TEXT NOT NULL, "
        "applied_at TEXT NOT NULL)"
    )
    applied = {
        int(row[0])
        for row in connection.execute(
            "SELECT version FROM schema_migrations"
        ).fetchall()
    }
    for migration in MIGRATIONS:
        if migration.version in applied:
            continue
        _execute_statements(connection, migration.sql)
        connection.execute(
            "INSERT INTO schema_migrations(version,name,applied_at) "
            "VALUES (?,?,?)",
            (migration.version, migration.name, FROZEN_CLOCK),
        )


def apply_site_backend_migrations_v8(
    connection: sqlite3.Connection,
) -> None:
    """Versioned runtime hook that advances already-bound v7 databases.

    WebsiteBench records a declared site hook exactly once.  Changing the
    declaration when the business migration head advances is therefore the
    durable signal that an existing canonical database must run the
    idempotent forward-migration loop again.
    """

    apply_site_backend_migrations(connection)


def apply_site_backend_migrations_v9(
    connection: sqlite3.Connection,
) -> None:
    """Advance an already-bound Eventbrite database through business v9."""

    apply_site_backend_migrations(connection)


def seed_site_backend(connection: sqlite3.Connection) -> None:
    """Seed the complete deterministic catalog in the caller transaction."""

    if not connection.in_transaction:
        raise RuntimeError("site-backend seed hook requires a transaction")
    ensure_frozen_listing_events_registered()
    Database(Path.cwd()).seed(connection=connection, commit=False)


class Database:
    """One SQLite database bound to a data directory."""

    def __init__(self, data_dir: Path) -> None:
        self.data_dir = Path(data_dir)
        self.path = self.data_dir / DB_FILENAME
        self._conn: sqlite3.Connection | None = None
        self._lock = threading.RLock()

    # -- connection & schema ------------------------------------------------

    def connect(self) -> sqlite3.Connection:
        with self._lock:
            if self._conn is None:
                self.data_dir.mkdir(parents=True, exist_ok=True)
                conn = sqlite3.connect(
                    str(self.path),
                    check_same_thread=False,
                    isolation_level=None,  # autocommit; orders use BEGIN IMMEDIATE
                )
                conn.row_factory = sqlite3.Row
                conn.execute("PRAGMA journal_mode=WAL")
                conn.execute("PRAGMA foreign_keys=ON")
                self._conn = conn
            return self._conn

    def close(self) -> None:
        with self._lock:
            if self._conn is not None:
                self._conn.close()
                self._conn = None

    def prepare(self) -> None:
        with self._lock:
            self.migrate()
            self.seed()

    def _ensure_migrations_table(self, conn: sqlite3.Connection) -> None:
        conn.execute(
            "CREATE TABLE IF NOT EXISTS schema_migrations ("
            "version INTEGER PRIMARY KEY, "
            "name TEXT NOT NULL, "
            "applied_at TEXT NOT NULL)"
        )

    def migration_head(self) -> int:
        with self._lock:
            conn = self.connect()
            self._ensure_migrations_table(conn)
            row = conn.execute(
                "SELECT COALESCE(MAX(version), 0) AS head "
                "FROM schema_migrations"
            ).fetchone()
            return int(row["head"])

    def migrate(self) -> int:
        with self._lock:
            conn = self.connect()
            self._ensure_migrations_table(conn)
            head = self.migration_head()
            for migration in MIGRATIONS:
                if migration.version <= head:
                    continue
                conn.executescript(migration.sql)
                conn.execute(
                    "INSERT INTO schema_migrations "
                    "(version, name, applied_at) VALUES (?, ?, ?)",
                    (migration.version, migration.name, FROZEN_CLOCK),
                )
                head = migration.version
            conn.execute(f"PRAGMA user_version = {head}")
            conn.commit()
            return head

    def seed(
        self,
        *,
        connection: sqlite3.Connection | None = None,
        commit: bool = True,
    ) -> None:
        with self._lock:
            ensure_frozen_listing_events_registered()
            conn = connection if connection is not None else self.connect()
            for slug, label, directory_label, breadcrumb, kind, parent, tz, rank in (
                seed_places()
            ):
                conn.execute(
                    "INSERT INTO places (slug, label, "
                    "directory_label, breadcrumb, kind, parent_slug, "
                    "timezone, rank) VALUES (?, ?, ?, ?, ?, ?, ?, ?) "
                    "ON CONFLICT(slug) DO UPDATE SET "
                    "label=excluded.label, "
                    "directory_label=excluded.directory_label, "
                    "breadcrumb=excluded.breadcrumb, kind=excluded.kind, "
                    "parent_slug=excluded.parent_slug, "
                    "timezone=excluded.timezone, rank=excluded.rank",
                    (
                        slug,
                        label,
                        directory_label,
                        breadcrumb,
                        kind,
                        parent,
                        tz,
                        rank,
                    ),
                )
            for category_slug, label, icon, rank in SEED_CATEGORIES:
                conn.execute(
                    "INSERT OR IGNORE INTO categories (slug, label, icon, "
                    "rank) VALUES (?, ?, ?, ?)",
                    (category_slug, label, icon, rank),
                )
            for rank, (place_slug, label) in enumerate(SEED_NEIGHBORHOODS):
                conn.execute(
                    "INSERT OR IGNORE INTO neighborhoods (slug, place_slug, "
                    "label, rank) VALUES (?, ?, ?, ?)",
                    (
                        f"{place_slug}--{_slugify(label)}",
                        place_slug,
                        label,
                        rank,
                    ),
                )
            for place_slug, labels in SEED_PLACE_TRENDS.items():
                for rank, label in enumerate(labels):
                    conn.execute(
                        "INSERT OR IGNORE INTO place_trends (place_slug, "
                        "rank, label) VALUES (?, ?, ?)",
                        (place_slug, rank, label),
                    )
            # A venue that has been hosting for years has a following;
            # seeding it from the organizer's own name keeps the number
            # stable across resets without inventing a fixture list.
            listed = (
                (
                    org_id,
                    name,
                    LISTING_ORGANIZER_PROFILES.get(org_id, (0, ""))[0]
                    or 12
                    + int(hashlib.sha256(name.encode()).hexdigest()[:4], 16)
                    % 900,
                    LISTING_ORGANIZER_PROFILES.get(org_id, (0, ""))[1]
                    or f"{2012 + int(hashlib.sha256(name.encode()).hexdigest()[4:6], 16) % 12}-01-01",
                )
                for org_id, name in LISTING_ORGANIZERS.items()
            )
            for organizer_id, name, followers, since in (
                *SEED_ORGANIZERS,
                *listed,
            ):
                conn.execute(
                    "INSERT OR IGNORE INTO organizers "
                    "(id, name, slug, follower_count, hosting_since) "
                    "VALUES (?, ?, ?, ?, ?)",
                    (
                        organizer_id,
                        name,
                        _slugify(name) or organizer_id,
                        followers,
                        since,
                    ),
                )
            for account_id, slug, display_name, email, role in SEED_ACCOUNTS:
                conn.execute(
                    "INSERT OR IGNORE INTO accounts "
                    "(id, slug, display_name, email, role) "
                    "VALUES (?, ?, ?, ?, ?)",
                    (account_id, slug, display_name, email, role),
                )
            # Listing rows classify themselves; fixture rows are classified
            # by the same keyword table so no row escapes the taxonomy.
            for row in (*SEED_EVENTS, *LISTING_EVENTS.values()):
                title, venue = str(row[2]), str(row[4])
                category = (
                    row[15] if len(row) > 15 else _classify_category(title, venue)
                )
                conn.execute(
                    "INSERT OR IGNORE INTO events (id, slug, title, "
                    "organizer_id, venue, address, city, timezone, "
                    "synthetic, recurrence, hero, hero_2x, avatar, "
                    "map_asset, overview, category_slug, format_slug) "
                    "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
                    (*row[:15], category, _classify_format(title, venue)),
                )
            # Listing rows carry a trailing price; the fixture rows omit it
            # and stay free.
            for (
                occ_id,
                event_id,
                start_at,
                end_at,
                label,
                capacity,
                per_order_max,
                sales_start,
                sales_end,
                *priced,
            ) in (*SEED_OCCURRENCES, *LISTING_OCCURRENCES.values()):
                price_cents = int(priced[0]) if priced else 0
                # priced[1] is a percentage of the house already sold.
                sold = (
                    capacity * int(priced[1]) // 100 if len(priced) > 1 else 0
                )
                conn.execute(
                    "INSERT OR IGNORE INTO occurrences "
                    "(id, event_id, start_at, end_at, label) "
                    "VALUES (?, ?, ?, ?, ?)",
                    (occ_id, event_id, start_at, end_at, label),
                )
                exists = conn.execute(
                    "SELECT 1 FROM ticket_classes WHERE occurrence_id = ?",
                    (occ_id,),
                ).fetchone()
                if exists is None:
                    conn.execute(
                        "INSERT INTO ticket_classes (occurrence_id, name, "
                        "price_cents, capacity, per_order_max, "
                        "sales_start_at, sales_end_at, version, "
                        "sold_baseline) "
                        "VALUES (?, ?, ?, ?, ?, ?, ?, 1, ?)",
                        (
                            occ_id,
                            TICKET_CLASS_NAME,
                            price_cents,
                            capacity,
                            per_order_max,
                            sales_start,
                            sales_end,
                            sold,
                        ),
                    )
            for event_id, (age, parking) in SEED_EVENT_DETAILS.items():
                conn.execute(
                    "UPDATE events SET age_restriction = ?, parking = ? "
                    "WHERE id = ?",
                    (age, parking, event_id),
                )
            for event_id, entries in SEED_EVENT_FAQS.items():
                for seq, (question, answer) in enumerate(entries):
                    conn.execute(
                        "INSERT OR IGNORE INTO event_faqs "
                        "(event_id, seq, question, answer) "
                        "VALUES (?, ?, ?, ?)",
                        (event_id, seq, question, answer),
                    )
            # Published slots: the ordered card list each feed paints.
            for place_slug, event_id, rank, badge in (
                *LISTING_PLACEMENTS,
                *SEED_PLACEMENTS,
            ):
                conn.execute(
                    "INSERT OR IGNORE INTO event_placements "
                    "(place_slug, event_id, rank, source, badge) "
                    "VALUES (?, ?, ?, 'publication', ?)",
                    (place_slug, event_id, rank, badge),
                )
            # Geographic membership: every event belongs to the place it
            # physically happens in AND to that place's metro and country,
            # so a city page nobody curated still answers with real
            # inventory instead of an empty result list.
            parent_of = {row[0]: row[5] for row in seed_places()}
            rank = 0
            for row in conn.execute(
                "SELECT id, city FROM events ORDER BY id"
            ).fetchall():
                scope = place_slug_for_city(str(row["city"]))
                while scope:
                    conn.execute(
                        "INSERT OR IGNORE INTO event_placements "
                        "(place_slug, event_id, rank, source, badge) "
                        "VALUES (?, ?, ?, 'geography', '')",
                        (scope, row["id"], rank),
                    )
                    rank += 1
                    scope = parent_of.get(scope)
            conn.execute(
                "INSERT OR IGNORE INTO organizer_events "
                "(id, title, event_date, location, description, owner, "
                "created_at) VALUES (?, ?, ?, ?, ?, ?, ?)",
                SEED_ORGANIZER_EVENT + (FROZEN_CLOCK,),
            )
            inserted_draft = conn.execute(
                "INSERT OR IGNORE INTO organizer_event_drafts "
                "(id, owner, version, title, event_date, location, "
                "description, summary, start_at, end_at, timezone, "
                "location_type, online_platform, organizer_name, overview, "
                "category_slug) VALUES (?,?,?,?,?,?,?, ?,?,?,?,?,?,?,?,?)",
                SEED_ORGANIZER_DRAFT + (
                    "Weekly paper reading group focusing on recent ML research.",
                    "2026-04-15T18:00",
                    "2026-04-15T20:00",
                    "America/New_York",
                    "online",
                    "Zoom",
                    "Alex Green",
                    TASK_372_DESCRIPTION,
                    "science-and-tech",
                ),
            ).rowcount == 1
            if inserted_draft:
                conn.execute(
                    "INSERT INTO draft_ticket_classes "
                    "(draft_id, name, kind, price_cents, quantity, "
                    "per_order_max, sales_start_at, sales_end_at, rank) "
                    "VALUES (?, 'General Admission', 'free', 0, 50, 10, "
                    "'2026-01-01T00:00:00-05:00', "
                    "'2026-04-15T18:00:00-04:00', 0)",
                    (SEED_ORGANIZER_DRAFT[0],),
                )
            if commit:
                conn.commit()
            self._seed_sold_out_order(conn, commit=commit)
            self._seed_organization_workspace(conn, commit=commit)

    def _seed_sold_out_order(
        self, conn: sqlite3.Connection, *, commit: bool = True
    ) -> None:
        reference = order_reference_for(
            SEED_ORDER["event_id"],
            SEED_ORDER["occurrence_id"],
            SEED_ORDER["email"],
        )
        exists = conn.execute(
            "SELECT 1 FROM orders WHERE reference = ?", (reference,)
        ).fetchone()
        if exists is not None:
            return
        account = conn.execute(
            "SELECT id FROM accounts WHERE slug = ?",
            (SEED_ORDER["account_slug"],),
        ).fetchone()
        ticket_class = conn.execute(
            "SELECT id FROM ticket_classes WHERE occurrence_id = ?",
            (SEED_ORDER["occurrence_id"],),
        ).fetchone()
        conn.execute(
            "INSERT INTO orders (reference, account_id, event_id, "
            "occurrence_id, email, first_name, last_name, total_cents, "
            "created_at) VALUES (?, ?, ?, ?, ?, ?, ?, 0, ?)",
            (
                reference,
                account["id"],
                SEED_ORDER["event_id"],
                SEED_ORDER["occurrence_id"],
                SEED_ORDER["email"],
                SEED_ORDER["first_name"],
                SEED_ORDER["last_name"],
                FROZEN_CLOCK,
            ),
        )
        conn.execute(
            "INSERT INTO order_lines (order_reference, ticket_class_id, "
            "quantity, unit_price_cents) VALUES (?, ?, ?, 0)",
            (reference, ticket_class["id"], SEED_ORDER["quantity"]),
        )
        for seq in range(1, SEED_ORDER["quantity"] + 1):
            conn.execute(
                "INSERT INTO registrations (order_reference, "
                "ticket_class_id, seq, first_name, last_name, email) "
                "VALUES (?, ?, ?, ?, ?, ?)",
                (
                    reference,
                    ticket_class["id"],
                    seq,
                    SEED_ORDER["first_name"],
                    SEED_ORDER["last_name"],
                    SEED_ORDER["email"],
                ),
            )
        if commit:
            conn.commit()

    def _seed_organization_workspace(
        self, conn: sqlite3.Connection, *, commit: bool = True
    ) -> None:
        """Seed representative v9 organizer lifecycle states.

        Every row is inserted only when absent.  Opening an existing runtime
        therefore never rewinds user-created campaigns, check-ins, payouts or
        integrations.  A deliberate reset deletes these rows first and gets
        the same deterministic identities back.
        """

        if conn.execute(
            "SELECT 1 FROM sqlite_master WHERE type='table' "
            "AND name='organizations'"
        ).fetchone() is None:
            # A deliberately constructed v7 compatibility runtime invokes the
            # shared seed hook before the current v9 hook is installed. Keep
            # that historical migration exercise readable without fabricating
            # tables ahead of the declared forward migration.
            return

        conn.execute(
            "INSERT OR IGNORE INTO organizations "
            "(id, name, owner_account_id, timezone, currency, "
            "payout_schedule, version, created_at, updated_at) "
            "VALUES ('1','Alex Green Events',1,'America/Los_Angeles',"
            "'USD','monthly',1,?,?)",
            (FROZEN_CLOCK, FROZEN_CLOCK),
        )
        conn.execute(
            "INSERT OR IGNORE INTO memberships "
            "(id, organization_id, account_id, email, role, status, version, "
            "invited_by, created_at, updated_at) "
            "SELECT 'mem-owner-1','1',id,email,'owner','active',1,id,?,? "
            "FROM accounts WHERE id=1",
            (FROZEN_CLOCK, FROZEN_CLOCK),
        )
        for account_id, timezone_name in (
            (1, "America/Los_Angeles"),
            (2, "America/New_York"),
        ):
            conn.execute(
                "INSERT OR IGNORE INTO account_preferences "
                "(account_id, locale, timezone, event_updates, "
                "organizer_updates, version, updated_at) "
                "VALUES (?,'en-US',?,1,1,1,?)",
                (account_id, timezone_name, FROZEN_CLOCK),
            )

        # The frozen organization owns the representative catalog.  Links,
        # rather than a request parameter, are the authority checked by
        # refunds, attendees and reports.
        conn.execute(
            "INSERT OR IGNORE INTO organization_event_links "
            "(organization_id, event_id, created_at) "
            "SELECT '1', id, ? FROM events",
            (FROZEN_CLOCK,),
        )
        conn.execute(
            "INSERT OR IGNORE INTO organization_attendees "
            "(id, organization_id, event_id, order_reference, registration_id, "
            "first_name, last_name, email, check_in_status, version, "
            "created_at, updated_at) "
            "SELECT 'att-' || r.id, '1', o.event_id, r.order_reference, r.id, "
            "r.first_name, r.last_name, r.email, 'not-checked-in', 1, ?, ? "
            "FROM registrations r JOIN orders o ON o.reference=r.order_reference "
            "JOIN organization_event_links l ON l.event_id=o.event_id "
            "AND l.organization_id='1'",
            (FROZEN_CLOCK, FROZEN_CLOCK),
        )
        attendee = conn.execute(
            "SELECT id FROM organization_attendees WHERE organization_id='1' "
            "ORDER BY id LIMIT 1"
        ).fetchone()
        if attendee is not None:
            inserted = conn.execute(
                "INSERT OR IGNORE INTO check_ins "
                "(id, organization_id, attendee_id, operation, status, version, "
                "remote_effect_count, actor_account_id, created_at) "
                "VALUES ('chk-seed-checked-in','1',?,'check-in','checked-in',"
                "1,0,1,?)",
                (attendee["id"], FROZEN_CLOCK),
            ).rowcount
            if inserted:
                conn.execute(
                    "UPDATE organization_attendees SET check_in_status='checked-in', "
                    "version=2, updated_at=? WHERE id=?",
                    (FROZEN_CLOCK, attendee["id"]),
                )

        order = conn.execute(
            "SELECT o.reference, o.total_cents FROM orders o "
            "JOIN organization_event_links l ON l.event_id=o.event_id "
            "WHERE l.organization_id='1' ORDER BY o.reference LIMIT 1"
        ).fetchone()
        if order is not None:
            conn.execute(
                "INSERT OR IGNORE INTO refunds "
                "(id, organization_id, order_reference, amount_cents, currency, "
                "reason, status, payment_adapter, version, remote_effect_count, "
                "created_by, created_at, updated_at) "
                "VALUES ('ref-seed-completed','1',?,?,'USD','Fixture refund',"
                "'completed','local-sandbox',3,0,1,?,?)",
                (
                    order["reference"],
                    int(order["total_cents"]),
                    FROZEN_CLOCK,
                    FROZEN_CLOCK,
                ),
            )

        conn.execute(
            "INSERT OR IGNORE INTO campaigns "
            "(id, organization_id, name, status, budget_cents, scheduled_for, "
            "result_summary, version, remote_effect_count, created_by, "
            "created_at, updated_at) VALUES "
            "('cmp-seed-draft','1','August attendee update','draft',0,'',"
            "'Local draft; nothing has been sent.',1,0,1,?,?),"
            "('cmp-seed-scheduled','1','Launch reminder','scheduled',0,"
            "'2026-08-20T09:00:00-07:00','Local schedule; nothing has been sent.',"
            "2,0,1,?,?)",
            (FROZEN_CLOCK, FROZEN_CLOCK, FROZEN_CLOCK, FROZEN_CLOCK),
        )
        conn.execute(
            "INSERT OR IGNORE INTO ads "
            "(id, organization_id, name, status, budget_cents, scheduled_for, "
            "result_summary, version, remote_effect_count, created_by, "
            "created_at, updated_at) VALUES "
            "('ad-seed-paused','1','Local discovery boost','paused',2500,"
            "'2026-08-18T08:00:00-07:00','Local simulation; no ad was published.',"
            "3,0,1,?,?)",
            (FROZEN_CLOCK, FROZEN_CLOCK),
        )
        gross = int(
            conn.execute(
                "SELECT COALESCE(SUM(o.total_cents),0) AS n FROM orders o "
                "JOIN organization_event_links l ON l.event_id=o.event_id "
                "WHERE l.organization_id='1'"
            ).fetchone()["n"]
        )
        order_count = int(
            conn.execute(
                "SELECT COUNT(*) AS n FROM orders o "
                "JOIN organization_event_links l ON l.event_id=o.event_id "
                "WHERE l.organization_id='1'"
            ).fetchone()["n"]
        )
        attendee_count = int(
            conn.execute(
                "SELECT COUNT(*) AS n FROM organization_attendees "
                "WHERE organization_id='1'"
            ).fetchone()["n"]
        )
        checked_in_count = int(
            conn.execute(
                "SELECT COUNT(*) AS n FROM organization_attendees "
                "WHERE organization_id='1' AND check_in_status='checked-in'"
            ).fetchone()["n"]
        )
        refunded = int(
            conn.execute(
                "SELECT COALESCE(SUM(amount_cents),0) AS n FROM refunds "
                "WHERE organization_id='1' AND status IN ('approved','completed')"
            ).fetchone()["n"]
        )
        conn.execute(
            "INSERT OR IGNORE INTO analytics_snapshots "
            "(id, organization_id, gross_cents, order_count, attendee_count, "
            "checked_in_count, refunded_cents, source, captured_at) "
            "VALUES ('analytics-seed-v9','1',?,?,?,?,?,'local-derived',?)",
            (
                gross,
                order_count,
                attendee_count,
                checked_in_count,
                refunded,
                FROZEN_CLOCK,
            ),
        )
        conn.execute(
            "INSERT OR IGNORE INTO payout_ledger "
            "(id, organization_id, amount_cents, currency, schedule, status, "
            "payment_adapter, version, remote_effect_count, created_by, "
            "created_at, updated_at) VALUES "
            "('pay-seed-scheduled','1',?,'USD','monthly','scheduled',"
            "'local-sandbox',1,0,1,?,?)",
            (max(0, gross - refunded), FROZEN_CLOCK, FROZEN_CLOCK),
        )
        conn.execute(
            "INSERT OR IGNORE INTO integration_connections "
            "(id, organization_id, integration_slug, display_name, status, "
            "connection_mode, version, remote_effect_count, created_by, "
            "created_at, updated_at) VALUES "
            "('int-seed-zoom','1','zoom','Zoom','connected','local-simulation',"
            "1,0,1,?,?)",
            (FROZEN_CLOCK, FROZEN_CLOCK),
        )
        if commit:
            conn.commit()

    def reset_in_transaction(self, conn: sqlite3.Connection) -> None:
        """Reset only Eventbrite-owned rows in a caller transaction."""

        if not conn.in_transaction:
            raise RuntimeError("business reset requires a transaction")
        for table in BUSINESS_TABLES:
            conn.execute(f"DELETE FROM {table}")
        conn.execute(
            "DELETE FROM sqlite_sequence WHERE name IN "
            "('ticket_classes', 'order_lines', 'registrations', "
            "'ticket_order_version_journal', "
            "'organizer_event_version_journal', "
            "'draft_ticket_classes', 'builder_version_journal')"
        )
        self.seed(connection=conn, commit=False)

    def reset(self) -> None:
        """Transactionally reset Eventbrite business rows and reseed."""

        with self._lock:
            conn = self.connect()
            conn.execute("BEGIN IMMEDIATE")
            try:
                self.reset_in_transaction(conn)
                conn.execute("COMMIT")
            except BaseException:
                if conn.in_transaction:
                    conn.execute("ROLLBACK")
                raise

    # -- catalog views --------------------------------------------------------

    def _ticket_class_view(self, row: sqlite3.Row) -> dict:
        return {
            "id": int(row["tc_id"]),
            "name": row["tc_name"],
            "price_cents": int(row["price_cents"]),
            "capacity": int(row["capacity"]),
            "per_order_max": int(row["per_order_max"]),
            "sales_start_at": datetime.fromisoformat(row["sales_start_at"]),
            "sales_end_at": datetime.fromisoformat(row["sales_end_at"]),
            "version": int(row["version"]),
            "rank": int(row["tc_rank"]),
        }

    def _occurrence_view(self, rows: list[sqlite3.Row]) -> dict:
        """One occurrence plus every ticket class on sale for it.

        The lowest-ranked class is the occurrence's default tier. Its
        window and version drive occurrence status and the checkout
        defaults, so the flattened keys below keep single-tier callers
        reading exactly what they read before tiers existed.
        """
        tickets = sorted(
            (self._ticket_class_view(row) for row in rows),
            key=lambda tc: (tc["rank"], tc["price_cents"], tc["id"]),
        )
        head, default = rows[0], tickets[0]
        return {
            "id": head["occ_id"],
            "start": datetime.fromisoformat(head["start_at"]).date(),
            "start_at": datetime.fromisoformat(head["start_at"]),
            "end_at": datetime.fromisoformat(head["end_at"]),
            "label": head["label"],
            "tickets": tickets,
            "capacity": sum(tc["capacity"] for tc in tickets),
            "ticket_class_id": default["id"],
            "ticket_class_name": default["name"],
            "price_cents": default["price_cents"],
            "per_order_max": default["per_order_max"],
            "sales_start_at": default["sales_start_at"],
            "sales_end_at": default["sales_end_at"],
            "version": default["version"],
        }

    def _event_view(self, event_row: sqlite3.Row) -> dict:
        with self._lock:
            conn = self.connect()
            occ_rows = conn.execute(
                "SELECT o.id AS occ_id, o.start_at, o.end_at, o.label, "
                "t.id AS tc_id, t.name AS tc_name, t.price_cents, "
                "t.capacity, t.per_order_max, t.sales_start_at, "
                "t.sales_end_at, t.version, t.rank AS tc_rank "
                "FROM occurrences o "
                "JOIN ticket_classes t ON t.occurrence_id = o.id "
                "WHERE o.event_id = ? "
                "ORDER BY o.start_at, o.id, t.rank, t.id",
                (event_row["id"],),
            ).fetchall()
        grouped: dict[str, list[sqlite3.Row]] = {}
        for row in occ_rows:
            grouped.setdefault(row["occ_id"], []).append(row)
        occurrences = {
            occ_id: self._occurrence_view(rows)
            for occ_id, rows in grouped.items()
        }
        default_id = None
        upcoming = [
            occ
            for occ in occurrences.values()
            if occ["start"] >= FROZEN_TODAY
        ]
        if upcoming:
            default_id = min(upcoming, key=lambda o: (o["start_at"], o["id"]))[
                "id"
            ]
        elif occurrences:
            default_id = max(
                occurrences.values(), key=lambda o: (o["start_at"], o["id"])
            )["id"]
        default_occ = occurrences.get(default_id) if default_id else None
        # "From $X" is the multi-tier form: it means the cheapest of several
        # classes. A single class states its own price outright.
        price_label = "Free"
        if default_occ:
            tiers = default_occ["tickets"]
            cheapest = min(tc["price_cents"] for tc in tiers)
            if len(tiers) > 1:
                price_label = f"From ${cheapest / 100:.2f}"
            elif cheapest > 0:
                price_label = f"${cheapest / 100:.2f}"
        return {
            "id": event_row["id"],
            "slug": event_row["slug"],
            "title": event_row["title"],
            "organizer": event_row["organizer_name"],
            "organizer_id": event_row["organizer_id"],
            # "Good to know" facts. Only what the record actually holds
            # is listed, so the section never asserts something unknown.
            "highlights": [
                text
                for text in (
                    "Online event" if event_row["is_online"] else "In person",
                    _duration_label(default_occ),
                    event_row["age_restriction"],
                    event_row["parking"],
                )
                if text
            ],
            "venue": event_row["venue"],
            "address": event_row["address"],
            "city": event_row["city"],
            "timezone": event_row["timezone"],
            "price_label": price_label,
            "synthetic": bool(event_row["synthetic"]),
            "recurrence": event_row["recurrence"],
            "hero": event_row["hero"],
            "hero_2x": event_row["hero_2x"],
            "avatar": event_row["avatar"],
            "map": event_row["map_asset"],
            "parking": event_row["parking"],
            "overview": event_row["overview"],
            "max_per_order": (
                default_occ["per_order_max"] if default_occ else 1
            ),
            "occurrences": occurrences,
            "default_occurrence": default_id,
        }

    def event_by_id(self, event_id: str) -> dict | None:
        with self._lock:
            row = self.connect().execute(
                "SELECT e.*, g.name AS organizer_name FROM events e "
                "JOIN organizers g ON g.id = e.organizer_id "
                "WHERE e.id = ?",
                (event_id,),
            ).fetchone()
        return self._event_view(row) if row is not None else None

    def event_by_slug(self, slug: str) -> dict | None:
        with self._lock:
            row = self.connect().execute(
                "SELECT e.*, g.name AS organizer_name FROM events e "
                "JOIN organizers g ON g.id = e.organizer_id "
                "WHERE e.slug = ?",
                (slug,),
            ).fetchone()
        return self._event_view(row) if row is not None else None

    # -- discovery ------------------------------------------------------------

    def place(self, slug: str) -> dict | None:
        with self._lock:
            row = self.connect().execute(
                "SELECT * FROM places WHERE slug = ?", (slug,)
            ).fetchone()
        return dict(row) if row is not None else None

    def place_by_label(self, label: str) -> dict | None:
        """Resolve typed text ("new york", "New York, NY") to a place."""
        needle = label.strip().casefold()
        if not needle:
            return None
        with self._lock:
            row = self.connect().execute(
                "SELECT * FROM places WHERE kind = 'city' AND ("
                "lower(label) = ? OR lower(directory_label) = ? OR slug = ?) "
                "ORDER BY rank LIMIT 1",
                (needle, needle, needle),
            ).fetchone()
            if row is None:
                row = self.connect().execute(
                    "SELECT * FROM places WHERE kind = 'city' "
                    "AND lower(label) LIKE ? ORDER BY rank LIMIT 1",
                    (f"{needle}%",),
                ).fetchone()
        return dict(row) if row is not None else None

    def nearby_places(self, slug: str, limit: int = 12) -> list[dict]:
        """Sibling cities under the same metro -- the 'things to do around
        X' roster, which is therefore always correct for the city shown."""
        with self._lock:
            rows = self.connect().execute(
                "SELECT p.* FROM places p "
                "JOIN places self ON self.slug = ? "
                "WHERE p.kind = 'city' AND p.parent_slug IS NOT NULL "
                "AND p.parent_slug = self.parent_slug AND p.slug != self.slug "
                "ORDER BY p.rank LIMIT ?",
                (slug, limit),
            ).fetchall()
        return [dict(row) for row in rows]

    def popular_cities(self, limit: int = 12) -> list[dict]:
        """Cities with their own inventory, busiest first -- so a "popular
        cities" chip always opens a page with events on it."""
        with self._lock:
            rows = self.connect().execute(
                "SELECT p.*, COUNT(DISTINCT ep.event_id) AS listed "
                "FROM places p "
                "JOIN event_placements ep ON ep.place_slug = p.slug "
                "WHERE p.kind = 'city' "
                "GROUP BY p.slug ORDER BY listed DESC, p.rank LIMIT ?",
                (limit,),
            ).fetchall()
        return [dict(row) for row in rows]

    def browsable_places(self) -> list[dict]:
        with self._lock:
            rows = self.connect().execute(
                "SELECT * FROM places WHERE kind = 'city' ORDER BY label"
            ).fetchall()
        return [dict(row) for row in rows]

    def place_trends(self, slug: str) -> list[str]:
        with self._lock:
            rows = self.connect().execute(
                "SELECT label FROM place_trends WHERE place_slug = ? "
                "ORDER BY rank",
                (slug,),
            ).fetchall()
        return [str(row["label"]) for row in rows]

    def neighborhoods(self, slug: str) -> list[dict]:
        with self._lock:
            rows = self.connect().execute(
                "SELECT * FROM neighborhoods WHERE place_slug = ? "
                "ORDER BY rank",
                (slug,),
            ).fetchall()
        return [dict(row) for row in rows]

    def categories(self, limit: int | None = None) -> list[dict]:
        """Browsable categories in display order. The home rail shows the
        first HOME_RAIL_CATEGORIES of them; the filter sidebar shows more."""
        with self._lock:
            rows = self.connect().execute(
                "SELECT * FROM categories WHERE slug != 'other' "
                "ORDER BY rank LIMIT ?",
                (limit if limit is not None else -1,),
            ).fetchall()
        return [dict(row) for row in rows]

    def search_events(self, query: "EventQuery") -> "SearchResult":
        """The one query behind every browse, search and category page.

        Results are ordered by feed rank, so a place that an editor has
        curated paints exactly its curated order, and a place that nobody
        curated still answers from geography instead of 404ing.

        A place with no inventory of its own climbs its parents (city ->
        metro -> country) rather than showing an empty page, and says so.
        An explicit `q` is never broadened: a search that finds nothing has
        to be allowed to say so.
        """
        rows, total = self._matching_events(query)
        placement_scope = query.place
        broadened_to = None
        if not total and not query.is_narrowed:
            scope = query.place
            while not total:
                parent = (self.place(scope) or {}).get("parent_slug")
                if not parent:
                    break
                rows, total = self._matching_events(
                    query._replace(place=parent)
                )
                scope = parent
                if total:
                    broadened_to = self.place(parent)
                    placement_scope = scope
        per_page = max(1, query.per_page)
        page_count = max(1, (total + per_page - 1) // per_page)
        events = [self._event_view(row) for row in rows]
        for event, row in zip(events, rows):
            placement_hero = LISTING_PLACEMENT_HERO.get(
                (placement_scope, str(event["id"]), int(row["rank"]))
            )
            if placement_hero:
                event["hero"] = placement_hero
                event["hero_2x"] = placement_hero
        # A curated slot may carry an editorial badge ("Promoted"); every
        # other badge is derived, so it means what it says.
        badges = []
        for event, row in zip(events, rows):
            occurrence = event["occurrences"].get(event["default_occurrence"])
            if occurrence is None:
                badges.append("")
                continue
            editorial = str(row["badge"]) if "Promoted" in str(row["badge"]) else ""
            badges.append(
                editorial
                or urgency_signal(
                    occurrence,
                    self.remaining_capacity(event["id"], occurrence["id"]),
                )
            )
        return SearchResult(
            events=events,
            badges=badges,
            total=total,
            page=query.page,
            page_count=page_count,
            broadened_to=broadened_to,
        )

    def _matching_events(
        self, query: "EventQuery"
    ) -> tuple[list[sqlite3.Row], int]:
        where = ["1 = 1"]
        params: list[object] = [query.place]
        if query.price == "free":
            where.append("t.price_cents = 0")
        elif query.price == "paid":
            where.append("t.price_cents > 0")
        for column, values in (
            ("e.category_slug", query.categories),
            ("e.format_slug", query.formats),
            ("e.language", query.languages),
        ):
            if values:
                marks = ",".join("?" * len(values))
                where.append(f"{column} IN ({marks})")
                params.extend(values)
        if query.currency:
            where.append("t.currency = ?")
            params.append(query.currency)
        if query.q:
            where.append("(e.title LIKE ? OR e.venue LIKE ? OR e.city LIKE ?)")
            params.extend([f"%{query.q}%"] * 3)
        if query.start_date:
            where.append("date(o.start_at) >= ?")
            params.append(query.start_date.isoformat())
        if query.end_date:
            where.append("date(o.start_at) <= ?")
            params.append(query.end_date.isoformat())
        if query.neighborhoods:
            marks = ",".join("?" * len(query.neighborhoods))
            where.append(
                "EXISTS (SELECT 1 FROM event_neighborhoods en "
                f"WHERE en.event_id = e.id AND en.neighborhood_slug IN ({marks}))"
            )
            params.extend(query.neighborhoods)
        if query.follows_only and query.account_id is not None:
            where.append(
                "EXISTS (SELECT 1 FROM organizer_follows f "
                "WHERE f.organizer_id = e.organizer_id AND f.account_id = ?)"
            )
            params.append(query.account_id)
        # A curated rail is a list of SLOTS: an event placed twice renders
        # twice, which is what the real home page does. A city directory is
        # a list of EVENTS, so it collapses an event's slots to its best
        # one -- curated rank if an editor placed it, geography after.
        if query.dedupe:
            placements = (
                "(SELECT event_id, MAX(badge) AS badge, "
                "MIN(CASE WHEN source = 'publication' "
                "THEN rank ELSE 100000 + rank END) AS rank "
                "FROM event_placements WHERE place_slug = ? "
                "GROUP BY event_id) ep"
            )
        else:
            placements = (
                "(SELECT event_id, badge, rank FROM event_placements "
                "WHERE place_slug = ? AND source = 'publication') ep"
            )
        body = (
            f"FROM {placements} "
            "JOIN events e ON e.id = ep.event_id "
            "JOIN organizers g ON g.id = e.organizer_id "
            "JOIN occurrences o ON o.event_id = e.id "
            "JOIN ticket_classes t ON t.occurrence_id = o.id AND t.rank = 0 "
            f"WHERE {' AND '.join(where)}"
        )
        # An event with several occurrences joins to several rows, so the
        # result set is grouped: a directory collapses to one row per
        # event, a curated rail to one row per slot.
        group = "e.id" if query.dedupe else "ep.rank"
        with self._lock:
            conn = self.connect()
            total = int(
                conn.execute(
                    f"SELECT COUNT(*) AS c FROM (SELECT 1 {body} "
                    f"GROUP BY {group}) counted",
                    params,
                ).fetchone()["c"]
            )
            order_by = {
                "date": "next_start, ep.rank, e.id",
                "price": "min_price, next_start, ep.rank, e.id",
                "price-desc": "min_price DESC, next_start, ep.rank, e.id",
            }.get(query.sort, "ep.rank, next_start, e.id")
            rows = conn.execute(
                "SELECT e.*, g.name AS organizer_name, ep.badge, ep.rank, "
                "MIN(o.start_at) AS next_start, MIN(t.price_cents) AS min_price "
                f"{body} GROUP BY {group} "
                f"ORDER BY {order_by} "
                "LIMIT ? OFFSET ?",
                (*params, query.per_page, (query.page - 1) * query.per_page),
            ).fetchall()
        return list(rows), total

    # -- organizers, saves and follows ----------------------------------------

    def organizer_profile(
        self, *, slug: str = "", organizer_id: str = "", account_id: int | None = None
    ) -> dict | None:
        """An organizer plus the counts its page shows, all derived.

        followers is a stored balance (seeded from the catalog snapshot,
        moved by real follows); everything else is counted live, so the
        numbers cannot drift from the catalog.
        """
        with self._lock:
            conn = self.connect()
            row = conn.execute(
                "SELECT * FROM organizers WHERE slug = ? OR id = ?",
                (slug, organizer_id or slug),
            ).fetchone()
            if row is None:
                return None
            events = int(
                conn.execute(
                    "SELECT COUNT(*) AS c FROM events WHERE organizer_id = ?",
                    (row["id"],),
                ).fetchone()["c"]
            )
            attendees = int(
                conn.execute(
                    "SELECT COALESCE(SUM(l.quantity), 0) AS c "
                    "FROM order_lines l "
                    "JOIN orders o ON o.reference = l.order_reference "
                    "JOIN events e ON e.id = o.event_id "
                    "WHERE e.organizer_id = ?",
                    (row["id"],),
                ).fetchone()["c"]
            )
            following = False
            if account_id is not None:
                following = (
                    conn.execute(
                        "SELECT 1 FROM organizer_follows "
                        "WHERE account_id = ? AND organizer_id = ?",
                        (account_id, row["id"]),
                    ).fetchone()
                    is not None
                )
        since = str(row["hosting_since"] or "")
        years = 0
        if since:
            years = max(0, FROZEN_TODAY.year - date.fromisoformat(since).year)
        return {
            "id": row["id"],
            "name": row["name"],
            "slug": row["slug"],
            "followers": int(row["follower_count"]),
            "events": events,
            "attendees": attendees,
            "hosting_years": years,
            "following": following,
        }

    def set_follow(self, account_id: int, organizer_id: str, follow: bool) -> bool:
        """Follow or unfollow. The follower balance moves with the row, in
        one transaction, so the count on screen is never a guess."""
        with self._lock:
            conn = self.connect()
            conn.execute("BEGIN IMMEDIATE")
            try:
                existing = conn.execute(
                    "SELECT 1 FROM organizer_follows "
                    "WHERE account_id = ? AND organizer_id = ?",
                    (account_id, organizer_id),
                ).fetchone()
                if follow and existing is None:
                    conn.execute(
                        "INSERT INTO organizer_follows "
                        "(account_id, organizer_id, created_at) "
                        "VALUES (?, ?, ?)",
                        (account_id, organizer_id, FROZEN_CLOCK),
                    )
                    conn.execute(
                        "UPDATE organizers SET follower_count = "
                        "follower_count + 1 WHERE id = ?",
                        (organizer_id,),
                    )
                elif not follow and existing is not None:
                    conn.execute(
                        "DELETE FROM organizer_follows "
                        "WHERE account_id = ? AND organizer_id = ?",
                        (account_id, organizer_id),
                    )
                    conn.execute(
                        "UPDATE organizers SET follower_count = "
                        "MAX(0, follower_count - 1) WHERE id = ?",
                        (organizer_id,),
                    )
                conn.execute("COMMIT")
            except Exception:
                conn.execute("ROLLBACK")
                raise
        return follow

    def set_saved(self, account_id: int, event_id: str, saved: bool) -> bool:
        with self._lock:
            conn = self.connect()
            if saved:
                conn.execute(
                    "INSERT OR IGNORE INTO saved_events "
                    "(account_id, event_id, created_at) VALUES (?, ?, ?)",
                    (account_id, event_id, FROZEN_CLOCK),
                )
            else:
                conn.execute(
                    "DELETE FROM saved_events "
                    "WHERE account_id = ? AND event_id = ?",
                    (account_id, event_id),
                )
            conn.commit()
        return saved

    def saved_event_ids(self, account_id: int) -> set[str]:
        with self._lock:
            rows = self.connect().execute(
                "SELECT event_id FROM saved_events WHERE account_id = ?",
                (account_id,),
            ).fetchall()
        return {str(row["event_id"]) for row in rows}

    def event_faqs(self, event_id: str) -> list[dict]:
        with self._lock:
            rows = self.connect().execute(
                "SELECT question, answer FROM event_faqs "
                "WHERE event_id = ? ORDER BY seq",
                (event_id,),
            ).fetchall()
        return [dict(row) for row in rows]

    def events_by_organizer(self, organizer_id: str) -> list[dict]:
        with self._lock:
            rows = self.connect().execute(
                "SELECT e.*, g.name AS organizer_name FROM events e "
                "JOIN organizers g ON g.id = e.organizer_id "
                "WHERE e.organizer_id = ? ORDER BY e.title",
                (organizer_id,),
            ).fetchall()
        return [self._event_view(row) for row in rows]

    def saved_events(self, account_id: int) -> list[dict]:
        with self._lock:
            rows = self.connect().execute(
                "SELECT e.*, g.name AS organizer_name FROM saved_events s "
                "JOIN events e ON e.id = s.event_id "
                "JOIN organizers g ON g.id = e.organizer_id "
                "WHERE s.account_id = ? ORDER BY s.created_at, e.title",
                (account_id,),
            ).fetchall()
        return [self._event_view(row) for row in rows]

    def orders_for_account(self, account_id: int) -> list[dict]:
        with self._lock:
            rows = self.connect().execute(
                "SELECT o.reference, o.created_at, o.total_cents, "
                "e.title, e.slug, c.label AS occurrence_label, "
                "COALESCE(SUM(l.quantity), 0) AS quantity "
                "FROM orders o "
                "JOIN events e ON e.id = o.event_id "
                "JOIN occurrences c ON c.id = o.occurrence_id "
                "LEFT JOIN order_lines l ON l.order_reference = o.reference "
                "WHERE o.account_id = ? "
                "GROUP BY o.reference ORDER BY c.start_at, o.reference",
                (account_id,),
            ).fetchall()
        return [
            {
                "reference": row["reference"],
                "title": row["title"],
                "slug": row["slug"],
                "occurrence_label": row["occurrence_label"],
                "quantity": int(row["quantity"]),
                "total": f"{int(row['total_cents']) / 100:.2f}",
            }
            for row in rows
        ]

    def remaining_capacity(
        self, event_id: str, occurrence_id: str, ticket_class_id: int | None = None
    ) -> int:
        """Seats left on an occurrence, summed across its ticket classes.

        Pass ticket_class_id to scope the count to one tier -- that is the
        number a buyer of that tier is actually competing for.
        """
        with self._lock:
            conn = self.connect()
            rows = conn.execute(
                "SELECT t.id AS tc_id, t.capacity, "
                "t.sold_baseline + COALESCE((SELECT SUM(l.quantity) "
                "FROM order_lines l WHERE l.ticket_class_id = t.id), 0) AS used "
                "FROM ticket_classes t "
                "JOIN occurrences o ON o.id = t.occurrence_id "
                "WHERE o.event_id = ? AND o.id = ?",
                (event_id, occurrence_id),
            ).fetchall()
            if not rows:
                raise ValueError(
                    f"unknown occurrence {occurrence_id!r} "
                    f"for event {event_id!r}"
                )
            if ticket_class_id is not None:
                rows = [r for r in rows if int(r["tc_id"]) == ticket_class_id]
                if not rows:
                    raise ValueError(
                        f"unknown ticket class {ticket_class_id!r} "
                        f"for occurrence {occurrence_id!r}"
                    )
            return sum(int(r["capacity"]) - int(r["used"]) for r in rows)

    def bump_ticket_class_version(
        self, event_id: str, occurrence_id: str
    ) -> int:
        """Simulate an organizer edit: increment the optimistic version."""
        with self._lock:
            conn = self.connect()
            conn.execute(
                "UPDATE ticket_classes SET version = version + 1 "
                "WHERE occurrence_id IN ("
                "SELECT id FROM occurrences WHERE event_id = ? AND id = ?)",
                (event_id, occurrence_id),
            )
            conn.commit()
            row = conn.execute(
                "SELECT version FROM ticket_classes WHERE occurrence_id = ?",
                (occurrence_id,),
            ).fetchone()
            return int(row["version"])

    # -- accounts & sessions --------------------------------------------------

    def account_by_slug(self, slug: str) -> sqlite3.Row | None:
        with self._lock:
            return self.connect().execute(
                "SELECT * FROM accounts WHERE slug = ?", (slug,)
            ).fetchone()

    def create_registered_subject(
        self,
        connection: sqlite3.Connection,
        *,
        subject_id: str,
        email: str,
        display_name: str,
    ) -> str:
        """Create the site business subject inside the auth transaction."""
        normalized_slug = subject_id.strip()
        if not normalized_slug:
            raise ValueError("subject id is required")
        next_id = int(
            connection.execute(
                "SELECT COALESCE(MAX(id), 0) + 1 FROM accounts"
            ).fetchone()[0]
        )
        connection.execute(
            "INSERT INTO accounts(id,slug,display_name,email,role) "
            "VALUES (?,?,?,?, 'attendee')",
            (next_id, normalized_slug, display_name, email),
        )
        return normalized_slug

    def create_session(self, account_slug: str) -> str:
        with self._lock:
            account = self.account_by_slug(account_slug)
            if account is None:
                raise ValueError(f"unknown account: {account_slug}")
            token = uuid.uuid4().hex
            conn = self.connect()
            conn.execute(
                "INSERT INTO sessions (token, account_id, created_at) "
                "VALUES (?, ?, ?)",
                (token, account["id"], FROZEN_CLOCK),
            )
            conn.commit()
            return token

    def session_account(self, token: str) -> sqlite3.Row | None:
        if not token:
            return None
        with self._lock:
            return self.connect().execute(
                "SELECT a.* FROM sessions s "
                "JOIN accounts a ON a.id = s.account_id "
                "WHERE s.token = ?",
                (token,),
            ).fetchone()

    def delete_session(self, token: str) -> None:
        with self._lock:
            conn = self.connect()
            conn.execute("DELETE FROM sessions WHERE token = ?", (token,))
            conn.commit()

    # -- orders ---------------------------------------------------------------

    def order_by_reference(self, reference: str) -> dict | None:
        with self._lock:
            conn = self.connect()
            row = conn.execute(
                "SELECT * FROM orders WHERE reference = ?", (reference,)
            ).fetchone()
            if row is None:
                return None
            line = conn.execute(
                "SELECT * FROM order_lines WHERE order_reference = ?",
                (reference,),
            ).fetchone()
        quantity = int(line["quantity"]) if line is not None else 0
        unit_cents = int(line["unit_price_cents"]) if line is not None else 0
        return {
            "id": row["reference"],
            "account_id": int(row["account_id"]),
            "event_id": row["event_id"],
            "occurrence_id": row["occurrence_id"],
            "quantity": quantity,
            "email": row["email"],
            "first_name": row["first_name"],
            "last_name": row["last_name"],
            "unit_price": f"{unit_cents / 100:.2f}",
            "total": f"{int(row['total_cents']) / 100:.2f}",
            "created_at": row["created_at"],
            "payment_flow_id": row["payment_flow_id"],
            "payment_fingerprint": row["payment_fingerprint"],
        }

    def replayed_order_reference(
        self, *, owner: str, idempotency_key: str, payload_digest: str
    ) -> str | None:
        """Resolve an exact committed retry before opening a payment flow."""
        with self._lock:
            row = self.connect().execute(
                "SELECT payload_digest,order_reference "
                "FROM ticket_order_commands "
                "WHERE owner=? AND idempotency_key=?",
                (owner, idempotency_key),
            ).fetchone()
            if row is None:
                return None
            if str(row["payload_digest"]) != payload_digest:
                raise CommandConflict(
                    "idempotency key already belongs to another payload"
                )
            order_exists = self.connect().execute(
                "SELECT 1 FROM orders WHERE reference=?",
                (row["order_reference"],),
            ).fetchone()
            if order_exists is None:
                raise CommandConflict(
                    "committed order command refers to a missing order"
                )
            return str(row["order_reference"])

    def create_order(
        self,
        *,
        reference: str,
        account_id: int,
        owner: str,
        idempotency_key: str,
        payload_digest: str,
        expected_version: int,
        event_id: str,
        occurrence_id: str,
        ticket_class_id: int,
        quantity: int,
        email: str,
        first_name: str,
        last_name: str,
        payment_flow_id: str = "",
        payment_consumer: Callable[
            [sqlite3.Connection, dict[str, object]], object
        ]
        | None = None,
    ) -> str:
        """Commit one owner-scoped order command and its registrations.

        For a paid order, ``payment_consumer`` spends the exact sandbox
        authorization after all server-owned facts validate and before the
        first order write. The payment and order therefore commit or roll back
        together.
        """
        with self._lock:
            conn = self.connect()
            try:
                conn.execute("BEGIN IMMEDIATE")
                account = conn.execute(
                    "SELECT slug FROM accounts WHERE id = ?", (account_id,)
                ).fetchone()
                if account is None or str(account["slug"]) != owner:
                    conn.execute("ROLLBACK")
                    raise ValueError(
                        "order account does not match the authenticated owner"
                    )
                payment_claimed = bool(payment_flow_id or payment_consumer)
                prior_command = conn.execute(
                    "SELECT payload_digest,order_reference,canonical_result "
                    "FROM ticket_order_commands "
                    "WHERE owner=? AND idempotency_key=?",
                    (owner, idempotency_key),
                ).fetchone()
                if prior_command is not None:
                    if prior_command["payload_digest"] != payload_digest:
                        conn.execute("ROLLBACK")
                        raise CommandConflict(
                            "idempotency key already belongs to another payload"
                        )
                    if payment_claimed:
                        prior_order = conn.execute(
                            "SELECT total_cents FROM orders WHERE reference=?",
                            (prior_command["order_reference"],),
                        ).fetchone()
                        if (
                            prior_order is not None
                            and int(prior_order["total_cents"]) == 0
                        ):
                            conn.execute("ROLLBACK")
                            raise ValueError(
                                "free orders cannot consume a sandbox payment"
                            )
                    conn.execute("ROLLBACK")
                    return "replayed"
                existing = conn.execute(
                    "SELECT 1 FROM orders WHERE reference = ?", (reference,)
                ).fetchone()
                if existing is not None and not payment_claimed:
                    conn.execute("ROLLBACK")
                    raise CommandConflict(
                        "canonical order identity already belongs to another command"
                    )

                def consume_and_verify(
                    final_facts: dict[str, object],
                ) -> tuple[str, str]:
                    if not payment_flow_id or payment_consumer is None:
                        raise ValueError(
                            "paid orders require a bound sandbox authorization"
                        )
                    snapshot = payment_consumer(conn, final_facts)
                    if not isinstance(snapshot, dict):
                        raise ValueError(
                            "payment consumer returned no final-state snapshot"
                        )
                    snapshot_fingerprint = str(snapshot.get("fingerprint", ""))
                    snapshot_amount = int(final_facts["amount_minor"])
                    if (
                        str(snapshot.get("site_id", "")) != "eventbrite"
                        or str(snapshot.get("flow_id", "")) != payment_flow_id
                        or str(snapshot.get("owner", "")) != owner
                        or int(snapshot.get("amount_minor", -1))
                        != snapshot_amount
                        or str(snapshot.get("currency", "")) != "USD"
                        or snapshot.get("is_simulation") is not True
                        or re.fullmatch(r"[a-f0-9]{64}", snapshot_fingerprint)
                        is None
                    ):
                        raise ValueError(
                            "payment consumer returned an invalid final snapshot"
                        )
                    flow = conn.execute(
                        "SELECT owner,amount_minor,currency,fingerprint,status,"
                        "is_simulation FROM websitebench_payment_flows "
                        "WHERE site_id='eventbrite' AND flow_id=?",
                        (payment_flow_id,),
                    ).fetchone()
                    attempt = conn.execute(
                        "SELECT owner,amount_minor,currency,fingerprint,status,"
                        "is_simulation FROM websitebench_payment_attempts "
                        "WHERE site_id='eventbrite' AND flow_id=? "
                        "AND status='CONSUMED'",
                        (payment_flow_id,),
                    ).fetchone()
                    expected = (
                        owner,
                        snapshot_amount,
                        "USD",
                        snapshot_fingerprint,
                        1,
                    )
                    if (
                        flow is None
                        or attempt is None
                        or (
                            str(flow["owner"]),
                            int(flow["amount_minor"]),
                            str(flow["currency"]),
                            str(flow["fingerprint"]),
                            int(flow["is_simulation"]),
                        )
                        != expected
                        or str(flow["status"]) != "CONSUMED"
                        or (
                            str(attempt["owner"]),
                            int(attempt["amount_minor"]),
                            str(attempt["currency"]),
                            str(attempt["fingerprint"]),
                            int(attempt["is_simulation"]),
                        )
                        != expected
                    ):
                        raise ValueError(
                            "payment consumer did not consume the bound shared ledger"
                        )
                    return payment_flow_id, snapshot_fingerprint

                row = conn.execute(
                    "SELECT t.capacity,t.per_order_max,t.version,t.price_cents,"
                    "t.occurrence_id,o.event_id,t.sold_baseline + "
                    "COALESCE((SELECT SUM(quantity) FROM order_lines "
                    "WHERE ticket_class_id=t.id),0) AS used "
                    "FROM ticket_classes t JOIN occurrences o "
                    "ON o.id=t.occurrence_id WHERE t.id=?",
                    (ticket_class_id,),
                ).fetchone()
                if row is None:
                    if payment_claimed:
                        flow = conn.execute(
                            "SELECT amount_minor FROM websitebench_payment_flows "
                            "WHERE site_id='eventbrite' AND flow_id=? AND owner=?",
                            (payment_flow_id, owner),
                        ).fetchone()
                        # A missing ticket class is a terminal final-state
                        # mismatch.  The deliberately impossible tombstone
                        # facts cannot equal an approval minted by the HTTP
                        # checkout (which always binds a real association,
                        # non-negative inventory and an available class), so
                        # the shared ledger durably invalidates the approval.
                        consume_and_verify(
                            {
                                "event_id": event_id,
                                "occurrence_id": occurrence_id,
                                "ticket_class_id": ticket_class_id,
                                "ticket_class_version": expected_version,
                                "quantity": quantity,
                                "unit_price_cents": 0,
                                "amount_minor": (
                                    int(flow["amount_minor"])
                                    if flow is not None
                                    else 0
                                ),
                                "remaining": -1,
                                "association_matches": False,
                                "inventory_available": False,
                                "quantity_within_limit": False,
                                "canonical_order_available": False,
                                "owner_account_matches": True,
                            }
                        )
                    raise ValueError("ticket class does not exist")
                association_matches = (
                    str(row["event_id"]) == event_id
                    and str(row["occurrence_id"]) == occurrence_id
                )
                if quantity < 1:
                    conn.execute("ROLLBACK")
                    raise ValueError("ticket quantity must be positive")
                current_version = int(row["version"])
                remaining = int(row["capacity"]) - int(row["used"])
                current_unit_price_cents = int(row["price_cents"])
                total_cents = current_unit_price_cents * quantity
                if total_cents == 0 and payment_claimed:
                    conn.execute("ROLLBACK")
                    raise ValueError(
                        "free orders cannot consume a sandbox payment"
                    )
                final_facts: dict[str, object] = {
                    "event_id": str(row["event_id"]),
                    "occurrence_id": str(row["occurrence_id"]),
                    "ticket_class_id": ticket_class_id,
                    "ticket_class_version": current_version,
                    "quantity": quantity,
                    "unit_price_cents": current_unit_price_cents,
                    "amount_minor": total_cents,
                    "remaining": remaining,
                    "association_matches": association_matches,
                    "inventory_available": remaining >= quantity,
                    "quantity_within_limit": (
                        quantity <= int(row["per_order_max"])
                    ),
                    "canonical_order_available": existing is None,
                    "owner_account_matches": True,
                }
                if total_cents > 0:
                    payment_flow_id, payment_fingerprint = consume_and_verify(
                        final_facts
                    )
                else:
                    payment_fingerprint = ""
                if existing is not None:
                    conn.execute("ROLLBACK")
                    raise CommandConflict(
                        "canonical order identity already belongs to another command"
                    )
                if not association_matches:
                    conn.execute("ROLLBACK")
                    raise ValueError(
                        "ticket class does not belong to the supplied event occurrence"
                    )
                if current_version != expected_version:
                    conn.execute("ROLLBACK")
                    raise StaleVersion(
                        f"expected {expected_version}, current {current_version}"
                    )
                if quantity > int(row["per_order_max"]):
                    conn.execute("ROLLBACK")
                    raise ValueError(
                        "ticket quantity exceeds the current per-order limit"
                    )
                if remaining < quantity:
                    conn.execute("ROLLBACK")
                    raise SoldOut(
                        f"remaining {remaining} < requested {quantity}"
                    )
                conn.execute(
                    "INSERT INTO orders (reference, account_id, event_id, "
                    "occurrence_id, email, first_name, last_name, "
                    "total_cents, created_at, payment_flow_id, "
                    "payment_fingerprint) "
                    "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
                    (
                        reference,
                        account_id,
                        event_id,
                        occurrence_id,
                        email,
                        first_name,
                        last_name,
                        total_cents,
                        FROZEN_CLOCK,
                        payment_flow_id,
                        payment_fingerprint,
                    ),
                )
                conn.execute(
                    "INSERT INTO order_lines (order_reference, "
                    "ticket_class_id, quantity, unit_price_cents) "
                    "VALUES (?, ?, ?, ?)",
                    (
                        reference,
                        ticket_class_id,
                        quantity,
                        current_unit_price_cents,
                    ),
                )
                for seq in range(1, quantity + 1):
                    conn.execute(
                        "INSERT INTO registrations (order_reference, "
                        "ticket_class_id, seq, first_name, last_name, "
                        "email) VALUES (?, ?, ?, ?, ?, ?)",
                        (
                            reference,
                            ticket_class_id,
                            seq,
                            first_name,
                            last_name,
                            email,
                        ),
                    )
                command_id = (
                    "order-command-"
                    + hashlib.sha256(
                        f"{owner}|{idempotency_key}".encode("utf-8")
                    ).hexdigest()[:24]
                )
                canonical_result = f"receipt:{reference}"
                conn.execute(
                    "INSERT INTO ticket_order_commands("
                    "command_id,owner,idempotency_key,payload_digest,"
                    "order_reference,expected_version,canonical_result,created_at"
                    ") VALUES (?,?,?,?,?,?,?,?)",
                    (
                        command_id,
                        owner,
                        idempotency_key,
                        payload_digest,
                        reference,
                        expected_version,
                        canonical_result,
                        FROZEN_CLOCK,
                    ),
                )
                next_version = current_version + 1
                conn.execute(
                    "UPDATE ticket_classes SET version=? WHERE id=?",
                    (next_version, ticket_class_id),
                )
                conn.execute(
                    "INSERT INTO ticket_order_version_journal("
                    "ticket_class_id,prior_version,version,command_id,"
                    "outcome_digest,created_at) VALUES (?,?,?,?,?,?)",
                    (
                        ticket_class_id,
                        current_version,
                        next_version,
                        command_id,
                        hashlib.sha256(
                            canonical_result.encode("utf-8")
                        ).hexdigest(),
                        FROZEN_CLOCK,
                    ),
                )
                conn.execute("COMMIT")
                return "created"
            except (SoldOut, StaleVersion, CommandConflict):
                raise
            except Exception:
                try:
                    conn.execute("ROLLBACK")
                except sqlite3.OperationalError:
                    pass
                raise

    def order_count(self) -> int:
        with self._lock:
            row = self.connect().execute(
                "SELECT COUNT(*) AS n FROM orders"
            ).fetchone()
            return int(row["n"])

    def orders_snapshot(self) -> list[dict]:
        with self._lock:
            rows = self.connect().execute(
                "SELECT reference FROM orders ORDER BY rowid"
            ).fetchall()
        return [
            order
            for order in (
                self.order_by_reference(row["reference"]) for row in rows
            )
            if order is not None
        ]

    def registration_count(self, reference: str) -> int:
        with self._lock:
            row = self.connect().execute(
                "SELECT COUNT(*) AS n FROM registrations "
                "WHERE order_reference = ?",
                (reference,),
            ).fetchone()
            return int(row["n"])

    # -- organizer events -------------------------------------------------------

    def organizer_event(self, local_id: str) -> sqlite3.Row | None:
        with self._lock:
            return self.connect().execute(
                "SELECT * FROM organizer_events WHERE id = ?", (local_id,)
            ).fetchone()

    def organizer_events_for(self, owner: str) -> list[sqlite3.Row]:
        with self._lock:
            return self.connect().execute(
                "SELECT * FROM organizer_events "
                "WHERE owner = ? AND status='published-local' "
                "ORDER BY created_at, id",
                (owner,),
            ).fetchall()

    def create_organizer_event(
        self,
        *,
        local_id: str,
        title: str,
        event_date: str,
        location: str,
        description: str,
        owner: str,
        expected_version: int = 1,
        idempotency_key: str = "",
        payload_digest: str = "",
        draft_id: str = "draft:task-372:ml-paper-reading-group",
    ) -> str:
        with self._lock:
            conn = self.connect()
            try:
                conn.execute("BEGIN IMMEDIATE")
                key = idempotency_key or f"create:{local_id}"
                digest = payload_digest or hashlib.sha256(
                    (
                        f"{title}|{event_date}|{location}|{description}|"
                        f"{draft_id}|{expected_version}"
                    ).encode("utf-8")
                ).hexdigest()
                prior = conn.execute(
                    "SELECT payload_digest,canonical_result "
                    "FROM organizer_event_commands "
                    "WHERE owner=? AND idempotency_key=?",
                    (owner, key),
                ).fetchone()
                if prior is not None:
                    if prior["payload_digest"] != digest:
                        conn.execute("ROLLBACK")
                        raise CommandConflict(
                            "idempotency key already belongs to another payload"
                        )
                    conn.execute("ROLLBACK")
                    return "replayed"
                draft = conn.execute(
                    "SELECT * FROM organizer_event_drafts WHERE id=?",
                    (draft_id,),
                ).fetchone()
                if draft is None or draft["owner"] != owner:
                    conn.execute("ROLLBACK")
                    raise PermissionError("draft belongs to another organizer")
                current_version = int(draft["version"])
                if current_version != expected_version:
                    conn.execute("ROLLBACK")
                    raise StaleVersion(
                        f"expected {expected_version}, current {current_version}"
                    )
                existing = conn.execute(
                    "SELECT owner FROM organizer_events WHERE id=?",
                    (local_id,),
                ).fetchone()
                if existing is not None and existing["owner"] != owner:
                    conn.execute("ROLLBACK")
                    raise PermissionError("event belongs to another organizer")
                conn.execute(
                    "INSERT INTO organizer_events "
                    "(id,title,event_date,location,description,owner,created_at,"
                    "version,status) VALUES (?,?,?,?,?,?,?,?, 'published-local')",
                    (
                        local_id,
                        title,
                        event_date,
                        location,
                        description,
                        owner,
                        FROZEN_CLOCK,
                        expected_version,
                    ),
                )
                command_id = (
                    "organizer-command-"
                    + hashlib.sha256(f"{owner}|{key}".encode("utf-8")).hexdigest()[:24]
                )
                canonical_result = f"event:{local_id}:published-local"
                conn.execute(
                    "INSERT INTO organizer_event_commands("
                    "command_id,owner,idempotency_key,payload_digest,operation,"
                    "event_id,expected_version,canonical_result,created_at"
                    ") VALUES (?,?,?,?, 'create',?,?,?,?)",
                    (
                        command_id,
                        owner,
                        key,
                        digest,
                        local_id,
                        expected_version,
                        canonical_result,
                        FROZEN_CLOCK,
                    ),
                )
                conn.execute(
                    "INSERT INTO organizer_event_version_journal("
                    "event_id,prior_version,version,command_id,outcome_digest,"
                    "created_at) VALUES (?,?,?,?,?,?)",
                    (
                        local_id,
                        0,
                        expected_version,
                        command_id,
                        hashlib.sha256(
                            canonical_result.encode("utf-8")
                        ).hexdigest(),
                        FROZEN_CLOCK,
                    ),
                )
                conn.execute("COMMIT")
                return "created"
            except (CommandConflict, StaleVersion, PermissionError):
                raise
            except Exception:
                try:
                    conn.execute("ROLLBACK")
                except sqlite3.OperationalError:
                    pass
                raise

    def delete_organizer_event(
        self,
        local_id: str,
        *,
        owner: str,
        expected_version: int,
        idempotency_key: str,
    ) -> str:
        with self._lock:
            conn = self.connect()
            try:
                conn.execute("BEGIN IMMEDIATE")
                payload_digest = hashlib.sha256(
                    f"delete|{local_id}|{expected_version}".encode("utf-8")
                ).hexdigest()
                prior = conn.execute(
                    "SELECT payload_digest FROM organizer_event_commands "
                    "WHERE owner=? AND idempotency_key=?",
                    (owner, idempotency_key),
                ).fetchone()
                if prior is not None:
                    if prior["payload_digest"] != payload_digest:
                        conn.execute("ROLLBACK")
                        raise CommandConflict(
                            "idempotency key already belongs to another payload"
                        )
                    conn.execute("ROLLBACK")
                    return "replayed"
                event = conn.execute(
                    "SELECT owner,version,status FROM organizer_events WHERE id=?",
                    (local_id,),
                ).fetchone()
                if event is None:
                    conn.execute("ROLLBACK")
                    raise ValueError("event does not exist")
                if event["owner"] != owner:
                    conn.execute("ROLLBACK")
                    raise PermissionError("event belongs to another organizer")
                current_version = int(event["version"])
                if current_version != expected_version:
                    conn.execute("ROLLBACK")
                    raise StaleVersion(
                        f"expected {expected_version}, current {current_version}"
                    )
                next_version = current_version + 1
                conn.execute(
                    "UPDATE organizer_events SET status='deleted',version=? "
                    "WHERE id=?",
                    (next_version, local_id),
                )
                command_id = (
                    "organizer-command-"
                    + hashlib.sha256(
                        f"{owner}|{idempotency_key}".encode("utf-8")
                    ).hexdigest()[:24]
                )
                canonical_result = f"event:{local_id}:deleted"
                conn.execute(
                    "INSERT INTO organizer_event_commands("
                    "command_id,owner,idempotency_key,payload_digest,operation,"
                    "event_id,expected_version,canonical_result,created_at"
                    ") VALUES (?,?,?,?, 'delete',?,?,?,?)",
                    (
                        command_id,
                        owner,
                        idempotency_key,
                        payload_digest,
                        local_id,
                        expected_version,
                        canonical_result,
                        FROZEN_CLOCK,
                    ),
                )
                conn.execute(
                    "INSERT INTO organizer_event_version_journal("
                    "event_id,prior_version,version,command_id,outcome_digest,"
                    "created_at) VALUES (?,?,?,?,?,?)",
                    (
                        local_id,
                        current_version,
                        next_version,
                        command_id,
                        hashlib.sha256(
                            canonical_result.encode("utf-8")
                        ).hexdigest(),
                        FROZEN_CLOCK,
                    ),
                )
                conn.execute("COMMIT")
                return "deleted"
            except (CommandConflict, StaleVersion, PermissionError, ValueError):
                raise
            except Exception:
                try:
                    conn.execute("ROLLBACK")
                except sqlite3.OperationalError:
                    pass
                raise

    def organizer_event_ids(self) -> set[str]:
        with self._lock:
            rows = self.connect().execute(
                "SELECT id FROM organizer_events"
            ).fetchall()
            return {row["id"] for row in rows}

    def organizer_event_count(self) -> int:
        with self._lock:
            row = self.connect().execute(
                "SELECT COUNT(*) AS n FROM organizer_events"
            ).fetchone()
            return int(row["n"])

    def command_counts(self) -> dict[str, int]:
        with self._lock:
            conn = self.connect()
            return {
                "ticket_order_commands": int(
                    conn.execute(
                        "SELECT COUNT(*) FROM ticket_order_commands"
                    ).fetchone()[0]
                ),
                "ticket_order_version_journal": int(
                    conn.execute(
                        "SELECT COUNT(*) FROM ticket_order_version_journal"
                    ).fetchone()[0]
                ),
                "organizer_event_commands": int(
                    conn.execute(
                        "SELECT COUNT(*) FROM organizer_event_commands"
                    ).fetchone()[0]
                ),
                "organizer_event_version_journal": int(
                    conn.execute(
                        "SELECT COUNT(*) FROM organizer_event_version_journal"
                    ).fetchone()[0]
                ),
            }

    # -- event builder (multi-step create flow) -------------------------------

    def _builder_replay(
        self, conn: sqlite3.Connection, owner: str, key: str, digest: str
    ) -> str | None:
        """Idempotency gate shared by every builder command. Returns the
        canonical result of the prior identical command, or None when the
        command is new. A key reused with a different payload is a
        conflict, mirroring the ticket/organizer command ledgers."""
        prior = conn.execute(
            "SELECT payload_digest, canonical_result FROM builder_commands "
            "WHERE owner=? AND idempotency_key=?",
            (owner, key),
        ).fetchone()
        if prior is None:
            return None
        if prior["payload_digest"] != digest:
            raise CommandConflict(
                "idempotency key already belongs to another payload"
            )
        return str(prior["canonical_result"])

    def _builder_record(
        self,
        conn: sqlite3.Connection,
        *,
        owner: str,
        key: str,
        digest: str,
        operation: str,
        draft_id: str,
        expected_version: int,
        prior_version: int,
        version: int,
        canonical_result: str,
    ) -> None:
        command_id = (
            "builder-command-"
            + hashlib.sha256(f"{owner}|{key}".encode("utf-8")).hexdigest()[:24]
        )
        conn.execute(
            "INSERT INTO builder_commands("
            "command_id,owner,idempotency_key,payload_digest,operation,"
            "draft_id,expected_version,canonical_result,created_at"
            ") VALUES (?,?,?,?,?,?,?,?,?)",
            (command_id, owner, key, digest, operation, draft_id,
             expected_version, canonical_result, FROZEN_CLOCK),
        )
        conn.execute(
            "INSERT INTO builder_version_journal("
            "draft_id,prior_version,version,command_id,outcome_digest,"
            "created_at) VALUES (?,?,?,?,?,?)",
            (draft_id, prior_version, version, command_id,
             hashlib.sha256(canonical_result.encode("utf-8")).hexdigest(),
             FROZEN_CLOCK),
        )

    def _builder_draft_row(
        self, conn: sqlite3.Connection, draft_id: str, owner: str
    ) -> sqlite3.Row:
        row = conn.execute(
            "SELECT * FROM organizer_event_drafts WHERE id=?", (draft_id,)
        ).fetchone()
        if row is None:
            raise ValueError("draft does not exist")
        if row["owner"] != owner:
            raise PermissionError("draft belongs to another organizer")
        return row

    @staticmethod
    def _builder_ticket_view(row: sqlite3.Row) -> dict:
        return {
            "id": int(row["id"]),
            "name": row["name"],
            "kind": row["kind"],
            "price_cents": int(row["price_cents"]),
            "quantity": int(row["quantity"]),
            "per_order_max": int(row["per_order_max"]),
            "sales_start_at": str(row["sales_start_at"]),
            "sales_end_at": str(row["sales_end_at"]),
            "rank": int(row["rank"]),
        }

    def builder_draft(self, draft_id: str, owner: str) -> dict | None:
        with self._lock:
            conn = self.connect()
            try:
                row = self._builder_draft_row(conn, draft_id, owner)
            except (ValueError, PermissionError):
                return None
            tickets = [
                self._builder_ticket_view(t)
                for t in conn.execute(
                    "SELECT * FROM draft_ticket_classes WHERE draft_id=? "
                    "ORDER BY rank, id",
                    (draft_id,),
                ).fetchall()
            ]
            draft = {key: row[key] for key in row.keys()}
            draft["version"] = int(row["version"])
            draft["tickets"] = tickets
            return draft

    def builder_drafts_for(self, owner: str) -> list[dict]:
        with self._lock:
            rows = self.connect().execute(
                "SELECT * FROM organizer_event_drafts WHERE owner=? "
                "ORDER BY updated_seq DESC, id",
                (owner,),
            ).fetchall()
        return [
            {**{key: row[key] for key in row.keys()},
             "version": int(row["version"])}
            for row in rows
        ]

    def builder_create_count(self, owner: str) -> int:
        """Count immutable create commands, including discarded drafts."""
        with self._lock:
            row = self.connect().execute(
                "SELECT COUNT(*) AS n FROM builder_commands "
                "WHERE owner=? AND operation='draft-create'",
                (owner,),
            ).fetchone()
            return int(row["n"])

    def builder_create_next_draft(self, owner: str) -> tuple[str, str]:
        """Allocate the next builder-entry command and draft atomically.

        The immutable create ledger is the sequence authority. Holding one
        BEGIN IMMEDIATE transaction across allocation and insertion prevents
        concurrent GET /manage/events/create requests from sharing a key.
        """
        with self._lock:
            conn = self.connect()
            try:
                conn.execute("BEGIN IMMEDIATE")
                serial = int(
                    conn.execute(
                        "SELECT COUNT(*) FROM builder_commands "
                        "WHERE owner=? AND operation='draft-create'",
                        (owner,),
                    ).fetchone()[0]
                ) + 1
                key = f"builder-entry:{serial}"
                draft_id = (
                    "draft:builder:"
                    + hashlib.sha256(f"{owner}|{key}".encode("utf-8")).hexdigest()[:16]
                )
                digest = hashlib.sha256(
                    f"draft-create|{draft_id}".encode()
                ).hexdigest()
                prior = self._builder_replay(conn, owner, key, digest)
                if prior is not None:
                    conn.execute("ROLLBACK")
                    return draft_id, "replayed"
                conn.execute(
                    "INSERT INTO organizer_event_drafts "
                    "(id, owner, version, title, event_date, location, "
                    "description, updated_seq) VALUES (?,?,1,'','','','',1)",
                    (draft_id, owner),
                )
                self._builder_record(
                    conn, owner=owner, key=key, digest=digest,
                    operation="draft-create", draft_id=draft_id,
                    expected_version=0, prior_version=0, version=1,
                    canonical_result=f"draft:{draft_id}:created",
                )
                conn.execute("COMMIT")
                return draft_id, "created"
            except Exception:
                if conn.in_transaction:
                    conn.execute("ROLLBACK")
                raise

    def builder_create_draft(
        self, owner: str, *, idempotency_key: str
    ) -> tuple[str, str]:
        """Create an empty builder draft. Deterministic id per (owner, key)
        so retrying the create lands on the same draft."""
        draft_id = (
            "draft:builder:"
            + hashlib.sha256(
                f"{owner}|{idempotency_key}".encode("utf-8")
            ).hexdigest()[:16]
        )
        digest = hashlib.sha256(f"draft-create|{draft_id}".encode()).hexdigest()
        with self._lock:
            conn = self.connect()
            try:
                conn.execute("BEGIN IMMEDIATE")
                replayed = self._builder_replay(
                    conn, owner, idempotency_key, digest)
                if replayed is not None:
                    conn.execute("ROLLBACK")
                    return draft_id, "replayed"
                conn.execute(
                    "INSERT INTO organizer_event_drafts "
                    "(id, owner, version, title, event_date, location, "
                    "description, updated_seq) VALUES (?,?,1,'','','','',1)",
                    (draft_id, owner),
                )
                self._builder_record(
                    conn, owner=owner, key=idempotency_key, digest=digest,
                    operation="draft-create", draft_id=draft_id,
                    expected_version=0, prior_version=0, version=1,
                    canonical_result=f"draft:{draft_id}:created",
                )
                conn.execute("COMMIT")
                return draft_id, "created"
            except CommandConflict:
                try:
                    conn.execute("ROLLBACK")
                except sqlite3.OperationalError:
                    pass
                raise
            except Exception:
                try:
                    conn.execute("ROLLBACK")
                except sqlite3.OperationalError:
                    pass
                raise

    def builder_update_draft(
        self,
        draft_id: str,
        owner: str,
        *,
        expected_version: int,
        fields: dict[str, str],
        idempotency_key: str,
    ) -> tuple[int, str]:
        """Autosave one or more draft fields under optimistic concurrency."""
        unknown = set(fields) - BUILDER_UPDATABLE_FIELDS
        if unknown:
            raise ValueError(f"unknown fields: {sorted(unknown)}")
        if not fields:
            raise ValueError("no fields to update")
        for field, value in fields.items():
            if not isinstance(field, str) or not isinstance(value, str):
                raise ValueError("builder field names and values must be strings")
            if len(value) > BUILDER_FIELD_LIMITS[field]:
                raise ValueError(f"{field} is too long")
        if (
            "location_type" in fields
            and fields["location_type"] not in {"venue", "online", "tbd"}
        ):
            raise ValueError("location_type must be venue, online, or tbd")
        if (
            "timezone" in fields
            and fields["timezone"] not in BUILDER_ALLOWED_TIMEZONES
        ):
            raise ValueError("timezone is not supported")
        for date_field in ("start_at", "end_at"):
            if fields.get(date_field):
                try:
                    datetime.fromisoformat(fields[date_field])
                except ValueError:
                    raise ValueError(
                        f"{date_field} must be a date and time"
                    ) from None
        image_ref = fields.get("image_ref")
        if image_ref is not None:
            valid_gallery = (
                image_ref.startswith("gallery:")
                and ".." not in image_ref
                and re.fullmatch(r"gallery:[A-Za-z0-9_./-]+", image_ref)
            )
            valid_upload = re.fullmatch(r"upload:[0-9a-f]{64}", image_ref)
            if image_ref and not (valid_gallery or valid_upload):
                raise ValueError("image_ref is not a local builder image")
        payload = "|".join(f"{k}={fields[k]}" for k in sorted(fields))
        digest = hashlib.sha256(
            f"draft-update|{draft_id}|{expected_version}|{payload}".encode()
        ).hexdigest()
        with self._lock:
            conn = self.connect()
            try:
                conn.execute("BEGIN IMMEDIATE")
                replayed = self._builder_replay(
                    conn, owner, idempotency_key, digest)
                row = self._builder_draft_row(conn, draft_id, owner)
                current = int(row["version"])
                if replayed is not None:
                    conn.execute("ROLLBACK")
                    return current, "replayed"
                if row["status"] == "published":
                    conn.execute("ROLLBACK")
                    raise ValueError("draft is already published")
                if current != expected_version:
                    conn.execute("ROLLBACK")
                    raise StaleVersion(
                        f"expected {expected_version}, current {current}"
                    )
                if image_ref and image_ref.startswith("upload:"):
                    image = conn.execute(
                        "SELECT owner FROM uploaded_images WHERE sha=?",
                        (image_ref.split(":", 1)[1],),
                    ).fetchone()
                    if image is None:
                        conn.execute("ROLLBACK")
                        raise ValueError("uploaded image does not exist")
                    if str(image["owner"]) != owner:
                        conn.execute("ROLLBACK")
                        raise PermissionError(
                            "uploaded image belongs to another organizer"
                        )
                resulting_start = fields.get("start_at", row["start_at"])
                resulting_end = fields.get("end_at", row["end_at"])
                if resulting_start and resulting_end:
                    try:
                        end_before_start = datetime.fromisoformat(
                            str(resulting_end)
                        ) < datetime.fromisoformat(str(resulting_start))
                    except TypeError:
                        conn.execute("ROLLBACK")
                        raise ValueError(
                            "event dates must use the same timezone form"
                        ) from None
                    if end_before_start:
                        conn.execute("ROLLBACK")
                        raise ValueError("event end must be after event start")
                version = current + 1
                assignments = {**fields}
                # Keep the legacy single-string columns mirrored so the old
                # auto-create surface renders builder drafts too.
                if "start_at" in fields:
                    assignments["event_date"] = fields["start_at"][:16].replace(
                        "T", " ")
                if {
                    "location_type", "venue_name", "venue_city",
                    "online_platform",
                } & set(fields):
                    location_type = fields.get(
                        "location_type", row["location_type"]
                    )
                    if location_type == "online":
                        platform = str(fields.get(
                            "online_platform", row["online_platform"]
                        )).strip()
                        assignments["location"] = (
                            f"Online ({platform})" if platform else "Online"
                        )
                    elif location_type == "tbd":
                        assignments["location"] = "To be announced"
                    else:
                        name = fields.get("venue_name", row["venue_name"])
                        city = fields.get("venue_city", row["venue_city"])
                        assignments["location"] = ", ".join(
                            part for part in (name, city) if part)
                if "summary" in fields and not row["description"]:
                    assignments["description"] = fields["summary"]
                sets = ", ".join(f"{k}=?" for k in assignments)
                conn.execute(
                    f"UPDATE organizer_event_drafts SET {sets}, "
                    "version=?, updated_seq=? WHERE id=?",
                    (*assignments.values(), version, version, draft_id),
                )
                self._builder_record(
                    conn, owner=owner, key=idempotency_key, digest=digest,
                    operation="draft-update", draft_id=draft_id,
                    expected_version=expected_version,
                    prior_version=current, version=version,
                    canonical_result=f"draft:{draft_id}:v{version}",
                )
                conn.execute("COMMIT")
                return version, "updated"
            except (CommandConflict, StaleVersion, PermissionError, ValueError):
                try:
                    conn.execute("ROLLBACK")
                except sqlite3.OperationalError:
                    pass
                raise
            except Exception:
                try:
                    conn.execute("ROLLBACK")
                except sqlite3.OperationalError:
                    pass
                raise

    def builder_ticket_command(
        self,
        draft_id: str,
        owner: str,
        *,
        operation: str,
        expected_version: int,
        idempotency_key: str,
        ticket_id: int | None = None,
        fields: dict | None = None,
    ) -> tuple[int, int | None, str]:
        """Create/update/delete one draft ticket class. Returns
        (new draft version, ticket id, outcome)."""
        if operation not in ("ticket-create", "ticket-update", "ticket-delete"):
            raise ValueError("unknown ticket operation")
        fields = dict(fields or {})
        unknown = set(fields) - BUILDER_TICKET_FIELDS
        if unknown:
            raise ValueError(f"unknown fields: {sorted(unknown)}")
        # The active offline-clone scope intentionally has no payment flow.
        # Keep source-shaped paid/donation choices visible in the UI, but
        # never persist a ticket class that implies an unpaid paid order.
        requested_kind = fields.get("kind")
        if requested_kind is not None and (
            not isinstance(requested_kind, str) or requested_kind != "free"
        ):
            raise ValueError(
                "Paid and donation tickets are unavailable in this offline preview"
            )
        requested_price = fields.get("price_cents")
        if requested_price is not None and (
            isinstance(requested_price, bool)
            or not isinstance(requested_price, int)
            or requested_price != 0
        ):
            raise ValueError("free ticket price must be exactly zero")
        if operation == "ticket-create":
            fields["kind"] = "free"
        if operation in ("ticket-create", "ticket-update") and "price_cents" in fields:
            fields["price_cents"] = 0
        if operation in ("ticket-create", "ticket-update"):
            if "name" in fields:
                name = fields["name"]
                if not isinstance(name, str) or not name.strip():
                    raise ValueError("ticket name is required")
                if len(name.strip()) > 120:
                    raise ValueError("ticket name is too long")
                fields["name"] = name.strip()
            for numeric_field in ("quantity", "per_order_max", "rank"):
                if numeric_field not in fields:
                    continue
                value = fields[numeric_field]
                if isinstance(value, bool) or not isinstance(value, int):
                    raise ValueError(
                        f"{numeric_field} must be a whole number"
                    )
            if int(fields.get("quantity", 1)) < 1:
                raise ValueError("ticket quantity must be at least 1")
            if int(fields.get("per_order_max", 1)) < 1:
                raise ValueError("per-order maximum must be at least 1")
            if int(fields.get("rank", 0)) < 0:
                raise ValueError("ticket rank cannot be negative")
            parsed_sales_dates: dict[str, datetime] = {}
            for date_field in ("sales_start_at", "sales_end_at"):
                if date_field not in fields:
                    continue
                value = fields[date_field]
                if not isinstance(value, str):
                    raise ValueError(f"{date_field} must be a date and time")
                if len(value) > 64:
                    raise ValueError(f"{date_field} must be a date and time")
                if value:
                    try:
                        parsed_sales_dates[date_field] = datetime.fromisoformat(value)
                    except ValueError:
                        raise ValueError(
                            f"{date_field} must be a date and time"
                        ) from None
            if len(parsed_sales_dates) == 2:
                try:
                    invalid_window = (
                        parsed_sales_dates["sales_start_at"]
                        > parsed_sales_dates["sales_end_at"]
                    )
                except TypeError:
                    raise ValueError(
                        "ticket sales dates must use the same timezone form"
                    ) from None
                if invalid_window:
                    raise ValueError("ticket sales end must be after sales start")
            if operation == "ticket-create" and int(
                fields.get("per_order_max", 10)
            ) > int(fields.get("quantity", 100)):
                raise ValueError(
                    "per-order maximum cannot exceed ticket quantity"
                )
        payload = "|".join(f"{k}={fields[k]}" for k in sorted(fields))
        digest = hashlib.sha256(
            f"{operation}|{draft_id}|{ticket_id}|{expected_version}|{payload}"
            .encode()
        ).hexdigest()
        with self._lock:
            conn = self.connect()
            try:
                conn.execute("BEGIN IMMEDIATE")
                replayed = self._builder_replay(
                    conn, owner, idempotency_key, digest)
                row = self._builder_draft_row(conn, draft_id, owner)
                current = int(row["version"])
                if replayed is not None:
                    conn.execute("ROLLBACK")
                    replay_ticket = None
                    if replayed.startswith("ticket:"):
                        replay_ticket = int(replayed.split(":")[1])
                    return current, replay_ticket, "replayed"
                if row["status"] == "published":
                    conn.execute("ROLLBACK")
                    raise ValueError("draft is already published")
                if current != expected_version:
                    conn.execute("ROLLBACK")
                    raise StaleVersion(
                        f"expected {expected_version}, current {current}"
                    )
                version = current + 1
                result_ticket: int | None = None
                if operation == "ticket-create":
                    cursor = conn.execute(
                        "INSERT INTO draft_ticket_classes (draft_id, name, "
                        "kind, price_cents, quantity, per_order_max, "
                        "sales_start_at, sales_end_at, rank) "
                        "VALUES (?,?,?,?,?,?,?,?,?)",
                        (
                            draft_id,
                            str(fields.get("name", "General Admission")),
                            "free",
                            0,
                            int(fields.get("quantity", 100)),
                            int(fields.get("per_order_max", 10)),
                            str(fields.get("sales_start_at", "")),
                            str(fields.get("sales_end_at", "")),
                            int(fields.get("rank", 0)),
                        ),
                    )
                    result_ticket = int(cursor.lastrowid)
                    canonical = f"ticket:{result_ticket}:created"
                else:
                    ticket = conn.execute(
                        "SELECT * FROM draft_ticket_classes "
                        "WHERE id=? AND draft_id=?",
                        (ticket_id, draft_id),
                    ).fetchone()
                    if ticket is None:
                        conn.execute("ROLLBACK")
                        raise ValueError("ticket does not exist")
                    result_ticket = int(ticket["id"])
                    if operation == "ticket-delete":
                        conn.execute(
                            "DELETE FROM draft_ticket_classes WHERE id=?",
                            (ticket_id,),
                        )
                        canonical = f"ticket:{result_ticket}:deleted"
                    else:
                        if not fields:
                            conn.execute("ROLLBACK")
                            raise ValueError("no fields to update")
                        resulting_kind = str(fields.get("kind", ticket["kind"]))
                        if resulting_kind != "free":
                            conn.execute("ROLLBACK")
                            raise ValueError(
                                "Paid and donation tickets are unavailable in "
                                "this offline preview"
                            )
                        if "kind" in fields:
                            fields["kind"] = "free"
                        if "price_cents" in fields:
                            fields["price_cents"] = 0
                        resulting_quantity = int(
                            fields.get("quantity", ticket["quantity"])
                        )
                        resulting_maximum = int(
                            fields.get("per_order_max", ticket["per_order_max"])
                        )
                        if resulting_maximum > resulting_quantity:
                            conn.execute("ROLLBACK")
                            raise ValueError(
                                "per-order maximum cannot exceed ticket quantity"
                            )
                        sets = ", ".join(f"{k}=?" for k in fields)
                        conn.execute(
                            f"UPDATE draft_ticket_classes SET {sets} "
                            "WHERE id=?",
                            (*fields.values(), ticket_id),
                        )
                        canonical = f"ticket:{result_ticket}:v{version}"
                conn.execute(
                    "UPDATE organizer_event_drafts SET version=?, "
                    "updated_seq=? WHERE id=?",
                    (version, version, draft_id),
                )
                self._builder_record(
                    conn, owner=owner, key=idempotency_key, digest=digest,
                    operation=operation, draft_id=draft_id,
                    expected_version=expected_version,
                    prior_version=current, version=version,
                    canonical_result=canonical,
                )
                conn.execute("COMMIT")
                return version, result_ticket, operation.split("-")[1] + "d"
            except (CommandConflict, StaleVersion, PermissionError, ValueError):
                try:
                    conn.execute("ROLLBACK")
                except sqlite3.OperationalError:
                    pass
                raise
            except Exception:
                try:
                    conn.execute("ROLLBACK")
                except sqlite3.OperationalError:
                    pass
                raise

    def builder_store_image(
        self, owner: str, content: bytes, mime: str,
        width: int = 0, height: int = 0,
    ) -> str:
        """Store an uploaded image; content-addressed so identical bytes
        return the same handle without a second row."""
        sha = hashlib.sha256(content).hexdigest()
        with self._lock:
            conn = self.connect()
            existing = conn.execute(
                "SELECT owner FROM uploaded_images WHERE sha=?", (sha,)
            ).fetchone()
            if existing is not None and str(existing["owner"]) != owner:
                raise PermissionError(
                    "uploaded image belongs to another organizer"
                )
            conn.execute(
                "INSERT OR IGNORE INTO uploaded_images "
                "(sha, owner, mime, bytes, width, height, content, created_at)"
                " VALUES (?,?,?,?,?,?,?,?)",
                (sha, owner, mime, len(content), width, height, content,
                 FROZEN_CLOCK),
            )
            conn.commit()
        return sha

    def builder_image(self, sha: str) -> sqlite3.Row | None:
        with self._lock:
            return self.connect().execute(
                "SELECT * FROM uploaded_images WHERE sha=?", (sha,)
            ).fetchone()

    def _builder_hero(self, image_ref: str) -> str:
        # gallery refs carry the capture-date-relative path (e.g.
        # "2026-07-25/home/x.jpg") so either frozen asset batch resolves.
        if image_ref.startswith("gallery:"):
            return (
                "/static/assets/source-current/"
                + image_ref.split(":", 1)[1].lstrip("/")
            )
        if image_ref.startswith("upload:"):
            return f"/media/{image_ref.split(':', 1)[1]}"
        return "/static/art/synthetic-sf-card.svg"

    def builder_publish(
        self,
        draft_id: str,
        owner: str,
        *,
        expected_version: int,
        idempotency_key: str,
    ) -> dict:
        """Publish a builder draft into the public catalog. The event, its
        occurrence, ticket classes and feed placements are written in one
        transaction, so the listing is browsable and purchasable the moment
        the command returns."""
        digest = hashlib.sha256(
            f"publish|{draft_id}|{expected_version}".encode()
        ).hexdigest()
        with self._lock:
            conn = self.connect()
            try:
                conn.execute("BEGIN IMMEDIATE")
                replayed = self._builder_replay(
                    conn, owner, idempotency_key, digest)
                row = self._builder_draft_row(conn, draft_id, owner)
                if replayed is not None or row["status"] == "published":
                    event_id = str(row["published_event_id"])
                    event = conn.execute(
                        "SELECT slug FROM events WHERE id=?", (event_id,)
                    ).fetchone()
                    conn.execute("ROLLBACK")
                    return {
                        "outcome": "replayed",
                        "event_id": event_id,
                        "slug": event["slug"] if event else "",
                        "version": int(row["version"]),
                    }
                current = int(row["version"])
                if current != expected_version:
                    conn.execute("ROLLBACK")
                    raise StaleVersion(
                        f"expected {expected_version}, current {current}"
                    )
                title = str(row["title"]).strip()
                if not title:
                    conn.execute("ROLLBACK")
                    raise ValueError("event title is required")
                if not str(row["start_at"]).strip():
                    conn.execute("ROLLBACK")
                    raise ValueError("event date and time are required")
                if row["location_type"] == "venue" and not str(
                    row["venue_name"]).strip():
                    conn.execute("ROLLBACK")
                    raise ValueError("venue name is required")
                tickets = conn.execute(
                    "SELECT * FROM draft_ticket_classes WHERE draft_id=? "
                    "ORDER BY rank, id",
                    (draft_id,),
                ).fetchall()
                if not tickets:
                    conn.execute("ROLLBACK")
                    raise ValueError("add at least one ticket before publishing")

                tz_name = str(row["timezone"])
                if tz_name not in _LISTING_UTC_OFFSETS:
                    tz_name = "America/Los_Angeles"
                tz = timezone(_LISTING_UTC_OFFSETS[tz_name])
                start = datetime.fromisoformat(str(row["start_at"]))
                if start.tzinfo is None:
                    start = start.replace(tzinfo=tz)
                end_raw = str(row["end_at"]).strip()
                end = (
                    datetime.fromisoformat(end_raw)
                    if end_raw
                    else start + _LISTING_DURATION
                )
                if end.tzinfo is None:
                    end = end.replace(tzinfo=tz)
                if end <= start:
                    conn.execute("ROLLBACK")
                    raise ValueError("event must end after it starts")

                event_id = (
                    "builder-evt-"
                    + hashlib.sha256(draft_id.encode()).hexdigest()[:12]
                )
                serial = int(
                    hashlib.sha256(draft_id.encode()).hexdigest()[:12], 16
                ) % 10_000_000_000
                slug = f"{_slugify(title)}-tickets-{serial:010d}"
                collision = conn.execute(
                    "SELECT id FROM events WHERE slug=?", (slug,)
                ).fetchone()
                if collision is not None and collision["id"] != event_id:
                    slug = f"{_slugify(title)}-tickets-{(serial + 1):010d}"

                account = conn.execute(
                    "SELECT display_name FROM accounts WHERE slug=?", (owner,)
                ).fetchone()
                organizer_name = str(row["organizer_name"]).strip() or (
                    account["display_name"] if account else owner.title()
                )
                organizer_identity = (
                    f"{owner}|{organizer_name}"
                    if str(row["organizer_name"]).strip()
                    else owner
                )
                organizer_id = "org-builder-" + hashlib.sha256(
                    organizer_identity.encode()
                ).hexdigest()[:10]
                conn.execute(
                    "INSERT OR IGNORE INTO organizers "
                    "(id, name, slug, hosting_since, follower_count) "
                    "VALUES (?,?,?,?,0)",
                    (organizer_id, organizer_name,
                     _slugify(organizer_name), FROZEN_TODAY.isoformat()),
                )

                if row["location_type"] == "online":
                    platform = str(row["online_platform"]).strip()
                    venue, address, city = (
                        "Online event",
                        f"Online ({platform})" if platform else "Online",
                        "",
                    )
                elif row["location_type"] == "tbd":
                    venue, address, city = (
                        "Location to be announced", "To be announced", "")
                else:
                    venue = str(row["venue_name"]).strip()
                    city = str(row["venue_city"]).strip()
                    address = ", ".join(
                        part for part in
                        (str(row["venue_address"]).strip() or venue, city)
                        if part)
                place_slug = (
                    place_slug_for_city(city) if city else ""
                ) or DEFAULT_PLACE

                conn.execute(
                    "INSERT INTO events (id, slug, title, organizer_id, "
                    "venue, address, city, timezone, synthetic, recurrence, "
                    "hero, hero_2x, avatar, map_asset, overview, "
                    "category_slug, format_slug, is_online) "
                    "VALUES (?,?,?,?,?,?,?,?,1,NULL,?,?,NULL,NULL,?,?,"
                    "'other',?)",
                    (
                        event_id, slug, title, organizer_id, venue, address,
                        city or "Los Angeles, CA", tz_name,
                        self._builder_hero(str(row["image_ref"])),
                        self._builder_hero(str(row["image_ref"])),
                        str(row["overview"]).strip()
                        or str(row["summary"]).strip()
                        or str(row["description"]).strip(),
                        str(row["category_slug"]) or "other",
                        1 if row["location_type"] == "online" else 0,
                    ),
                )
                occurrence_id = f"{event_id}-occ"
                conn.execute(
                    "INSERT INTO occurrences (id, event_id, start_at, "
                    "end_at, label) VALUES (?,?,?,?,?)",
                    (occurrence_id, event_id, start.isoformat(),
                     end.isoformat(), _listing_label(start, end, tz_name)),
                )
                sales_open = datetime(2026, 1, 1, tzinfo=tz).isoformat()
                for ticket in tickets:
                    conn.execute(
                        "INSERT INTO ticket_classes (occurrence_id, name, "
                        "price_cents, capacity, per_order_max, "
                        "sales_start_at, sales_end_at, version, currency, "
                        "sold_baseline, rank) VALUES (?,?,?,?,?,?,?,1,"
                        "'usd',0,?)",
                        (
                            occurrence_id,
                            ticket["name"],
                            int(ticket["price_cents"]),
                            int(ticket["quantity"]),
                            int(ticket["per_order_max"]),
                            str(ticket["sales_start_at"]) or sales_open,
                            str(ticket["sales_end_at"]) or start.isoformat(),
                            int(ticket["rank"]),
                        ),
                    )
                # Feed slots: newly published events lead their city feed
                # (rank below the current minimum sorts first) and join the
                # geography chain so metro/country pages list them too.
                min_rank = conn.execute(
                    "SELECT COALESCE(MIN(rank), 0) AS r FROM event_placements"
                    " WHERE place_slug=? AND source='publication'",
                    (place_slug,),
                ).fetchone()
                conn.execute(
                    "INSERT OR IGNORE INTO event_placements "
                    "(place_slug, event_id, rank, source, badge) "
                    "VALUES (?,?,?,'publication','Just added')",
                    (place_slug, event_id, int(min_rank["r"]) - 1),
                )
                parent_of = {p[0]: p[5] for p in seed_places()}
                geo_rank = int(
                    hashlib.sha256(event_id.encode()).hexdigest()[:6], 16
                ) * -1
                scope: str | None = place_slug
                while scope:
                    conn.execute(
                        "INSERT OR IGNORE INTO event_placements "
                        "(place_slug, event_id, rank, source, badge) "
                        "VALUES (?,?,?,'geography','')",
                        (scope, event_id, geo_rank),
                    )
                    geo_rank += 1
                    scope = parent_of.get(scope)

                version = current + 1
                conn.execute(
                    "UPDATE organizer_event_drafts SET status='published', "
                    "published_event_id=?, version=?, updated_seq=? "
                    "WHERE id=?",
                    (event_id, version, version, draft_id),
                )
                self._builder_record(
                    conn, owner=owner, key=idempotency_key, digest=digest,
                    operation="publish", draft_id=draft_id,
                    expected_version=expected_version,
                    prior_version=current, version=version,
                    canonical_result=f"event:{event_id}:published",
                )
                conn.execute("COMMIT")
                return {
                    "outcome": "published",
                    "event_id": event_id,
                    "slug": slug,
                    "version": version,
                }
            except (CommandConflict, StaleVersion, PermissionError, ValueError):
                try:
                    conn.execute("ROLLBACK")
                except sqlite3.OperationalError:
                    pass
                raise
            except Exception:
                try:
                    conn.execute("ROLLBACK")
                except sqlite3.OperationalError:
                    pass
                raise

    def builder_unpublish(
        self,
        draft_id: str,
        owner: str,
        *,
        expected_version: int,
        idempotency_key: str,
    ) -> tuple[int, str]:
        """Take a published builder event off the catalog (delete listing
        rows, flip the draft back to draft status)."""
        digest = hashlib.sha256(
            f"unpublish|{draft_id}|{expected_version}".encode()
        ).hexdigest()
        with self._lock:
            conn = self.connect()
            try:
                conn.execute("BEGIN IMMEDIATE")
                replayed = self._builder_replay(
                    conn, owner, idempotency_key, digest)
                row = self._builder_draft_row(conn, draft_id, owner)
                current = int(row["version"])
                if replayed is not None:
                    conn.execute("ROLLBACK")
                    return current, "replayed"
                if row["status"] != "published":
                    conn.execute("ROLLBACK")
                    raise ValueError("draft is not published")
                if current != expected_version:
                    conn.execute("ROLLBACK")
                    raise StaleVersion(
                        f"expected {expected_version}, current {current}"
                    )
                event_id = str(row["published_event_id"])
                if conn.execute(
                    "SELECT 1 FROM orders WHERE event_id=? LIMIT 1",
                    (event_id,),
                ).fetchone() is not None:
                    conn.execute("ROLLBACK")
                    raise CommandConflict(
                        "published event has registrations and cannot be unpublished"
                    )
                conn.execute(
                    "DELETE FROM event_placements WHERE event_id=?",
                    (event_id,))
                conn.execute("DELETE FROM events WHERE id=?", (event_id,))
                version = current + 1
                conn.execute(
                    "UPDATE organizer_event_drafts SET status='draft', "
                    "published_event_id='', version=?, updated_seq=? "
                    "WHERE id=?",
                    (version, version, draft_id),
                )
                self._builder_record(
                    conn, owner=owner, key=idempotency_key, digest=digest,
                    operation="unpublish", draft_id=draft_id,
                    expected_version=expected_version,
                    prior_version=current, version=version,
                    canonical_result=f"event:{event_id}:unpublished",
                )
                conn.execute("COMMIT")
                return version, "unpublished"
            except (CommandConflict, StaleVersion, PermissionError, ValueError):
                try:
                    conn.execute("ROLLBACK")
                except sqlite3.OperationalError:
                    pass
                raise
            except Exception:
                try:
                    conn.execute("ROLLBACK")
                except sqlite3.OperationalError:
                    pass
                raise

    def builder_discard(
        self, draft_id: str, owner: str, *, expected_version: int
    ) -> str:
        """Remove one owner-scoped draft and any public listing it produced.

        This is cleanup, not a replayable editing command: the builder command
        and version journals remain as immutable audit rows after the draft is
        gone. Uploaded images are content-addressed and may be shared, so they
        are retained until deterministic reset.
        """
        with self._lock:
            conn = self.connect()
            try:
                conn.execute("BEGIN IMMEDIATE")
                row = self._builder_draft_row(conn, draft_id, owner)
                current = int(row["version"])
                if current != expected_version:
                    conn.execute("ROLLBACK")
                    raise StaleVersion(
                        f"expected {expected_version}, current {current}"
                    )
                event_id = str(row["published_event_id"])
                if event_id:
                    if conn.execute(
                        "SELECT 1 FROM orders WHERE event_id=? LIMIT 1",
                        (event_id,),
                    ).fetchone() is not None:
                        conn.execute("ROLLBACK")
                        raise CommandConflict(
                            "published event has registrations and cannot be discarded"
                        )
                    conn.execute(
                        "DELETE FROM event_placements WHERE event_id=?",
                        (event_id,),
                    )
                    conn.execute("DELETE FROM events WHERE id=?", (event_id,))
                conn.execute(
                    "DELETE FROM organizer_event_drafts WHERE id=? AND owner=?",
                    (draft_id, owner),
                )
                conn.execute("COMMIT")
                return event_id
            except (CommandConflict, StaleVersion, PermissionError, ValueError):
                try:
                    conn.execute("ROLLBACK")
                except sqlite3.OperationalError:
                    pass
                raise
            except Exception:
                try:
                    conn.execute("ROLLBACK")
                except sqlite3.OperationalError:
                    pass
                raise

    # -- diagnostics ------------------------------------------------------------

    def table_counts(self) -> dict[str, int]:
        with self._lock:
            conn = self.connect()
            return {
                table: int(
                    conn.execute(
                        f"SELECT COUNT(*) AS n FROM {table}"
                    ).fetchone()["n"]
                )
                for table in BUSINESS_TABLES
            }


_DATABASES: dict[Path, Database] = {}
_REGISTRY_LOCK = threading.Lock()


def resolve_data_dir() -> Path:
    database_path = os.environ.get(DATABASE_PATH_ENV, "").strip()
    if database_path:
        resolved = Path(database_path).resolve()
        if resolved.name != DB_FILENAME:
            raise RuntimeError(
                "WebsiteBench Eventbrite database path has the wrong filename"
            )
        return resolved.parent
    env_value = os.environ.get(DATA_DIR_ENV, "").strip()
    if env_value:
        return Path(env_value).resolve()
    return (CLONE_ROOT.parent / "data").resolve()


def get_db() -> Database:
    """Database bound to the CURRENT data directory (resolved lazily per
    call so tests can repoint CLAWBENCH_DATA_DIR between cases)."""
    target = resolve_data_dir()
    with _REGISTRY_LOCK:
        database = _DATABASES.get(target)
        if database is None:
            database = Database(target)
            _DATABASES[target] = database
            database.prepare()
        return database


def ensure_ready() -> Database:
    return get_db()