Spaces:
Running

File size: 63,063 Bytes
d0f4815
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4c2adc3
d0f4815
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cba899b
 
 
 
 
 
 
 
 
 
d0f4815
 
ad5abd9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d0f4815
 
 
 
 
 
f843020
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d0f4815
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f843020
 
 
 
d0f4815
 
 
 
 
 
 
 
 
 
 
 
f843020
 
 
 
 
 
 
 
 
 
d0f4815
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c60f90
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d0f4815
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b723316
 
 
 
d0f4815
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80b0fbf
d0f4815
 
 
 
 
 
 
 
 
 
 
b723316
 
 
 
 
 
 
d0f4815
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80b0fbf
 
 
 
 
d0f4815
80b0fbf
d0f4815
80b0fbf
 
 
 
 
 
 
 
 
 
d0f4815
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4c2adc3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d0f4815
4c2adc3
d0f4815
 
 
4c2adc3
 
 
 
 
 
 
 
 
 
 
d0f4815
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
"""FastAPI search server for the gamer2 archive.

Run:
    uvicorn search.server:app --reload --port 8000

Endpoints:
    GET /                       โ†’ single-page UI (static/index.html)
    GET /api/search             โ†’ FTS5 search with filters & snippets
    GET /api/thread/{thread_id} โ†’ full thread (all posts in order)
    GET /api/forums             โ†’ list of forums
    GET /api/stats              โ†’ DB stats
"""

from __future__ import annotations

import os
import sqlite3
from pathlib import Path
from typing import Optional

import re
from functools import lru_cache

from bs4 import BeautifulSoup
from fastapi import FastAPI, HTTPException, Query, Request
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
from slowapi import Limiter, _rate_limit_exceeded_handler
from slowapi.errors import RateLimitExceeded
from slowapi.middleware import SlowAPIMiddleware
from slowapi.util import get_remote_address

BASE_DIR = Path(__file__).resolve().parent
DB_PATH = Path(os.environ.get("GAMER_DB", BASE_DIR / "posts.db"))
STATIC_DIR = BASE_DIR / "static"
AVATAR_DIR = Path(
    os.environ.get(
        "GAMER_AVATARS",
        BASE_DIR.parent / "gamer2" / "static" / "user_avatar",
    )
)
EMOJI_DIR = Path(
    os.environ.get(
        "GAMER_EMOJIS",
        BASE_DIR.parent / "gamer2" / "static" / "gamer" / "forum_images",
    )
)


def db():
    """Open a fresh read-only connection per request (sqlite handles concurrency fine).

    immutable=1 (not mode=ro) โ€” the DB was last written by bake_rich_html.py
    in WAL mode, which leaves it expecting to lock -shm/-wal files even on
    a "read-only" open. In the deployed Docker image posts.db lives on a
    user-non-writable mount, so any lock attempt errors with "attempt to
    write a readonly database". immutable=1 tells SQLite the file will not
    change and to skip locking entirely โ€” perfect for our use case where
    the DB is baked once at image-build time and never modified at runtime."""
    uri = f"file:{DB_PATH}?immutable=1"
    conn = sqlite3.connect(uri, uri=True, check_same_thread=False)
    conn.row_factory = sqlite3.Row
    # Best-effort perf PRAGMAs. cache_size and temp_store both attempt a
    # schema write in some SQLite builds, which fails when the DB file is
    # not user-writable (e.g. in the deployed Docker image where posts.db
    # is owned by root and we run as an unprivileged user). mmap_size is
    # the most important one โ€” it lets SQLite map the DB into the address
    # space and read pages without going through the page cache.
    for pragma in (
        "PRAGMA mmap_size = 1073741824",
        "PRAGMA cache_size = -262144",
        "PRAGMA temp_store = MEMORY",
    ):
        try:
            conn.execute(pragma)
        except sqlite3.OperationalError:
            pass
    return conn


_HEBREW_PREFIXES = ("ื”", "ื‘", "ื•", "ืœ", "ืž", "ืฉ", "ื›")
_HEBREW_LETTER_RE = re.compile(r"[ึ-ืฟ]")

# Hebrew stopwords โ€” short, ultra-common words whose postings lists are
# huge (millions of hits each). When they appear alongside other tokens
# we drop them from the FTS query so the rare tokens dominate the AND
# intersection; without this, a query like `ืื ื™ ืงื•ืคืฅ ื‘ื—ื“ืจ` had to scan
# 100k+ postings just for "ืื ื™". Users who need the literal word can
# wrap it in "double quotes" to bypass this filter.
_HEBREW_STOPWORDS = frozenset({
    # personal pronouns
    "ืื ื™", "ืืชื”", "ืืช", "ื”ื•ื", "ื”ื™ื", "ืื ื—ื ื•", "ืืชื", "ืืชืŸ", "ื”ื", "ื”ืŸ",
    # demonstratives / common particles
    "ื–ื”", "ื–ืืช", "ืืœื”", "ืืœื•", "ื›ืš", "ื›ื›ื”", "ืฉื", "ืคื”", "ื›ืืŸ",
    # prepositions / conjunctions / fillers
    "ืฉืœ", "ืขืœ", "ืขื", "ืืœ", "ื›ื™", "ืื", "ืื–", "ื’ื", "ืจืง", "ื›ืŸ", "ืœื",
    "ืื‘ืœ", "ืื•", "ื›ืœ", "ื›ืžื•", "ื™ืฉ", "ืื™ืŸ", "ื”ื™ื”", "ื”ื™ื•", "ืื—ืจ", "ืœืคื ื™",
    "ืื—ืจื™", "ื‘ื™ืŸ", "ืžื”", "ืžื™", "ืื™ืš", "ืœืžื”", "ืœื™", "ืœื•", "ืœื”", "ืœื ื•", "ืœื›ื",
})


def _is_stopword(tok: str) -> bool:
    return tok in _HEBREW_STOPWORDS


_QUOTED_RE = re.compile(r'"([^"]+)"')
_BLOCKQUOTE_OPEN_RE = re.compile(r"<blockquote\b[^>]*>", re.IGNORECASE)
_BLOCKQUOTE_CLOSE_RE = re.compile(r"</blockquote\s*>", re.IGNORECASE)
_TAG_RE = re.compile(r"<[^>]+>")
_SPECIAL_TOKEN_RE = re.compile(r"^(ื“ื™ืจื•ื’[<>=]|ืฉื ื”:|ืคื•ืจื•ื:|ื”ื•ื“ืขื”:|ื”ื›ื™:)")


def _strip_quotes_from_html(html: str) -> str:
    """Strip <blockquote>โ€ฆ</blockquote> sections (including arbitrarily
    nested ones) from baked HTML, returning the post's body text โ€” i.e.
    everything outside quoted-reply blocks.

    Uses a depth counter rather than regex matching since regex can't pair
    nested tags correctly: the outermost <blockquote> contains all the
    quote chain, so we drop everything between depth 0 โ†’ 0 transitions."""
    out: list[str] = []
    depth = 0
    i = 0
    n = len(html)
    while i < n:
        opn = _BLOCKQUOTE_OPEN_RE.search(html, i)
        cls = _BLOCKQUOTE_CLOSE_RE.search(html, i)
        if opn is None and cls is None:
            if depth == 0:
                out.append(html[i:])
            break
        if opn is not None and (cls is None or opn.start() < cls.start()):
            if depth == 0:
                out.append(html[i:opn.start()])
            depth += 1
            i = opn.end()
        else:
            depth = max(0, depth - 1)
            i = cls.end()  # type: ignore[union-attr]
    return _TAG_RE.sub(" ", "".join(out))


def _query_terms(q: str) -> list[str]:
    """Pull bare search terms out of user input โ€” quoted phrases and bare
    words, minus the structured tokens (ื“ื™ืจื•ื’>80, ืฉื ื”:2014, ...) that don't
    contribute to the FTS body match."""
    terms: list[str] = []

    def _take_phrase(m: re.Match) -> str:
        phrase = m.group(1).strip()
        if phrase:
            terms.append(phrase)
        return " "

    remainder = _QUOTED_RE.sub(_take_phrase, q)
    for tok in remainder.split():
        if _SPECIAL_TOKEN_RE.match(tok):
            continue
        tok = tok.replace('"', "").strip()
        if tok:
            terms.append(tok)
    return terms


def _term_present_in_body(body_text_lower: str, term: str) -> bool:
    """Check if a search term (or any one-letter Hebrew prefix variant of it)
    is present in body text. Mirrors the prefix-expansion that escape_fts()
    does so the body-match check stays in sync with what FTS would have
    actually matched."""
    if term.lower() in body_text_lower:
        return True
    if _HEBREW_LETTER_RE.search(term):
        for p in _HEBREW_PREFIXES:
            if (p + term).lower() in body_text_lower:
                return True
    return False


def _first_term_pos(body_lower: str, terms: list[str]) -> int:
    """Return the position of the earliest matching term in body_lower, or -1
    if none of the terms appear."""
    best = -1
    for term in terms:
        variants = [term.lower()]
        if _HEBREW_LETTER_RE.search(term):
            variants += [(p + term).lower() for p in _HEBREW_PREFIXES]
        for v in variants:
            pos = body_lower.find(v)
            if pos != -1 and (best == -1 or pos < best):
                best = pos
    return best


def _strip_quote_headers_text(text: str) -> str:
    """Strip serialized quote-header blocks from plain text content. Used as
    a fallback for posts whose HTML hasn't been baked yet โ€” without structure
    we can't tell where a quoted reply ends, but we can at least drop the
    'ื ื›ืชื‘ ืข"ื™ <user> ื‘ืชืืจื™ืš <date>' / 'ืฆื™ื˜ื•ื˜ ืฉืœ <user> ืžืชื•ืš ื”ื•ื“ืขื” ืž <date>'
    header chunks so the visible snippet is the post text itself, not the
    quote chain metadata."""
    lines = text.split("\n")
    out = []
    i = 0
    while i < len(lines):
        stripped = lines[i].strip()
        if stripped == 'ื ื›ืชื‘ ืข"ื™' and i + 2 < len(lines):
            i += 3  # skip "ื ื›ืชื‘ ืข"ื™", username, "ื‘ืชืืจื™ืš <date>"
            continue
        if stripped == "ืฆื™ื˜ื•ื˜ ืฉืœ" and i + 2 < len(lines):
            i += 3
            continue
        out.append(lines[i])
        i += 1
    return "\n".join(out)


def _build_snippet(body: str, terms: list[str], window: int = 320) -> str:
    """Build a context window centered on the first matching term. If no term
    appears in `body`, return the start of `body` (truncated)."""
    body = re.sub(r"\s+", " ", body).strip()
    if not body:
        return ""
    pos = _first_term_pos(body.lower(), terms)
    if pos == -1:
        s = body[:window]
        return s + ("โ€ฆ" if len(body) > window else "")
    half = window // 2
    start = max(0, pos - half)
    end = min(len(body), start + window)
    s = body[start:end]
    if start > 0:
        s = "โ€ฆ" + s.lstrip()
    if end < len(body):
        s = s.rstrip() + "โ€ฆ"
    return s


# Rating-bar colors that signify the top "elite positive" tiers. These have
# G <= R numerically (so the simple G>R green-dominance check excludes them)
# but in the original forum's palette they represent the highest-praise tiers
# (magenta=0x990099, olive=0x323000 โ€” both only ever paired with dsize=100).
_POSITIVE_ELITE_COLORS = (0x990099, 0x323000)
_POS_FILTER = (
    "(((p.color >> 8) & 0xFF) > ((p.color >> 16) & 0xFF) "
    f"OR p.color IN ({','.join(str(c) for c in _POSITIVE_ELITE_COLORS)}))"
)
# Sort key that puts elite colors above the green-dominant ones, breaking ties
# by dsize and recency.
_POS_ORDER = (
    "CASE p.color "
    f"WHEN {0x990099} THEN 3 "
    f"WHEN {0x323000} THEN 2 "
    "ELSE 1 END DESC, p.dsize DESC, p.created_at DESC"
)


def escape_fts(q: str) -> str:
    """Build an FTS5 MATCH expression from user input.

    Anything inside paired double-quotes is treated as an EXACT phrase
    (no prefix-letter expansion, no wildcard suffix) โ€” e.g. `"red dead"`
    matches the phrase literally.

    Outside quotes, each whitespace-separated token:
      * If it contains Hebrew, expands to an OR of variants โ€” the bare token
        plus the same token with each common one-letter prefix (ื”/ื‘/ื•/ืœ/ืž/ืฉ/ื›).
        Each variant gets a `*` suffix so suffixed forms also match
        (e.g. "ื’ื•ืžืœ" โ†’ "ื’ื•ืžืœ*" matches ื’ื•ืžืœืช/ื’ื•ืžืœื™ื, "ื”ื’ื•ืžืœ*" matches ื”ื’ื•ืžืœืช).
      * Non-Hebrew tokens get the same prefix-wildcard treatment but no
        prefix-letter expansion.

    Hebrew stopwords (ืื ื™ / ืฉืœ / ืขืœ / โ€ฆ) are dropped when there are other
    tokens โ€” their postings lists are too big to AND-intersect efficiently
    and they add no selectivity. Users who need them literally can quote.

    Quoting + bareword sanitization keeps user input safe inside the
    FTS5 MATCH grammar."""
    parts: list[str] = []

    # First, pull out quoted phrases and add them as exact FTS phrase matches.
    def _take_phrase(m: re.Match) -> str:
        phrase = m.group(1).replace('"', "").strip()
        if phrase:
            parts.append(f'"{phrase}"')
        return " "
    remainder = _QUOTED_RE.sub(_take_phrase, q)

    # Two-pass over bare tokens so we know if we have non-stopword content
    # before deciding whether to drop the stopwords.
    raw_tokens = [t.replace('"', "").strip() for t in remainder.split()]
    bare_tokens = [t for t in raw_tokens if t]
    non_stop = [t for t in bare_tokens if not _is_stopword(t)]
    # Drop stopwords only if at least one non-stopword survives โ€” otherwise
    # a query like just "ืื ื™" would return no results at all.
    tokens = non_stop if non_stop else bare_tokens

    for tok in tokens:
        if _HEBREW_LETTER_RE.search(tok):
            variants = [tok]
            for p in _HEBREW_PREFIXES:
                if not tok.startswith(p):
                    variants.append(p + tok)
            ored = " OR ".join(f'"{v}"*' for v in variants)
            parts.append(f"({ored})")
        else:
            parts.append(f'"{tok}"*')
    return " AND ".join(parts) if parts else ""


app = FastAPI(title="gamer2 archive search")

# ---------- rate limiting ----------
# Per-IP sliding-window limits, applied to every route via SlowAPIMiddleware.
# 120/min is generous for normal interactive use (~2 req/sec); trips on abuse.
limiter = Limiter(key_func=get_remote_address, default_limits=["120/minute"])
app.state.limiter = limiter
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
app.add_middleware(SlowAPIMiddleware)


# ---------- rich HTML extraction (on-demand from source files) ----------

# Tags we keep when serving the rich representation. Everything else is stripped
# (its contents survive). We keep blockquote so the forum-style quote rendering
# works, formatting tags for fidelity, and br/p for layout.
_ALLOWED_TAGS = {
    "blockquote", "b", "strong", "i", "em", "u",
    "p", "br", "hr",
    "div", "span", "font",
    "ul", "ol", "li",
    "table", "tr", "td", "th",
    "img", "a",
}
_ALLOWED_ATTRS = {
    "a": {"href", "title"},
    "img": {"src", "alt", "width", "height", "title"},
    "div": {"dir", "style", "class"},
    "span": {"dir", "style"},
    "font": {"color", "face", "size"},
    "p": {"dir"},
    "blockquote": {"dir", "data-quote-author", "data-quote-time"},
}
_SCRIPT_TAGS = {"script", "style", "noscript", "iframe", "object", "embed"}

# Within a `style` attribute, only these CSS properties are kept. Anything
# else (position:fixed overlays, transform tricks, url() expressions, etc.)
# is dropped.
_ALLOWED_CSS_PROPS = {"background-color", "color"}
_CSS_DECL_RE = re.compile(r"([a-zA-Z-]+)\s*:\s*([^;]+)")


def _sanitize_style(value: str) -> str:
    """Keep only allowlisted CSS properties; drop anything else."""
    out = []
    for m in _CSS_DECL_RE.finditer(value or ""):
        prop = m.group(1).strip().lower()
        val = m.group(2).strip()
        if prop not in _ALLOWED_CSS_PROPS:
            continue
        # Defensive: reject any value containing url() / expression() /
        # javascript: in case a weird future browser tries to execute it.
        low = val.lower()
        if "url(" in low or "expression(" in low or "javascript:" in low:
            continue
        out.append(f"{prop}: {val}")
    return "; ".join(out)

_REPLY_PATTERN = re.compile(r"^Reply(\d+)$")
# Quote headers come in two flavors:
#   "ืฆื™ื˜ื•ื˜ ืฉืœ <b>NICK</b> ืžืชื•ืš ื”ื•ื“ืขื” ืž YYYY-MM-DD HH:MM:SS"
#   "ื ื›ืชื‘ ืข"ื™ <a href=...>NICK</a> ื‘ืชืืจื™ืš YYYY-MM-DD HH:MM:SS"
_QUOTE_HEADER_RES = [
    re.compile(r"ืฆื™ื˜ื•ื˜ ืฉืœ\s*(?:<[^>]+>)?\s*(?P<nick>[^<\n]+?)\s*(?:</[^>]+>)?\s*ืžืชื•ืš ื”ื•ื“ืขื” ืž\s*(?P<ts>\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2})"),
    re.compile(r"ื ื›ืชื‘ ืข\"ื™\s*(?:<[^>]+>)?\s*(?P<nick>[^<\n]+?)\s*(?:</[^>]+>)?\s*ื‘ืชืืจื™ืš\s*(?P<ts>\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2})"),
]
# rewrite gamer-hosted asset urls to our local mounts
_EMOJI_URL_RE = re.compile(r"https?://[^/]*gamer[^/]*/(?:gamer/)?forum_images/([^\"' >]+)")
_AVATAR_URL_RE = re.compile(r"(?:https?://[^/]*gamer[^/]*/)?(?:\.\./)*user_avatar/(user\d+\.jpg)", re.I)


def _rewrite_asset_url(src: str) -> str:
    if not src:
        return src
    m = _EMOJI_URL_RE.search(src)
    if m:
        return "/forum_emojis/" + m.group(1)
    m = _AVATAR_URL_RE.search(src)
    if m:
        return "/avatars/" + m.group(1)
    return src


def _annotate_quote_blocks(soup, node):
    """Normalize <blockquote> structure and tag with data-quote-author/time.

    Forum blockquotes come in two flavors:
      Old (2004-2007):
          <blockquote><div>ืฆื™ื˜ื•ื˜ ืฉืœ X ืžืชื•ืš ื”ื•ื“ืขื” ืž DATE</div><hr/><div>body</div></blockquote>
      Newer (2010+):
          <blockquote>ื ื›ืชื‘ ืข"ื™ <a>X</a> ื‘ืชืืจื™ืš DATE<hr/>body<hr/></blockquote>
      (children are raw text/anchors, separated by <hr/>, no wrapping divs)

    We split each blockquote at the FIRST <hr/>, wrap the head in
    <div class="quote-head"> and the rest in <div class="quote-body">, and
    drop the separators. That gives the client a single, predictable
    structure to style and to handle clicks on (jump-to-quoted-post)."""
    from bs4 import NavigableString
    for bq in list(node.find_all("blockquote")):
        children = list(bq.children)
        # find first <hr> separator (or fall back: no split, treat first
        # text/inline run as head)
        split_idx = None
        for i, ch in enumerate(children):
            if getattr(ch, "name", None) == "hr":
                split_idx = i
                break
        if split_idx is None:
            head_children = []
            body_children = children
        else:
            head_children = children[:split_idx]
            body_children = children[split_idx + 1 :]

        # Strip a trailing <hr/> from the body (closing separator in new format)
        while body_children and getattr(body_children[-1], "name", None) == "hr":
            body_children = body_children[:-1]

        # Extract author+time from head text (works for either format)
        head_html = "".join(
            (c.decode() if hasattr(c, "decode") else str(c)) for c in head_children
        )
        nick = ts = None
        for pat in _QUOTE_HEADER_RES:
            m = pat.search(head_html)
            if m:
                nick = m.group("nick").strip()
                ts = m.group("ts").strip()
                break

        # Rebuild: <blockquote><div class="quote-head">โ€ฆ</div><div class="quote-body">โ€ฆ</div></blockquote>
        bq.clear()
        if nick:
            bq["data-quote-author"] = nick
        if ts:
            bq["data-quote-time"] = ts

        head_div = soup.new_tag("div")
        head_div["class"] = "quote-head"
        for c in head_children:
            if getattr(c, "name", None) == "hr":
                continue
            head_div.append(c.extract() if hasattr(c, "extract") else NavigableString(str(c)))
        if len(list(head_div.children)) or nick:
            bq.append(head_div)

        body_div = soup.new_tag("div")
        body_div["class"] = "quote-body"
        for c in body_children:
            body_div.append(c.extract() if hasattr(c, "extract") else NavigableString(str(c)))
        bq.append(body_div)


def _sanitize(node):
    """In-place sanitization: drop disallowed tags & attributes; unwrap the rest."""
    for tag in list(node.find_all(True)):
        # An ancestor may have been decomposed in a prior iteration โ€” skip
        # detached nodes to avoid BS4's "not part of a tree" ValueError.
        if tag.parent is None:
            continue
        if tag.name in _SCRIPT_TAGS:
            tag.decompose()
            continue
        if tag.name not in _ALLOWED_TAGS:
            try:
                tag.unwrap()
            except ValueError:
                pass
            continue
        allowed = _ALLOWED_ATTRS.get(tag.name, set())
        for attr in list(tag.attrs.keys()):
            if attr not in allowed:
                del tag.attrs[attr]
        # neuter javascript: links
        if tag.name == "a":
            href = tag.attrs.get("href", "")
            if href.lower().startswith(("javascript:", "data:")):
                tag.attrs["href"] = "#"
        # rewrite gamer-hosted asset URLs to our local mounts
        if tag.name == "img" and "src" in tag.attrs:
            tag.attrs["src"] = _rewrite_asset_url(tag.attrs["src"])
        # tighten style attributes to a CSS allowlist (kills overlay/expr risks)
        if "style" in tag.attrs:
            cleaned = _sanitize_style(tag.attrs["style"])
            if cleaned:
                tag.attrs["style"] = cleaned
            else:
                del tag.attrs["style"]


def _sibling_page_files(file_path: str) -> list:
    """Given any one of the (possibly paginated) HTML files for a thread,
    return all sibling files for that thread on disk.

    Threads in batches 70-100 are split into 'replieslist.php@TopicID=N',
    'replieslist.php@TopicID=N&page=1', '...&page=2', etc. We need all of
    them to render rich HTML for every post."""
    if not file_path:
        return []
    p = Path(file_path)
    m = re.search(r"TopicID=(\d+)", p.name)
    if not m:
        return [file_path]
    tid = m.group(1)
    # match the base file and all &page=N siblings
    pattern = re.compile(rf"TopicID={tid}(?:&page=\d+)?$|TopicID={tid}&|TopicID={tid}\Z")
    siblings = []
    try:
        for entry in os.scandir(p.parent):
            if entry.is_file() and pattern.search(entry.name):
                siblings.append(str(Path(entry.path)))
    except OSError:
        return [file_path]
    return siblings or [file_path]


@lru_cache(maxsize=64)
def _parse_thread_html(file_path: str):
    """Returns dict[post_id] -> sanitized rich HTML string. Cached by file path
    since one file holds an entire thread; opening a post then the thread of
    that post would otherwise parse the same file twice."""
    out = {}
    try:
        with open(file_path, "rb") as f:
            soup = BeautifulSoup(f, "html5lib")
    except FileNotFoundError:
        return out
    for div in soup.find_all("div", id=_REPLY_PATTERN):
        m = _REPLY_PATTERN.match(div["id"])
        if not m:
            continue
        pid = int(m.group(1))
        _annotate_quote_blocks(soup, div)
        _sanitize(div)
        # decode_contents returns the inner HTML
        html = div.decode_contents()
        # strip the spammed "Eliran Pe'er" link
        html = html.replace(
            "<a href=\"http://cookiesession.com/ืขืœื™ื ื•/ืืœื™ืจืŸ-ืคืืจ/\">Eliran Pe'er ืืœื™ืจืŸ ืคืืจ</a>",
            "",
        )
        # rewrite relative avatar/file urls? keep as-is for now.
        out[pid] = html
    return out


def _post_html(file_path: str, post_id: int):
    return _parse_thread_html(file_path).get(post_id, "")


def _search_threads(conn, q, forum, author, date_from, date_to, sort, limit, offset, cursor=None):
    """Thread-scoped search. Matches the thread title (LIKE) and shows
    aggregated stats (first/last post, post count). Author/date filters are
    applied at the post level โ€” a thread is included only if it has matching
    posts under those filters."""
    cur = conn.cursor()

    # Date filters operate at post level (thread included if it has any post
    # in the date range). Author filter is special โ€” in thread scope it means
    # "threads opened by this user", i.e. the user wrote the first post.
    post_filters = ["1=1"]
    post_params: list = []
    if date_from:
        post_filters.append("p.created_at >= ?")
        post_params.append(date_from)
    if date_to:
        post_filters.append("p.created_at < ?")
        post_params.append(date_to)

    thread_filters = []
    thread_params: list = []
    if q:
        # Tokenize the title query like escape_fts does: quoted phrases stay
        # as single substrings; bare tokens are AND-ed individually so word
        # order and gaps don't matter (a query like `ืื ื™ ืงื•ืคืฅ ื‘ื—ื“ืจ` matches
        # a title `ืื ื™ ืงื•ืคืฅ ืขื›ืฉื™ื• ื‘ื—ื“ืจ`). Drop stopwords so they don't add
        # selectivity-free LIKEs.
        like_terms: list[str] = []
        def _take(m: re.Match) -> str:
            phrase = m.group(1).replace('"', "").strip()
            if phrase:
                like_terms.append(phrase)
            return " "
        remainder = _QUOTED_RE.sub(_take, q)
        bare = [t.replace('"', "").strip() for t in remainder.split() if t.strip()]
        non_stop = [t for t in bare if not _is_stopword(t)]
        like_terms.extend(non_stop if non_stop else bare)
        if not like_terms:
            like_terms.append(q)  # fallback (shouldn't trigger in practice)
        for term in like_terms:
            thread_filters.append("t.name LIKE ?")
            thread_params.append(f"%{term}%")
    if forum is not None:
        thread_filters.append("t.forum_id = ?")
        thread_params.append(forum)

    if date_from or date_to:
        thread_filters.append(
            f"t.id IN (SELECT p.thread_id FROM posts p WHERE {' AND '.join(post_filters)})"
        )
        thread_params.extend(post_params)

    if author is not None:
        # Uses materialized t.first_author_id (set by build_index / maintenance)
        thread_filters.append("t.first_author_id = ?")
        thread_params.append(author)

    # Cursor pagination (O(1) for next/prev) โ€” relies on the materialized
    # t.first_post_at column.
    if cursor and sort in ("newest", "oldest"):
        try:
            c_at, c_id = cursor.rsplit("|", 1)
            c_id = int(c_id)
            cmp = "<" if sort == "newest" else ">"
            thread_filters.append(f"(t.first_post_at, t.id) {cmp} (?, ?)")
            thread_params.append(c_at)
            thread_params.append(c_id)
        except ValueError:
            pass

    where = " AND ".join(thread_filters) if thread_filters else "1=1"

    order = {
        "newest": "t.first_post_at DESC, t.id DESC",
        "oldest": "t.first_post_at ASC,  t.id ASC",
        "relevance": "t.post_count DESC, t.first_post_at DESC",
    }[sort]

    sql = f"""
        SELECT
            t.id, t.name, t.forum_id, t.archive,
            f.name AS forum_name,
            t.first_post_at AS first_post,
            t.last_post_at  AS last_post,
            t.post_count    AS post_count,
            t.first_author_id,
            u.nick AS first_author_nick,
            (SELECT substr(p.content, 1, 200) FROM posts p
              WHERE p.thread_id = t.id ORDER BY p.idx LIMIT 1) AS first_excerpt
        FROM threads t
        LEFT JOIN forums f ON f.id = t.forum_id
        LEFT JOIN users  u ON u.id = t.first_author_id
        WHERE {where}
        ORDER BY {order}
        LIMIT ? OFFSET ?
    """
    effective_offset = 0 if cursor else offset
    rows = cur.execute(sql, thread_params + [limit, effective_offset]).fetchall()
    if cursor:
        total = -1
    else:
        total = cur.execute(
            f"SELECT COUNT(*) FROM threads t WHERE {where}", thread_params
        ).fetchone()[0]
    rds = [dict(r) for r in rows]
    next_cursor = prev_cursor = None
    if rds and sort in ("newest", "oldest"):
        first = rds[0]; last = rds[-1]
        prev_cursor = f"{first.get('first_post') or ''}|{first.get('id') or 0}"
        next_cursor = f"{last.get('first_post') or ''}|{last.get('id') or 0}"
    return {
        "scope": "threads",
        "total": total,
        "limit": limit,
        "offset": offset,
        "next_cursor": next_cursor,
        "prev_cursor": prev_cursor,
        "results": rds,
    }


@app.get("/api/search")
def search(
    q: str = Query("", description="Search query (FTS5)"),
    scope: str = Query("posts", pattern="^(posts|threads)$"),
    forum: Optional[int] = Query(None),
    author: Optional[int] = Query(None),
    date_from: Optional[str] = Query(None, description="ISO date, inclusive"),
    date_to: Optional[str] = Query(None, description="ISO date, exclusive"),
    sort: str = Query("newest", pattern="^(relevance|newest|oldest|top_rated|top_hated)$"),
    limit: int = Query(30, ge=1, le=100),
    offset: int = Query(0, ge=0),
    cursor: Optional[str] = Query(None, description="Stable cursor 'created_at|id' for O(1) next/prev pagination"),
    rating_min: Optional[int] = Query(None, ge=0, le=100, description="Post star-rating bar fill %, lower bound (inclusive)"),
    rating_max: Optional[int] = Query(None, ge=0, le=100, description="Post star-rating bar fill %, upper bound (inclusive)"),
    idx: Optional[int] = Query(None, ge=1, description="Post index within thread (1 = first post)"),
):
    q = (q or "").strip()
    conn = db()
    try:
        if scope == "threads":
            return _search_threads(conn, q, forum, author, date_from, date_to, sort, limit, offset, cursor)
        cur = conn.cursor()

        # ------- Branch 1: text search โ†’ use FTS5 -------
        if q:
            fts_q = escape_fts(q)
            where = ["posts_fts MATCH ?"]
            params: list = [fts_q]
            join_filters = []
            if forum is not None:
                join_filters.append("t.forum_id = ?")
                params.append(forum)
            if author is not None:
                join_filters.append("p.author_id = ?")
                params.append(author)
            if date_from:
                join_filters.append("p.created_at >= ?")
                params.append(date_from)
            if date_to:
                join_filters.append("p.created_at < ?")
                params.append(date_to)
            if rating_min is not None:
                join_filters.append("p.dsize >= ?")
                params.append(rating_min)
            if rating_max is not None:
                join_filters.append("p.dsize <= ?")
                params.append(rating_max)
            if idx is not None:
                join_filters.append("p.idx = ?")
                params.append(idx)

            # Cursor pagination โ€” O(1) next/prev instead of slow OFFSET.
            # Cursor format: "created_at|post_id" (post_id breaks ties for
            # rows with equal created_at).
            if cursor and sort in ("newest", "oldest"):
                try:
                    c_at, c_id = cursor.rsplit("|", 1)
                    c_id = int(c_id)
                    cmp = "<" if sort == "newest" else ">"
                    join_filters.append(f"(p.created_at, p.id) {cmp} (?, ?)")
                    params.append(c_at)
                    params.append(c_id)
                except ValueError:
                    pass

            order = {
                "relevance": "rank",
                "newest": "p.created_at DESC, p.id DESC",
                "oldest": "p.created_at ASC, p.id ASC",
            }[sort]

            # The original forum's star bar encodes vote direction in the BAR
            # COLOR โ€” green-ish = liked, brown-ish = hated. dsize alone doesn't
            # distinguish them, so for top_rated/top_hated we (a) filter by
            # color channel sign (G byte vs R byte) and (b) sort by dsize.
            if sort == "top_rated":
                join_filters.append(_POS_FILTER)
                join_filters.append("p.dsize > 0")
            elif sort == "top_hated":
                join_filters.append("((p.color >> 16) & 0xFF) > ((p.color >> 8) & 0xFF)")
                join_filters.append("p.dsize > 0")
            order_indexed = {
                "relevance": "p.created_at DESC, p.id DESC",  # FTS rank doesn't apply with this plan
                "newest":    "p.created_at DESC, p.id DESC",
                "oldest":    "p.created_at ASC,  p.id ASC",
                "top_rated": _POS_ORDER,
                "top_hated": "p.dsize DESC, p.created_at DESC",
            }[sort]
            sql = f"""
                SELECT
                    p.id AS post_id,
                    p.thread_id,
                    p.author_id,
                    p.idx,
                    p.created_at,
                    p.color AS post_color,
                    p.dsize AS post_dsize,
                    p.rank_desc, p.rank_color, p.rank_dsize,
                    t.name AS thread_name,
                    t.forum_id,
                    f.name AS forum_name,
                    u.nick AS author_nick,
                    u.location AS author_location,
                    u.messagecount AS author_messagecount,
                    substr(p.content, 1, 320) AS snippet,
                    p.content_html AS _content_html,
                    t.file_path AS _file_path,
                    t.name AS title_snippet
                FROM posts p INDEXED BY posts_created
                JOIN threads t ON t.id = p.thread_id
                LEFT JOIN forums f ON f.id = t.forum_id
                LEFT JOIN users  u ON u.id = p.author_id
                WHERE p.id IN (SELECT rowid FROM posts_fts WHERE {" AND ".join(where)})
                  {(' AND ' + ' AND '.join(join_filters)) if join_filters else ''}
                ORDER BY {order_indexed}
                LIMIT ? OFFSET ?
            """
            effective_offset = 0 if cursor else offset
            # Over-fetch so we can tier-sort (body match > unknown > quote-only)
            # across a larger window than one page. Without this, quote-only
            # hits on page N stay on page N even though direct hits exist
            # right behind them in natural order.
            fetch_limit = limit * 3 if sort in ("newest", "oldest", "relevance") else limit
            rows = cur.execute(sql, params + [fetch_limit, effective_offset]).fetchall()

            # COUNT is expensive when filters apply (full join scan). Skip on
            # cursor pages; cap at 10001 otherwise so "584K matches" doesn't
            # take seconds. Also skip for top_rated/top_hated โ€” the color
            # expression forces a per-row scan and pushes COUNT into multi-
            # second territory even with the cap. UI shows "โ€”" for total=-1.
            if cursor or sort in ("top_rated", "top_hated"):
                total = -1
            else:
                count_params = list(params)
                count_sql = f"""
                    SELECT COUNT(*) FROM (
                      SELECT 1 FROM posts_fts
                      JOIN posts   p ON p.id = posts_fts.rowid
                      JOIN threads t ON t.id = p.thread_id
                      WHERE {" AND ".join(where + join_filters)}
                      LIMIT 10001
                    )
                """
                total = cur.execute(count_sql, count_params).fetchone()[0]

        # ------- Branch 2: no text search โ†’ metadata filter only -------
        else:
            where = ["1=1"]
            params = []
            if forum is not None:
                where.append("t.forum_id = ?")
                params.append(forum)
            if author is not None:
                where.append("p.author_id = ?")
                params.append(author)
            if date_from:
                where.append("p.created_at >= ?")
                params.append(date_from)
            if date_to:
                where.append("p.created_at < ?")
                params.append(date_to)
            if rating_min is not None:
                where.append("p.dsize >= ?")
                params.append(rating_min)
            if rating_max is not None:
                where.append("p.dsize <= ?")
                params.append(rating_max)
            if idx is not None:
                where.append("p.idx = ?")
                params.append(idx)

            if cursor and sort in ("newest", "oldest"):
                try:
                    c_at, c_id = cursor.rsplit("|", 1)
                    c_id = int(c_id)
                    cmp = "<" if sort == "newest" else ">"
                    where.append(f"(p.created_at, p.id) {cmp} (?, ?)")
                    params.append(c_at)
                    params.append(c_id)
                except ValueError:
                    pass

            # See notes above: rating bar color encodes vote direction
            if sort == "top_rated":
                where.append(_POS_FILTER)
                where.append("p.dsize > 0")
            elif sort == "top_hated":
                where.append("((p.color >> 16) & 0xFF) > ((p.color >> 8) & 0xFF)")
                where.append("p.dsize > 0")

            order = {
                "oldest":    "p.created_at ASC,  p.id ASC",
                "top_rated": _POS_ORDER,
                "top_hated": "p.dsize DESC, p.created_at DESC",
            }.get(sort, "p.created_at DESC, p.id DESC")

            sql = f"""
                SELECT
                    p.id AS post_id, p.thread_id, p.author_id, p.idx, p.created_at,
                    p.color AS post_color, p.dsize AS post_dsize,
                    p.rank_desc, p.rank_color, p.rank_dsize,
                    t.name AS thread_name, t.forum_id, f.name AS forum_name,
                    u.nick AS author_nick,
                    u.location AS author_location,
                    u.messagecount AS author_messagecount,
                    substr(p.content, 1, 280) AS snippet,
                    p.content_html AS _content_html,
                    t.name AS title_snippet
                FROM posts p
                JOIN threads t ON t.id = p.thread_id
                LEFT JOIN forums f ON f.id = t.forum_id
                LEFT JOIN users  u ON u.id = p.author_id
                WHERE {" AND ".join(where)}
                ORDER BY {order}
                LIMIT ? OFFSET ?
            """
            effective_offset = 0 if cursor else offset
            rows = cur.execute(sql, params + [limit, effective_offset]).fetchall()
            # Skip COUNT for cursor pages, and also for the rating sorts โ€”
            # top_rated/top_hated need to scan every row in the date range
            # (or whole table) to evaluate the color expression, which can
            # take 5+ s on cold pages. The user gets the visible page in
            # ~200 ms; an exact result count isn't worth the wait. UI shows
            # "โ€”" when total is -1.
            if cursor or sort in ("top_rated", "top_hated"):
                total = -1
            else:
                total = cur.execute(
                    f"""SELECT COUNT(*) FROM (
                        SELECT 1 FROM posts p JOIN threads t ON t.id=p.thread_id
                        WHERE {' AND '.join(where)} LIMIT 10001
                    )""",
                    params,
                ).fetchone()[0]

        result_dicts = [dict(r) for r in rows]

        # Quote-only detection + snippet rebuild: for results that have baked
        # HTML, strip the <blockquote> reply blocks to isolate the post's own
        # body. If any search term appears there, the match is "in body" and
        # the snippet is rebuilt as a window around that term. Otherwise the
        # match was purely on quoted text โ€” the snippet shows the start of
        # the actual reply (not the quote header) and the quote-only flag is
        # set. For unbaked posts we fall back to a heuristic plaintext strip
        # that removes 'ื ื›ืชื‘ ืข"ื™โ€ฆ' / 'ืฆื™ื˜ื•ื˜ ืฉืœโ€ฆ' header chunks, so the snippet
        # at least isn't the quote-chain metadata.
        if q:
            terms = _query_terms(q)
            for d in result_dicts:
                html = d.pop("_content_html", None) or ""
                d.pop("_file_path", None)
                if not terms:
                    d["match_in_body"] = None
                    continue
                if html:
                    body = _strip_quotes_from_html(html)
                    if not body.strip():
                        d["match_in_body"] = False
                        continue
                    d["match_in_body"] = any(
                        _term_present_in_body(body.lower(), t) for t in terms
                    )
                    snippet = _build_snippet(body, terms)
                    if snippet:
                        d["snippet"] = snippet
                else:
                    # Unbaked: best-effort header strip on the substr-based
                    # content snippet. We can't reliably tell quote vs body
                    # from plain text, so match_in_body stays unknown.
                    d["match_in_body"] = None
                    raw = d.get("snippet") or ""
                    if raw:
                        cleaned = _strip_quote_headers_text(raw).strip()
                        if cleaned:
                            d["snippet"] = _build_snippet(cleaned, terms)
        else:
            # No search term โ€” still rebuild snippets from the post body when
            # we have baked HTML, so author-filter / sort-only views don't
            # show "ื ื›ืชื‘ ืข"ื™ X ื‘ืชืืจื™ืšโ€ฆ" quote headers as the snippet. With no
            # query there's nothing to highlight or center on; we just take
            # the start of the non-quoted body.
            for d in result_dicts:
                html = d.pop("_content_html", None) or ""
                d.pop("_file_path", None)
                if html:
                    body = _strip_quotes_from_html(html).strip()
                    if body:
                        d["snippet"] = _build_snippet(body, terms=[])
                else:
                    raw = d.get("snippet") or ""
                    if raw:
                        cleaned = _strip_quote_headers_text(raw).strip()
                        if cleaned:
                            d["snippet"] = _build_snippet(cleaned, terms=[])

        # Cursor advances by `limit` natural rows per page, NOT by the full
        # over-fetched window. Otherwise pages 2+ would skip rows the user
        # never saw โ€” and short result sets (total < over-fetch) would have
        # an "empty page 2" because page 1's cursor jumped past the end. The
        # over-fetch gives the tier sort a wider candidate pool; pagination
        # still walks the natural-order match set in `limit`-sized strides.
        next_cursor = prev_cursor = None
        if result_dicts and sort in ("newest", "oldest"):
            first = result_dicts[0]
            cursor_row = result_dicts[min(limit, len(result_dicts)) - 1]
            prev_cursor = f"{first.get('created_at') or ''}|{first.get('post_id') or first.get('id') or 0}"
            next_cursor = f"{cursor_row.get('created_at') or ''}|{cursor_row.get('post_id') or cursor_row.get('id') or 0}"

        # Tier sort: confirmed quote-only (false) sinks to the bottom of the
        # over-fetch window; everything else โ€” confirmed body match AND
        # unknown/unbaked โ€” stays in the SQL's natural sort order. This
        # preserves "newest = newest" semantics while still pushing posts
        # we've *proven* are quote-only matches to the bottom.
        if q:
            result_dicts.sort(key=lambda d: 1 if d.get("match_in_body") is False else 0)
        result_dicts = result_dicts[:limit]
        return {
            "scope": "posts",
            "total": total,
            "limit": limit,
            "offset": offset,
            "next_cursor": next_cursor,
            "prev_cursor": prev_cursor,
            "results": result_dicts,
        }
    finally:
        conn.close()


@app.get("/api/find_post_by_quote")
def find_post_by_quote(nick: str = Query(...), time: str = Query(...)):
    """Resolve a quoted-post reference (nick + timestamp from a quote header)
    to a concrete post id, so the UI can jump to the quoted message."""
    # The quote header timestamp uses local time without a TZ ('2005-01-08 14:50:34'),
    # while we stored ISO with +03:00 offset. Match on the YYYY-MM-DDTHH:MM:SS prefix.
    iso_prefix = time.replace(" ", "T")
    conn = db()
    try:
        cur = conn.cursor()
        row = cur.execute(
            """
            SELECT p.id AS post_id, p.thread_id, p.idx, u.nick
            FROM posts p
            JOIN users u ON u.id = p.author_id
            WHERE u.nick = ?
              AND p.created_at LIKE ? || '%'
            LIMIT 1
            """,
            (nick, iso_prefix),
        ).fetchone()
        if not row:
            return {"found": False}
        return {"found": True, **dict(row)}
    finally:
        conn.close()


@app.get("/api/post/{post_id}")
def get_post(post_id: int, bare: bool = Query(False, description="Skip rich-HTML parsing (faster for list views)")):
    conn = db()
    try:
        cur = conn.cursor()
        row = cur.execute(
            """
            SELECT p.id, p.idx, p.created_at, p.content, p.content_html,
                   p.thread_id,
                   p.color AS post_color, p.dsize AS post_dsize,
                   p.rank_desc, p.rank_color, p.rank_dsize,
                   p.author_id,
                   u.nick AS author_nick, u.location AS author_location,
                   u.messagecount AS author_messagecount,
                   t.name AS thread_name, t.forum_id, t.archive,
                   t.file_path,
                   f.name AS forum_name,
                   t.post_count AS thread_post_count
            FROM posts p
            LEFT JOIN users   u ON u.id = p.author_id
            LEFT JOIN threads t ON t.id = p.thread_id
            LEFT JOIN forums  f ON f.id = t.forum_id
            WHERE p.id = ?
            """,
            (post_id,),
        ).fetchone()
        if not row:
            raise HTTPException(status_code=404, detail="post not found")
        d = dict(row)
        file_path = d.pop("file_path")
        # Prefer baked content_html. If absent and caller wants rich HTML,
        # predict which sibling page file contains this post from its idx
        # (15 posts/page) and parse only that file.
        if bare:
            d["content_html"] = d.get("content_html") or ""
        elif d.get("content_html"):
            pass  # already baked
        else:
            html = ""
            idx = d.get("idx")
            siblings = _sibling_page_files(file_path)
            if idx is not None and siblings:
                page_n = (idx - 1) // 15
                wanted = None
                for s in siblings:
                    if page_n == 0:
                        if "&page=" not in s:
                            wanted = s; break
                    else:
                        if f"&page={page_n}" in s:
                            wanted = s; break
                if wanted:
                    html = _post_html(wanted, post_id)
            if not html:
                for fp in siblings:
                    html = _post_html(fp, post_id)
                    if html:
                        break
            d["content_html"] = html
        return d
    finally:
        conn.close()


@app.get("/api/thread/{thread_id}")
def get_thread(
    thread_id: int,
    highlight_post: Optional[int] = None,
    page: Optional[int] = Query(None, ge=0, description="0-based page index"),
    page_size: int = Query(20, ge=1, le=100),
    bare: bool = Query(False, description="Skip post fetching โ€” return only thread metadata"),
):
    """Thread fetch. When `page` is supplied, returns just that page of posts
    plus `total_posts`. Without it returns the whole thread (legacy / 'full'
    view mode).

    Performance: prefers posts.content_html (baked) when available; only falls
    back to on-the-fly HTML file parsing for the (possibly-empty) set of posts
    that haven't been baked yet."""
    conn = db()
    try:
        cur = conn.cursor()
        thread = cur.execute(
            """
            SELECT t.id, t.name, t.forum_id, t.archive, t.file_path,
                   t.post_count AS total_posts,
                   f.name AS forum_name
            FROM threads t LEFT JOIN forums f ON f.id = t.forum_id
            WHERE t.id = ?
            """,
            (thread_id,),
        ).fetchone()
        if not thread:
            raise HTTPException(status_code=404, detail="thread not found")

        thread_d = dict(thread)
        file_path = thread_d.pop("file_path")
        total_posts = thread_d.get("total_posts") or 0

        if bare:
            return {"thread": thread_d, "posts": [], "page": None, "page_size": 0, "highlight_post": None}

        # Build query: full thread (no page) or one page only
        sql = """
            SELECT p.id, p.idx, p.created_at, p.content, p.content_html,
                   p.color AS post_color, p.dsize AS post_dsize,
                   p.rank_desc, p.rank_color, p.rank_dsize,
                   p.author_id,
                   u.nick AS author_nick, u.location AS author_location,
                   u.messagecount AS author_messagecount
            FROM posts p LEFT JOIN users u ON u.id = p.author_id
            WHERE p.thread_id = ?
            ORDER BY p.idx, p.id
        """
        params: list = [thread_id]
        if page is not None:
            sql += " LIMIT ? OFFSET ?"
            params += [page_size, page * page_size]
        posts = cur.execute(sql, params).fetchall()

        post_list = [dict(p) for p in posts]
        # Fall back to file-parse only for posts whose content_html wasn't
        # baked. Be selective about WHICH sibling files we open โ€” only the
        # ones whose post indexes overlap missing posts (forum paginates at
        # 15 posts/page, so each file covers idx range [15*N+1, 15*N+15]).
        missing = [p for p in post_list if not p.get("content_html")]
        if missing:
            siblings = _sibling_page_files(file_path)
            wanted_pages = set()
            for p in missing:
                ix = p.get("idx") or 1
                wanted_pages.add((ix - 1) // 15)
            def page_n_of(path):
                m = re.search(r"&page=(\d+)", path)
                return int(m.group(1)) if m else 0
            relevant = [s for s in siblings if page_n_of(s) in wanted_pages]
            rich = {}
            for fp in (relevant or siblings):
                rich.update(_parse_thread_html(fp))
            for p in missing:
                p["content_html"] = rich.get(p["id"], "")

        return {
            "thread": thread_d,
            "posts": post_list,
            "page": page,
            "page_size": page_size,
            "highlight_post": highlight_post,
        }
    finally:
        conn.close()


@app.get("/api/forums")
def list_forums():
    conn = db()
    try:
        cur = conn.cursor()
        rows = cur.execute(
            """
            SELECT f.id, f.name, COUNT(t.id) AS thread_count
            FROM forums f
            LEFT JOIN threads t ON t.forum_id = f.id
            GROUP BY f.id
            ORDER BY thread_count DESC
            """
        ).fetchall()
        return {"forums": [dict(r) for r in rows]}
    finally:
        conn.close()


@app.get("/api/discovery/random_thread")
def random_thread(min_posts: int = Query(3, ge=1)):
    """Pick a random thread with at least min_posts posts."""
    conn = db()
    try:
        cur = conn.cursor()
        # Fast random: pick a random rowid offset then scan forward.
        # Repeat up to 5x if the random pick lands on a tiny thread.
        for _ in range(5):
            row = cur.execute(
                """
                SELECT t.id, t.name, t.forum_id, t.post_count,
                       COALESCE(f.name, 'ืคื•ืจื•ื ' || t.forum_id) AS forum_name
                FROM threads t
                LEFT JOIN forums f ON f.id = t.forum_id
                WHERE t.rowid >= (ABS(RANDOM()) % (SELECT MAX(rowid) FROM threads))
                  AND t.post_count >= ?
                ORDER BY t.rowid
                LIMIT 1
                """,
                (min_posts,),
            ).fetchone()
            if row:
                return dict(row)
        raise HTTPException(status_code=503, detail="couldn't find a random thread")
    finally:
        conn.close()


@app.get("/api/discovery/top_users")
def top_users(by: str = Query("messages", pattern="^(messages|threads_started)$"),
              limit: int = Query(50, ge=1, le=200)):
    """Leaderboard of users โ€” by total messages, or by threads they opened."""
    conn = db()
    try:
        cur = conn.cursor()
        if by == "messages":
            rows = cur.execute(
                """
                SELECT id, nick, location, messagecount AS metric
                FROM users
                WHERE messagecount IS NOT NULL AND nick IS NOT NULL
                ORDER BY messagecount DESC
                LIMIT ?
                """,
                (limit,),
            ).fetchall()
        else:  # threads_started
            rows = cur.execute(
                """
                SELECT u.id, u.nick, u.location, COUNT(*) AS metric
                FROM threads t
                JOIN users u ON u.id = t.first_author_id
                WHERE u.nick IS NOT NULL
                GROUP BY u.id
                ORDER BY metric DESC
                LIMIT ?
                """,
                (limit,),
            ).fetchall()
        return {"by": by, "results": [dict(r) for r in rows]}
    finally:
        conn.close()


@app.get("/api/discovery/hot_threads")
def hot_threads(limit: int = Query(50, ge=1, le=200), year: Optional[int] = None):
    """Threads with the most replies. Optional ?year=YYYY narrows to that year."""
    conn = db()
    try:
        cur = conn.cursor()
        where = ["t.post_count >= 10"]
        params: list = []
        if year is not None:
            where.append("t.first_post_at >= ? AND t.first_post_at < ?")
            params.append(f"{year}-01-01")
            params.append(f"{year+1}-01-01")
        sql = f"""
            SELECT t.id, t.name, t.forum_id, t.post_count,
                   t.first_post_at, t.last_post_at,
                   COALESCE(f.name, 'ืคื•ืจื•ื ' || t.forum_id) AS forum_name,
                   u.nick AS first_author_nick
            FROM threads t
            LEFT JOIN forums f ON f.id = t.forum_id
            LEFT JOIN users  u ON u.id = t.first_author_id
            WHERE {' AND '.join(where)}
            ORDER BY t.post_count DESC
            LIMIT ?
        """
        rows = cur.execute(sql, params + [limit]).fetchall()
        return {"results": [dict(r) for r in rows]}
    finally:
        conn.close()


@app.get("/api/stats")
def stats():
    conn = db()
    try:
        cur = conn.cursor()

        def one(sql):
            return cur.execute(sql).fetchone()[0]

        return {
            "threads": one("SELECT COUNT(*) FROM threads"),
            "posts": one("SELECT COUNT(*) FROM posts"),
            "users": one("SELECT COUNT(*) FROM users"),
            "forums": one("SELECT COUNT(*) FROM forums"),
            "date_min": one("SELECT MIN(created_at) FROM posts WHERE created_at IS NOT NULL"),
            "date_max": one("SELECT MAX(created_at) FROM posts WHERE created_at IS NOT NULL"),
        }
    finally:
        conn.close()


@app.get("/api/user/{user_id}")
def get_user_profile(user_id: int):
    """Profile view: header stats (post count, thread count, date range,
    latest known rank, avatar URL) + top-5 forums by post count."""
    conn = db()
    try:
        cur = conn.cursor()
        user = cur.execute(
            "SELECT id, nick, location, messagecount FROM users WHERE id = ?",
            (user_id,),
        ).fetchone()
        if not user:
            raise HTTPException(status_code=404, detail="user not found")

        stats = cur.execute(
            """
            SELECT
                COUNT(*)              AS post_count,
                COUNT(DISTINCT thread_id) AS thread_count,
                MIN(created_at)       AS first_post,
                MAX(created_at)       AS last_post
            FROM posts
            WHERE author_id = ?
            """,
            (user_id,),
        ).fetchone()

        top_forums = cur.execute(
            """
            SELECT f.id, COALESCE(f.name, 'ืคื•ืจื•ื ' || f.id) AS name, COUNT(*) AS posts
            FROM posts p
            JOIN threads t ON t.id = p.thread_id
            LEFT JOIN forums f ON f.id = t.forum_id
            WHERE p.author_id = ?
            GROUP BY f.id
            ORDER BY posts DESC
            LIMIT 5
            """,
            (user_id,),
        ).fetchall()

        latest_rank = cur.execute(
            """
            SELECT rank_desc, rank_color, rank_dsize
            FROM posts
            WHERE author_id = ? AND (rank_desc IS NOT NULL OR rank_dsize IS NOT NULL)
            ORDER BY created_at DESC NULLS LAST, id DESC
            LIMIT 1
            """,
            (user_id,),
        ).fetchone()

        # Avatar existence โ€” cheap filesystem stat
        avatar_exists = (AVATAR_DIR / f"user{user_id}.jpg").exists()

        return {
            "user": dict(user),
            "stats": dict(stats),
            "top_forums": [dict(r) for r in top_forums],
            "latest_rank": dict(latest_rank) if latest_rank else None,
            "avatar_exists": avatar_exists,
        }
    finally:
        conn.close()


@app.get("/api/users/search")
def user_search(q: str = Query(..., min_length=1), limit: int = Query(10, ge=1, le=50)):
    conn = db()
    try:
        cur = conn.cursor()
        rows = cur.execute(
            """
            SELECT id, nick, location, messagecount
            FROM users
            WHERE nick LIKE ?
            ORDER BY (messagecount IS NULL), messagecount DESC, id
            LIMIT ?
            """,
            (f"%{q}%", limit),
        ).fetchall()
        return {"users": [dict(r) for r in rows]}
    finally:
        conn.close()


def _og_meta(props: dict[str, str]) -> str:
    """Render a dict of OG/Twitter meta tags as an HTML fragment."""
    out: list[str] = []
    for k, v in props.items():
        if not v:
            continue
        # property vs name attribute: og:* uses property, twitter:* uses name
        attr = "property" if k.startswith("og:") else "name"
        out.append(
            f'<meta {attr}="{_html_escape(k)}" content="{_html_escape(str(v))}">'
        )
    return "\n  ".join(out)


def _html_escape(s: str) -> str:
    return (
        s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
        .replace('"', "&quot;").replace("'", "&#39;")
    )


def _truncate(text: str, n: int = 200) -> str:
    text = re.sub(r"\s+", " ", (text or "")).strip()
    if len(text) <= n:
        return text
    return text[: n - 1].rstrip() + "โ€ฆ"


def _og_for_post(conn, post_id: int) -> dict[str, str]:
    cur = conn.cursor()
    row = cur.execute(
        """
        SELECT p.id, p.content, p.content_html, p.created_at,
               t.name AS thread_name, f.name AS forum_name,
               u.nick AS author_nick
        FROM posts p
        JOIN threads t ON t.id = p.thread_id
        LEFT JOIN forums f ON f.id = t.forum_id
        LEFT JOIN users  u ON u.id = p.author_id
        WHERE p.id = ?
        """,
        (post_id,),
    ).fetchone()
    if not row:
        return {}
    d = dict(row)
    nick = d.get("author_nick") or "ืื ื•ื ื™ืžื™"
    thread = d.get("thread_name") or f"ื“ื™ื•ืŸ"
    forum = d.get("forum_name") or ""
    # Prefer stripped body from baked HTML; fall back to plain text.
    body_text = ""
    if d.get("content_html"):
        body_text = _strip_quotes_from_html(d["content_html"]).strip()
    if not body_text:
        body_text = _strip_quote_headers_text(d.get("content") or "").strip()
    return {
        "title": f"{nick}: {thread}",
        "description": _truncate(body_text, 200) or f"ื”ื•ื“ืขื” ืžืืช {nick} ื‘ื“ื™ื•ืŸ \"{thread}\"" + (f" ยท {forum}" if forum else ""),
        "type": "article",
    }


def _og_for_thread(conn, thread_id: int) -> dict[str, str]:
    cur = conn.cursor()
    row = cur.execute(
        """
        SELECT t.id, t.name AS thread_name, t.post_count,
               f.name AS forum_name,
               u.nick AS first_author_nick,
               (SELECT substr(p.content, 1, 400) FROM posts p
                WHERE p.thread_id = t.id ORDER BY p.idx LIMIT 1) AS first_excerpt
        FROM threads t
        LEFT JOIN forums f ON f.id = t.forum_id
        LEFT JOIN users  u ON u.id = t.first_author_id
        WHERE t.id = ?
        """,
        (thread_id,),
    ).fetchone()
    if not row:
        return {}
    d = dict(row)
    name = d.get("thread_name") or f"ื“ื™ื•ืŸ {thread_id}"
    forum = d.get("forum_name") or ""
    nick = d.get("first_author_nick")
    posts = d.get("post_count") or 0
    excerpt = _truncate(_strip_quote_headers_text(d.get("first_excerpt") or ""), 200)
    bits = []
    if forum:
        bits.append(forum)
    if posts:
        bits.append(f"{posts:,} ื”ื•ื“ืขื•ืช".replace(",", ","))
    if nick:
        bits.append(f"ืคืชื—: {nick}")
    subtitle = " ยท ".join(bits)
    return {
        "title": name,
        "description": excerpt or subtitle or f"ื“ื™ื•ืŸ ื‘ืืจื›ื™ื•ืŸ gamer.co.il",
        "type": "article",
    }


def _build_og_block(request: Request) -> str:
    """Return an HTML fragment of OG/Twitter meta tags appropriate for the
    URL the user landed on. Crawlers like Slack/Twitter/Discord fetch the
    page once and read these tags to render a rich link card."""
    qp = request.query_params
    url = str(request.url)
    # Sensible site-wide defaults.
    info = {
        "title": "Gamer Forums Archive",
        "description": (
            "ืืจื›ื™ื•ืŸ ืคื•ืจื•ืžื™ gamer.co.il โ€” ื—ื™ืคื•ืฉ ืขืœ ืคื ื™ 10 ืžื™ืœื™ื•ืŸ ื”ื•ื“ืขื•ืช "
            "ื‘-546 ืืœืฃ ื“ื™ื•ื ื™ื (2004โ€“2014)."
        ),
        "type": "website",
    }
    # Per-item overrides.
    open_param = qp.get("open", "")
    try:
        if open_param.startswith("post:"):
            conn = db()
            try:
                info.update({k: v for k, v in _og_for_post(conn, int(open_param.split(":", 1)[1])).items() if v})
            finally:
                conn.close()
        elif open_param.startswith("thread:"):
            conn = db()
            try:
                info.update({k: v for k, v in _og_for_thread(conn, int(open_param.split(":", 1)[1])).items() if v})
            finally:
                conn.close()
        elif qp.get("q"):
            info["title"] = f'ื—ื™ืคื•ืฉ: "{qp.get("q")}" โ€” Gamer Forums Archive'
    except Exception:
        # Never let OG generation 500 the page. Defaults are good enough.
        pass

    og = {
        "og:site_name": "Gamer Forums Archive",
        "og:title": info["title"],
        "og:description": info["description"],
        "og:type": info["type"],
        "og:url": url,
        "og:image": str(request.base_url).rstrip("/") + "/static/logo.png",
        "og:image:width": "500",
        "og:image:height": "143",
        "og:locale": "he_IL",
        "twitter:card": "summary_large_image",
        "twitter:title": info["title"],
        "twitter:description": info["description"],
        "twitter:image": str(request.base_url).rstrip("/") + "/static/logo.png",
    }
    return _og_meta(og)


@app.get("/")
def root(request: Request):
    index = STATIC_DIR / "index.html"
    if not index.exists():
        return JSONResponse({"error": "static/index.html not built yet"}, status_code=503)
    try:
        html = index.read_text(encoding="utf-8")
    except OSError:
        return FileResponse(index)
    og_block = _build_og_block(request)
    # Replace the placeholder if present; otherwise fall through to the
    # original file (covers both the templated case and any future direct
    # FileResponse fallback).
    if "<!--OG_TAGS-->" in html:
        html = html.replace("<!--OG_TAGS-->", og_block, 1)
    return HTMLResponse(html)


if STATIC_DIR.exists():
    app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
if AVATAR_DIR.exists():
    app.mount("/avatars", StaticFiles(directory=AVATAR_DIR), name="avatars")
if EMOJI_DIR.exists():
    app.mount("/forum_emojis", StaticFiles(directory=EMOJI_DIR), name="forum_emojis")