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

Reads lexicon TSVs and cognate-pair TSVs from data/training/, builds a
phylogenetic tree of language relationships, and generates stratified
validation sets split by phylogenetic distance, timespan, family, and
concept domain (religious terms).

Output goes to data/training/validation/.
"""

from __future__ import annotations

import csv
import json
import random
import sys
from collections import defaultdict
from pathlib import Path
from typing import Any

# Ensure cognate_pipeline package is importable
sys.path.insert(
    0,
    str(Path(__file__).resolve().parent.parent / "cognate_pipeline" / "src"),
)
from cognate_pipeline.normalise.sound_class import ipa_to_sound_class

# ---------------------------------------------------------------------------
# Paths
# ---------------------------------------------------------------------------

REPO_ROOT = Path(__file__).resolve().parent.parent
TRAINING_DIR = REPO_ROOT / "data" / "training"
LEXICONS_DIR = TRAINING_DIR / "lexicons"
COGNATE_DIR = TRAINING_DIR / "cognate_pairs"
OUTPUT_DIR = TRAINING_DIR / "validation"
FAMILY_MAP_PATH = (
    REPO_ROOT
    / "cognate_pipeline"
    / "src"
    / "cognate_pipeline"
    / "cognate"
    / "family_map.json"
)

PAIR_CAP = 50_000
SEED = 42
MAX_PAIRS_PER_CONCEPT_PER_LEVEL = 100
MAX_CROSS_FAMILY_PAIRS_PER_CONCEPT = 50
TRUE_NEG_SAMPLE_ATTEMPTS = 2_000_000

# ---------------------------------------------------------------------------
# TSV field names for output
# ---------------------------------------------------------------------------

OUTPUT_FIELDS = [
    "Lang_A",
    "Word_A",
    "IPA_A",
    "SCA_A",
    "Lang_B",
    "Word_B",
    "IPA_B",
    "SCA_B",
    "Concept_ID",
    "Label",
    "Phylo_Dist",
    "Timespan",
    "Score",
    "Source",
]

# ---------------------------------------------------------------------------
# Era classification
# ---------------------------------------------------------------------------

ANCIENT: set[str] = {
    "grc", "lat", "san", "ave", "got", "akk", "egy", "phn", "uga",
    "sux", "hit", "osc", "xum", "gmy", "sga", "chu", "och", "obr",
    "cop", "arc", "syc", "ett",
}

MEDIEVAL: set[str] = {
    "ang", "enm", "fro", "osp", "non", "goh", "dum", "mga", "wlm",
    "orv", "otk", "ota", "okm", "kaw", "mnc", "bod",
}


def classify_era(iso: str) -> str:
    """Return 'ancient', 'medieval', or 'modern'."""
    if iso in ANCIENT:
        return "ancient"
    if iso in MEDIEVAL:
        return "medieval"
    return "modern"


def get_timespan(iso_a: str, iso_b: str) -> str:
    """Return one of the four canonical timespan buckets."""
    era_a = classify_era(iso_a)
    era_b = classify_era(iso_b)
    eras = frozenset((era_a, era_b))
    if eras == {"ancient"}:
        return "ancient_ancient"
    if eras == {"modern"}:
        return "modern_modern"
    if eras == {"medieval"}:
        return "medieval_modern"
    if "ancient" in eras and "medieval" in eras:
        return "ancient_modern"
    if "ancient" in eras and "modern" in eras:
        return "ancient_modern"
    # medieval + modern
    return "medieval_modern"


# ---------------------------------------------------------------------------
# Religious concepts — organised by sub-domain (generous classification)
# ---------------------------------------------------------------------------

RELIGIOUS_CORE: set[str] = {
    "DEITY", "DEITY/GOD", "GOD", "SPIRIT", "TEMPLE", "ALTAR", "SACRIFICE",
    "WORSHIP", "PRAY", "PRIEST", "HOLY", "PREACH", "BLESS", "CHURCH",
    "MOSQUE", "SOUL", "RELIGION", "IDOL", "MINISTER",
}

RELIGIOUS_SUPERNATURAL: set[str] = {
    "GHOST", "DEMON", "MAGIC", "SORCERER", "MAGICIAN", "OMEN",
    "ELF OR FAIRY", "FAIRY TALE", "DREAM (SOMETHING)", "DREAM",
}

RELIGIOUS_MORAL: set[str] = {
    "SIN", "BAD OR EVIL", "EVIL", "BELIEVE", "TRUTH", "SHAME",
    "GUILTY", "CRIME", "ADULTERY", "PITY", "FORGIVE", "INNOCENT",
    "ACCUSE", "CONDEMN", "JUDGE", "JUDGMENT", "LAW", "PUNISHMENT",
    "WITNESS", "POOR", "RICH", "FAITHFUL", "GOOD",
}

RELIGIOUS_RITUAL: set[str] = {
    "CURSE", "FAST", "CIRCUMCISION", "INITIATION CEREMONY", "WEDDING",
    "OATH", "SWEAR", "CUSTOM", "BURY", "GRAVE", "CORPSE", "DANCE",
    "DRUM", "SONG",
}

RELIGIOUS_VERBS: set[str] = {
    "GIVE", "DONATE", "KNEEL", "BURN (SOMETHING)", "KILL", "POUR",
    "FEED", "SHARE", "INVITE", "COMMAND", "PROMISE", "OBEY",
    "HELP", "PROTECT", "DEFEND", "RESCUE", "HOPE (SOMETHING)",
    "FEAR (BE AFRAID)", "FEAR (FRIGHT)", "LOVE",
}

RELIGIOUS_COSMIC: set[str] = {
    "HEAVEN", "HELL", "LIGHTNING", "THUNDER", "FIRE", "SUN", "MOON",
    "STAR", "SKY", "RAINBOW", "EARTHQUAKE", "WORLD", "LIFE",
    "DEATH", "BE DEAD OR DIE", "BE ALIVE", "BE BORN",
    "ANCESTORS", "DESCENDANTS",
}

RELIGIOUS_PLACES: set[str] = {
    "TEMPLE", "CHURCH", "MOSQUE", "CAVE", "MOUNTAIN", "MOUNTAIN OR HILL",
    "SPRING OR WELL", "GARDEN", "FOREST", "STONE", "STONE OR ROCK",
    "VILLAGE", "TOWN", "COUNTRY", "ISLAND", "RIVER", "SEA",
    "NATIVE COUNTRY",
}

# Additional numeric IDs from cross-lingual datasets that map to religious concepts
_RELIGIOUS_NUMERIC_IDS: set[str] = {
    "3231", "53", "911", "853", "1103", "257", "24", "852", "1702", "304",
    "391", "8", "303", "1565", "878", "1973", "1945", "392", "2137", "1175",
    "107", "1349", "1603", "811", "2971", "661", "1944",
}

# Union of all sub-domains — the generous set
RELIGIOUS_ALL: set[str] = (
    RELIGIOUS_CORE
    | RELIGIOUS_SUPERNATURAL
    | RELIGIOUS_MORAL
    | RELIGIOUS_RITUAL
    | RELIGIOUS_VERBS
    | RELIGIOUS_COSMIC
    | RELIGIOUS_PLACES
    | _RELIGIOUS_NUMERIC_IDS
)

# Sub-domain name → concept set mapping (for generating sub-domain files)
RELIGIOUS_SUBDOMAINS: dict[str, set[str]] = {
    "core_religious": RELIGIOUS_CORE,
    "supernatural": RELIGIOUS_SUPERNATURAL,
    "moral_ethical": RELIGIOUS_MORAL,
    "ritual_ceremony": RELIGIOUS_RITUAL,
    "religious_verbs": RELIGIOUS_VERBS,
    "cosmic_spiritual": RELIGIOUS_COSMIC,
    "sacred_places": RELIGIOUS_PLACES,
}

# Pre-compute uppercase set for fast case-insensitive matching
_RELIGIOUS_ALL_UPPER: set[str] = {c.upper() for c in RELIGIOUS_ALL}


def is_religious(concept_id: str) -> bool:
    """Return True if *concept_id* refers to a religious concept."""
    if concept_id in RELIGIOUS_ALL:
        return True
    return concept_id.upper() in _RELIGIOUS_ALL_UPPER


def _in_subdomain(concept_id: str, subdomain_set: set[str]) -> bool:
    """Return True if *concept_id* belongs to the given sub-domain set."""
    if concept_id in subdomain_set:
        return True
    return concept_id.upper() in {c.upper() for c in subdomain_set}


# ---------------------------------------------------------------------------
# Top families
# ---------------------------------------------------------------------------

TOP_FAMILIES = [
    "germanic", "italic", "balto_slavic", "indo_iranian", "hellenic",
    "celtic", "uralic", "turkic", "sino_tibetan", "austronesian",
    "semitic", "dravidian", "japonic", "koreanic", "kartvelian",
]

# Map family_map values that differ from the tree's branch names
FAMILY_ALIAS = {
    "slavic": "balto_slavic",
    "baltic": "balto_slavic",
}

# ---------------------------------------------------------------------------
# SCA similarity (standalone, mirrors baseline_levenshtein.py)
# ---------------------------------------------------------------------------

_VOWELS = set("AEIOU")
_LABIALS = {"P", "B", "M"}
_CORONALS = {"T", "D", "N", "S", "L", "R"}
_VELARS = {"K", "G"}
_LARYNGEALS = {"H"}
_GLIDES = {"W", "Y"}
_NATURAL_CLASSES = [_VOWELS, _LABIALS, _CORONALS, _VELARS, _LARYNGEALS, _GLIDES]


def _substitution_cost(a: str, b: str) -> float:
    if a == b:
        return 0.0
    for cls in _NATURAL_CLASSES:
        if a in cls and b in cls:
            return 0.3
    return 1.0


def weighted_levenshtein(s1: str, s2: str) -> float:
    n, m = len(s1), len(s2)
    if n == 0:
        return m * 0.5
    if m == 0:
        return n * 0.5
    dp = [[0.0] * (m + 1) for _ in range(n + 1)]
    for i in range(n + 1):
        dp[i][0] = i * 0.5
    for j in range(m + 1):
        dp[0][j] = j * 0.5
    for i in range(1, n + 1):
        for j in range(1, m + 1):
            sub = _substitution_cost(s1[i - 1], s2[j - 1])
            dp[i][j] = min(
                dp[i - 1][j] + 0.5,
                dp[i][j - 1] + 0.5,
                dp[i - 1][j - 1] + sub,
            )
    return dp[n][m]


def normalised_similarity(s1: str, s2: str) -> float:
    if not s1 and not s2:
        return 1.0
    max_len = max(len(s1), len(s2))
    dist = weighted_levenshtein(s1, s2)
    return 1.0 - (dist / max_len) if max_len > 0 else 1.0


# ---------------------------------------------------------------------------
# Phylogenetic tree definition
# ---------------------------------------------------------------------------

def build_raw_tree() -> dict[str, Any]:
    """Return the hard-coded phylogenetic tree.

    Leaf-group values are either lists of ISO codes or the sentinel
    ``"__from_family_map__"`` which is resolved later.
    """
    return {
        "indo_european": {
            "germanic": {
                "west_germanic": {
                    "anglo_frisian": ["eng", "ang", "enm", "fry", "frr", "ofs"],
                    "franconian": ["nld", "dum", "lim", "afr"],
                    "high_german": ["deu", "goh", "gsw", "bar", "ltz", "yid"],
                },
                "north_germanic": [
                    "swe", "dan", "nor", "nno", "nob", "isl", "fao", "non",
                ],
                "east_germanic": ["got"],
            },
            "italic": {
                "romance": {
                    "ibero_romance": ["spa", "por", "cat", "glg", "osp"],
                    "gallo_romance": ["fra", "oci", "fro"],
                    "italo_dalmatian": ["ita", "nap", "scn", "dlm", "cos"],
                    "eastern_romance": ["ron", "rup"],
                },
                "latino_faliscan": ["lat", "osc", "xum"],
            },
            "celtic": {
                "goidelic": ["gle", "gla", "sga", "mga"],
                "brythonic": ["cym", "bre", "cor", "wlm"],
            },
            "balto_slavic": {
                "baltic": ["lit", "lav", "ltg"],
                "east_slavic": ["rus", "ukr", "bel", "orv"],
                "west_slavic": ["pol", "ces", "slk", "dsb", "hsb", "csb", "pox"],
                "south_slavic": ["bul", "mkd", "hrv", "slv", "hbs", "chu"],
            },
            "hellenic": ["ell", "grc", "gmy"],
            "indo_iranian": {
                "iranian": [
                    "fas", "pes", "oss", "kmr", "ckb", "pbu", "tgk", "ave",
                    "zza",
                ],
                "indic": [
                    "hin", "ben", "san", "guj", "mar", "pan", "sin", "urd",
                    "asm", "nep", "rom", "rmn",
                ],
            },
            "armenian": ["hye"],
            "albanian": ["sqi"],
            "anatolian": ["hit"],
        },
        "uralic": {
            "finnic": [
                "fin", "est", "ekk", "krl", "olo", "vep", "vot", "izh", "liv",
            ],
            "ugric": ["hun", "mns", "kca"],
            "samic": ["sme", "sma", "smj", "smn", "sms", "sjd"],
            "mordvinic": ["myv", "mdf"],
            "permic": ["kpv", "koi", "udm"],
            "mari": ["mhr", "mrj"],
            "samoyedic": ["yrk", "enf", "sel", "nio"],
        },
        "turkic": {
            "oghuz": ["tur", "aze", "azj", "ota", "otk"],
            "kipchak": ["kaz", "kir", "tat", "bak"],
            "siberian": ["sah", "tyv"],
            "karluk": ["uzb", "uzn"],
            "oghur": ["chv"],
        },
        "sino_tibetan": {
            "sinitic": ["zho", "cmn", "yue", "och"],
            "tibeto_burman": ["bod", "mya", "obr", "new", "lif"],
        },
        "austronesian": {
            "malayo_polynesian": "__from_family_map__",
        },
        "semitic": [
            "heb", "arb", "ara", "amh", "mlt", "syc", "arc", "akk", "phn",
            "uga",
        ],
        "dravidian": ["tam", "tel", "kan", "mal"],
        "japonic": ["jpn"],
        "koreanic": ["kor", "jje", "okm"],
        "kartvelian": ["kat", "lzz"],
    }


# ---------------------------------------------------------------------------
# Tree resolution helpers
# ---------------------------------------------------------------------------

def _collect_isos_from_tree(node: Any) -> set[str]:
    """Recursively collect all ISO codes that already appear in *node*."""
    if isinstance(node, list):
        return set(node)
    if isinstance(node, str):
        if node == "__from_family_map__":
            return set()
        return {node}
    isos: set[str] = set()
    for v in node.values():
        isos |= _collect_isos_from_tree(v)
    return isos


def resolve_tree(tree: dict[str, Any], family_map: dict[str, str]) -> dict[str, Any]:
    """Replace ``"__from_family_map__"`` sentinels and add catch-all groups.

    Returns a new tree (original is not mutated).
    """
    tree = _deep_copy_tree(tree)

    # Phase 1: resolve sentinels -----------------------------------------
    _resolve_sentinels(tree, family_map)

    # Phase 2: add catch-all for languages in family_map but not in tree --
    present = _collect_isos_from_tree(tree)
    extras: dict[str, list[str]] = defaultdict(list)
    for iso, fam in family_map.items():
        if iso in present:
            continue
        canonical = FAMILY_ALIAS.get(fam, fam)
        extras[canonical].append(iso)

    for fam, isos in extras.items():
        if fam not in tree:
            tree[fam] = sorted(isos)
        else:
            # Family exists as a top-level node — add under an
            # "other_{fam}" subgroup so we don't clobber existing structure.
            node = tree[fam]
            if isinstance(node, dict):
                existing = _collect_isos_from_tree(node)
                new_isos = [i for i in isos if i not in existing]
                if new_isos:
                    node[f"other_{fam}"] = sorted(new_isos)
            elif isinstance(node, list):
                existing = set(node)
                for iso in isos:
                    if iso not in existing:
                        node.append(iso)
            # If the node is a single string, wrap it
            elif isinstance(node, str) and node != "__from_family_map__":
                tree[fam] = [node] + sorted(isos)

    return tree


def _deep_copy_tree(node: Any) -> Any:
    if isinstance(node, dict):
        return {k: _deep_copy_tree(v) for k, v in node.items()}
    if isinstance(node, list):
        return list(node)
    return node


def _resolve_sentinels(node: Any, family_map: dict[str, str]) -> None:
    """In-place replacement of ``"__from_family_map__"`` values."""
    if not isinstance(node, dict):
        return
    for key, val in list(node.items()):
        if val == "__from_family_map__":
            # key is the family name that should match family_map values
            # For "malayo_polynesian" under "austronesian", pull all
            # family_map entries mapped to "austronesian".
            parent_family = _find_parent_family(node, key)
            if parent_family is None:
                parent_family = key
            isos = sorted(
                iso for iso, fam in family_map.items() if fam == parent_family
            )
            node[key] = isos if isos else []
        elif isinstance(val, dict):
            _resolve_sentinels(val, family_map)


def _find_parent_family(node: dict, child_key: str) -> str | None:  # noqa: ARG001
    """Heuristic: the sentinel is typically placed one level below the
    actual family name.  Walk the raw tree keys for a match.  For our
    tree, ``malayo_polynesian`` is under ``austronesian``, so we return
    ``austronesian``."""
    # We rely on the caller context; this is called from _resolve_sentinels
    # which walks the tree recursively.  At the point we find the sentinel
    # the *node* dict is ``{"malayo_polynesian": "__from_family_map__"}``,
    # and we need the grandparent key.  Since we don't track the parent key
    # inside the recursive walk, we use a simpler approach: just look up in
    # a mapping.
    _SENTINEL_PARENT: dict[str, str] = {
        "malayo_polynesian": "austronesian",
    }
    return _SENTINEL_PARENT.get(child_key)


# ---------------------------------------------------------------------------
# Language path index & phylo distance
# ---------------------------------------------------------------------------

def build_lang_paths(
    tree: dict[str, Any],
) -> dict[str, list[str]]:
    """Map each ISO code to its full path from root to its leaf group.

    For ``eng`` inside ``indo_european > germanic > west_germanic >
    anglo_frisian`` the path is
    ``["indo_european", "germanic", "west_germanic", "anglo_frisian"]``.
    """
    paths: dict[str, list[str]] = {}

    def _walk(node: Any, prefix: list[str]) -> None:
        if isinstance(node, list):
            for iso in node:
                paths[iso] = list(prefix)
        elif isinstance(node, dict):
            for key, child in node.items():
                _walk(child, prefix + [key])
        elif isinstance(node, str):
            # Single ISO as a leaf
            paths[node] = list(prefix)

    _walk(tree, [])
    return paths


def compute_distance(
    lang_a: str,
    lang_b: str,
    lang_paths: dict[str, list[str]],
) -> tuple[int, str]:
    """Return (edge_count, level_label) between two languages.

    Level mapping:
        L1 — same leaf group (same last path element)
        L2 — LCA is two levels above leaf
        L3 — LCA is deeper within same top-level family
        L4 — different top-level families or not in tree
    """
    pa = lang_paths.get(lang_a)
    pb = lang_paths.get(lang_b)
    if pa is None or pb is None:
        return (99, "L4")
    if not pa or not pb:
        return (99, "L4")

    # Find LCA depth
    lca_depth = 0
    for i, (a, b) in enumerate(zip(pa, pb)):
        if a != b:
            break
        lca_depth = i + 1
    else:
        # Exhausted the shorter path without mismatch
        lca_depth = min(len(pa), len(pb))

    if lca_depth == 0:
        # Different top-level families
        return (len(pa) + len(pb), "L4")

    depth_a = len(pa)
    depth_b = len(pb)
    edge_count = (depth_a - lca_depth) + (depth_b - lca_depth)

    # Determine level from the relationship between paths.
    #
    # L1 — same leaf group: paths are identical (both languages listed under
    #       the same terminal node, e.g. both in "anglo_frisian").
    # L2 — same branch, different leaf group: LCA is the *parent* of the
    #       leaf groups (e.g. eng in anglo_frisian, deu in high_german; LCA
    #       is west_germanic) OR LCA is one more level up within the same
    #       major branch.  Concretely: the paths diverge at the last or
    #       second-to-last position relative to the *shorter* path.
    # L3 — same top-level family, deeper divergence (e.g. eng vs fra both in
    #       indo_european but in different major branches).
    # L4 — different top-level families (already handled above).

    if pa == pb:
        # Same leaf group
        return (edge_count, "L1")

    # Classification based on how deep the shared ancestry is:
    #   L2 — same branch: they share at least 2 path elements
    #         e.g. both under [indo_european, germanic, ...]
    #         or both under [uralic, finnic, ...]
    #   L3 — same top-level family but different branches:
    #         they share only 1 path element (the super-family)
    #         e.g. [indo_european, germanic, ...] vs [indo_european, italic, ...]
    if lca_depth >= 2:
        return (edge_count, "L2")
    # lca_depth == 1: same top-level family, different branches
    return (edge_count, "L3")


def get_top_family(iso: str, lang_paths: dict[str, list[str]], family_map: dict[str, str]) -> str:
    """Return the top-level family name for *iso*.

    Tries the tree path first; falls back to family_map.
    """
    path = lang_paths.get(iso)
    if path:
        # The first element is the top-level family node; but we want the
        # *branch* name that corresponds to TOP_FAMILIES.  The branch is
        # typically the second element (e.g. "germanic" under "indo_european").
        # For top-level families like "uralic", the first element IS the family.
        if len(path) >= 2 and path[1] in _TOP_FAMILY_SET:
            return path[1]
        if path[0] in _TOP_FAMILY_SET:
            return path[0]
        # Search path for any matching family name
        for segment in path:
            if segment in _TOP_FAMILY_SET:
                return segment
        # Return the first path element as family
        return path[0] if path else "unknown"

    # Fallback: family_map
    fam = family_map.get(iso, "unknown")
    return FAMILY_ALIAS.get(fam, fam)


_TOP_FAMILY_SET = set(TOP_FAMILIES)

# ---------------------------------------------------------------------------
# Data loading
# ---------------------------------------------------------------------------

LexEntry = tuple[str, str, str]  # (word, ipa, sca)


def load_lexicons(
    lexicons_dir: Path,
) -> dict[tuple[str, str], list[LexEntry]]:
    """Load all lexicon TSVs into ``{(iso, concept_id): [(word, ipa, sca), ...]}``.

    Entries with ``Concept_ID`` of ``"-"`` or empty are skipped.
    """
    lexicon: dict[tuple[str, str], list[LexEntry]] = defaultdict(list)
    files = sorted(lexicons_dir.glob("*.tsv"))
    total_entries = 0
    skipped_no_concept = 0

    for i, fp in enumerate(files, 1):
        iso = fp.stem
        if i % 100 == 0 or i == len(files):
            print(f"  Loading lexicon {i}/{len(files)} ({iso}) ...")
        try:
            with fp.open(encoding="utf-8") as fh:
                reader = csv.DictReader(fh, delimiter="\t")
                for row in reader:
                    cid = row.get("Concept_ID", "").strip()
                    if cid in ("", "-"):
                        skipped_no_concept += 1
                        continue
                    word = row.get("Word", "").strip()
                    ipa = row.get("IPA", "").strip()
                    sca = row.get("SCA", "").strip()
                    if not word and not ipa and not sca:
                        continue
                    lexicon[(iso, cid)].append((word, ipa, sca))
                    total_entries += 1
        except Exception as exc:
            print(f"  WARNING: failed to read {fp.name}: {exc}", file=sys.stderr)

    print(f"  Loaded {total_entries:,} entries across {len(files)} lexicons "
          f"(skipped {skipped_no_concept:,} without concept).")
    return lexicon


def build_concept_index(
    lexicon: dict[tuple[str, str], list[LexEntry]],
) -> dict[str, list[str]]:
    """Map each concept_id to the list of ISO codes that have entries for it."""
    concept_langs: dict[str, set[str]] = defaultdict(set)
    for (iso, cid) in lexicon:
        concept_langs[cid].add(iso)
    return {cid: sorted(isos) for cid, isos in concept_langs.items()}


def load_cognate_pairs(path: Path) -> list[dict[str, str]]:
    """Load a cognate-pairs TSV file into a list of dicts."""
    rows: list[dict[str, str]] = []
    if not path.exists():
        print(f"  WARNING: {path} not found, skipping.")
        return rows
    with path.open(encoding="utf-8") as fh:
        reader = csv.DictReader(fh, delimiter="\t")
        for row in reader:
            rows.append(dict(row))
    print(f"  Loaded {len(rows):,} pairs from {path.name}")
    return rows


# ---------------------------------------------------------------------------
# Pair record builder
# ---------------------------------------------------------------------------

def make_pair_record(
    lang_a: str,
    word_a: str,
    ipa_a: str,
    sca_a: str,
    lang_b: str,
    word_b: str,
    ipa_b: str,
    sca_b: str,
    concept_id: str,
    label: str,
    lang_paths: dict[str, list[str]],
    source: str = "lexicon",
    score_override: float | None = None,
) -> dict[str, str]:
    """Build a single output-row dict."""
    _, level = compute_distance(lang_a, lang_b, lang_paths)
    ts = get_timespan(lang_a, lang_b)
    if score_override is not None:
        score = score_override
    else:
        score = normalised_similarity(sca_a, sca_b) if sca_a and sca_b else 0.0
    return {
        "Lang_A": lang_a,
        "Word_A": word_a,
        "IPA_A": ipa_a,
        "SCA_A": sca_a,
        "Lang_B": lang_b,
        "Word_B": word_b,
        "IPA_B": ipa_b,
        "SCA_B": sca_b,
        "Concept_ID": concept_id,
        "Label": label,
        "Phylo_Dist": level,
        "Timespan": ts,
        "Score": f"{score:.4f}",
        "Source": source,
    }


# ---------------------------------------------------------------------------
# TSV writing helper
# ---------------------------------------------------------------------------

def write_pairs_tsv(path: Path, pairs: list[dict[str, str]]) -> None:
    """Write a list of pair dicts as a TSV file."""
    path.parent.mkdir(parents=True, exist_ok=True)
    with path.open("w", encoding="utf-8", newline="") as fh:
        writer = csv.DictWriter(fh, fieldnames=OUTPUT_FIELDS, delimiter="\t",
                                extrasaction="ignore")
        writer.writeheader()
        for row in pairs:
            writer.writerow(row)
    print(f"  Wrote {len(pairs):,} pairs to {path.relative_to(REPO_ROOT)}")


# ---------------------------------------------------------------------------
# Step 3: True cognate pair generation
# ---------------------------------------------------------------------------

def generate_true_cognates(
    lexicon: dict[tuple[str, str], list[LexEntry]],
    concept_langs: dict[str, list[str]],
    lang_paths: dict[str, list[str]],
    family_map: dict[str, str],
    inherited_pairs: list[dict[str, str]],
) -> tuple[list[dict[str, str]], list[dict[str, str]], list[dict[str, str]]]:
    """Generate true cognate pairs at L1, L2, L3 levels.

    Returns (l1_pairs, l2_pairs, l3_pairs).
    """
    l1: list[dict[str, str]] = []
    l2: list[dict[str, str]] = []
    l3: list[dict[str, str]] = []

    buckets = {"L1": l1, "L2": l2, "L3": l3}
    thresholds = {"L1": 0.5, "L2": 0.5, "L3": 0.4}

    # Step 3a: incorporate expert pairs FIRST (they have priority)
    print("Step 3a: Adding expert cognate pairs ...")
    expert_added = 0
    for row in inherited_pairs:
        if all(len(b) >= PAIR_CAP for b in buckets.values()):
            break

        lang_a = row.get("Lang_A", "")
        lang_b = row.get("Lang_B", "")
        if not lang_a or not lang_b:
            continue

        _, level = compute_distance(lang_a, lang_b, lang_paths)
        if level not in buckets or len(buckets[level]) >= PAIR_CAP:
            continue

        cid = row.get("Concept_ID", "")
        ipa_a = row.get("IPA_A", "")
        ipa_b = row.get("IPA_B", "")
        word_a = row.get("Word_A", "")
        word_b = row.get("Word_B", "")
        sca_a = _lookup_sca(lexicon, lang_a, cid, word_a, ipa_a)
        sca_b = _lookup_sca(lexicon, lang_b, cid, word_b, ipa_b)

        score_str = row.get("Score", "0")
        try:
            score = float(score_str)
        except (ValueError, TypeError):
            score = 0.0

        if sca_a and sca_b:
            sca_sim = normalised_similarity(sca_a, sca_b)
        else:
            sca_sim = score

        rec = make_pair_record(
            lang_a, word_a, ipa_a, sca_a,
            lang_b, word_b, ipa_b, sca_b,
            cid, "true_cognate", lang_paths,
            source=row.get("Source", "expert"),
            score_override=sca_sim,
        )
        rec["Phylo_Dist"] = level
        buckets[level].append(rec)
        expert_added += 1

    print(f"  Added {expert_added:,} expert pairs "
          f"(L1={len(l1):,} L2={len(l2):,} L3={len(l3):,})")

    # Step 3b: Fill remaining slots from lexicon data
    print("Step 3b: Generating true cognates from lexicon data ...")

    concepts_processed = 0
    total_concepts = len(concept_langs)

    for cid, langs in concept_langs.items():
        concepts_processed += 1
        if concepts_processed % 500 == 0:
            print(f"  Concept {concepts_processed}/{total_concepts} "
                  f"(L1={len(l1):,} L2={len(l2):,} L3={len(l3):,})")

        # Early termination
        if all(len(b) >= PAIR_CAP for b in buckets.values()):
            break

        # Group languages by top-level family
        family_groups: dict[str, list[str]] = defaultdict(list)
        for iso in langs:
            fam = get_top_family(iso, lang_paths, family_map)
            family_groups[fam].append(iso)

        # Within each family, generate pairs
        for fam, fam_langs in family_groups.items():
            if len(fam_langs) < 2:
                continue

            # Sample pairs if too many languages
            if len(fam_langs) > 50:
                sampled = random.sample(fam_langs, 50)
            else:
                sampled = fam_langs

            pair_count_this_concept: dict[str, int] = {"L1": 0, "L2": 0, "L3": 0}

            for i in range(len(sampled)):
                for j in range(i + 1, len(sampled)):
                    iso_a = sampled[i]
                    iso_b = sampled[j]
                    if iso_a == iso_b:
                        continue

                    _, level = compute_distance(iso_a, iso_b, lang_paths)
                    if level not in buckets or len(buckets[level]) >= PAIR_CAP:
                        continue
                    if pair_count_this_concept.get(level, 0) >= MAX_PAIRS_PER_CONCEPT_PER_LEVEL:
                        continue

                    thresh = thresholds[level]
                    entries_a = lexicon.get((iso_a, cid), [])
                    entries_b = lexicon.get((iso_b, cid), [])
                    if not entries_a or not entries_b:
                        continue

                    # Pick one entry from each language (first with SCA)
                    ea = _pick_best_entry(entries_a)
                    eb = _pick_best_entry(entries_b)
                    if ea is None or eb is None:
                        continue

                    sca_sim = normalised_similarity(ea[2], eb[2]) if ea[2] and eb[2] else 0.0
                    if sca_sim < thresh:
                        continue

                    rec = make_pair_record(
                        iso_a, ea[0], ea[1], ea[2],
                        iso_b, eb[0], eb[1], eb[2],
                        cid, "true_cognate", lang_paths,
                        source="lexicon",
                        score_override=sca_sim,
                    )
                    rec["Phylo_Dist"] = level  # ensure correct level
                    buckets[level].append(rec)
                    pair_count_this_concept[level] = pair_count_this_concept.get(level, 0) + 1

    print(f"  From lexicon: L1={len(l1):,} L2={len(l2):,} L3={len(l3):,}")

    # Cap each bucket
    for level_name, bucket in buckets.items():
        if len(bucket) > PAIR_CAP:
            random.shuffle(bucket)
            buckets[level_name] = bucket[:PAIR_CAP]
            if level_name == "L1":
                l1[:] = buckets[level_name]
            elif level_name == "L2":
                l2[:] = buckets[level_name]
            else:
                l3[:] = buckets[level_name]

    print(f"  Final: L1={len(l1):,} L2={len(l2):,} L3={len(l3):,}")
    return l1, l2, l3


def _pick_best_entry(entries: list[LexEntry]) -> LexEntry | None:
    """Pick an entry preferring ones with non-empty SCA."""
    for e in entries:
        if e[2]:  # has SCA
            return e
    return entries[0] if entries else None


def _lookup_sca(
    lexicon: dict[tuple[str, str], list[LexEntry]],
    iso: str,
    concept_id: str,
    word: str,
    ipa: str = "",
) -> str:
    """Try to find the SCA encoding for a given word from the lexicon.

    Falls back to computing SCA on-the-fly from IPA if all lookups fail.
    """
    entries = lexicon.get((iso, concept_id), [])
    # Exact word match first
    for e in entries:
        if e[0] == word and e[2]:
            return e[2]
    # Any entry with SCA for this (iso, concept)
    for e in entries:
        if e[2]:
            return e[2]
    # Use the word index for cross-concept fallback (fast)
    sca = _word_sca_index.get((iso, word), "")
    if sca:
        return sca
    # Last resort: compute from IPA on-the-fly
    if ipa:
        return ipa_to_sound_class(ipa)
    return ""


# ---------------------------------------------------------------------------
# Step 4: False positives
# ---------------------------------------------------------------------------

def generate_false_positives(
    lexicon: dict[tuple[str, str], list[LexEntry]],
    concept_langs: dict[str, list[str]],
    lang_paths: dict[str, list[str]],
    family_map: dict[str, str],
    similarity_pairs: list[dict[str, str]],
) -> list[dict[str, str]]:
    """Cross-family pairs with same concept and SCA similarity >= 0.5."""
    print("Step 4: Generating false positives ...")
    fps: list[dict[str, str]] = []

    # 4a: From lexicon — cross-family same-concept pairs
    concepts_processed = 0
    for cid, langs in concept_langs.items():
        if len(fps) >= PAIR_CAP:
            break
        concepts_processed += 1
        if concepts_processed % 500 == 0:
            print(f"  Concept {concepts_processed}/{len(concept_langs)} "
                  f"(fps={len(fps):,})")

        # Group by family
        family_groups: dict[str, list[str]] = defaultdict(list)
        for iso in langs:
            fam = get_top_family(iso, lang_paths, family_map)
            family_groups[fam].append(iso)

        families = list(family_groups.keys())
        if len(families) < 2:
            continue

        # Cross-family pairs
        pair_count = 0
        for fi in range(len(families)):
            for fj in range(fi + 1, len(families)):
                if len(fps) >= PAIR_CAP:
                    break
                if pair_count >= MAX_CROSS_FAMILY_PAIRS_PER_CONCEPT:
                    break

                fam_a_langs = family_groups[families[fi]]
                fam_b_langs = family_groups[families[fj]]

                # Sample one from each
                iso_a = random.choice(fam_a_langs)
                iso_b = random.choice(fam_b_langs)

                entries_a = lexicon.get((iso_a, cid), [])
                entries_b = lexicon.get((iso_b, cid), [])
                if not entries_a or not entries_b:
                    continue

                ea = _pick_best_entry(entries_a)
                eb = _pick_best_entry(entries_b)
                if ea is None or eb is None:
                    continue

                sca_sim = normalised_similarity(ea[2], eb[2]) if ea[2] and eb[2] else 0.0
                if sca_sim < 0.5:
                    continue

                rec = make_pair_record(
                    iso_a, ea[0], ea[1], ea[2],
                    iso_b, eb[0], eb[1], eb[2],
                    cid, "false_positive", lang_paths,
                    source="lexicon",
                    score_override=sca_sim,
                )
                fps.append(rec)
                pair_count += 1

    print(f"  From lexicon: {len(fps):,} false positives")

    # 4b: From similarity_pairs file
    sim_added = 0
    for row in similarity_pairs:
        if len(fps) >= PAIR_CAP:
            break
        lang_a = row.get("Lang_A", "")
        lang_b = row.get("Lang_B", "")
        if not lang_a or not lang_b:
            continue

        fam_a = get_top_family(lang_a, lang_paths, family_map)
        fam_b = get_top_family(lang_b, lang_paths, family_map)
        if fam_a == fam_b:
            continue  # only want cross-family

        cid = row.get("Concept_ID", "")
        sca_a = _lookup_sca(lexicon, lang_a, cid, row.get("Word_A", ""),
                            row.get("IPA_A", ""))
        sca_b = _lookup_sca(lexicon, lang_b, cid, row.get("Word_B", ""),
                            row.get("IPA_B", ""))

        score_str = row.get("Score", "0")
        try:
            score = float(score_str)
        except (ValueError, TypeError):
            score = 0.0

        if sca_a and sca_b:
            sca_sim = normalised_similarity(sca_a, sca_b)
        else:
            sca_sim = score

        if sca_sim < 0.5:
            continue

        rec = make_pair_record(
            lang_a, row.get("Word_A", ""), row.get("IPA_A", ""), sca_a,
            lang_b, row.get("Word_B", ""), row.get("IPA_B", ""), sca_b,
            cid, "false_positive", lang_paths,
            source=row.get("Source", "similarity"),
            score_override=sca_sim,
        )
        fps.append(rec)
        sim_added += 1

    print(f"  Added {sim_added:,} from similarity pairs")

    if len(fps) > PAIR_CAP:
        random.shuffle(fps)
        fps = fps[:PAIR_CAP]

    print(f"  Final false positives: {len(fps):,}")
    return fps


# ---------------------------------------------------------------------------
# Step 5: True negatives
# ---------------------------------------------------------------------------

def generate_true_negatives(
    lexicon: dict[tuple[str, str], list[LexEntry]],
    lang_paths: dict[str, list[str]],
    family_map: dict[str, str],
) -> list[dict[str, str]]:
    """Random cross-family pairs with different concepts and SCA sim < 0.3."""
    print("Step 5: Generating true negatives ...")
    negs: list[dict[str, str]] = []

    # Build index of all (iso, concept_id) keys for sampling
    all_keys = list(lexicon.keys())
    if len(all_keys) < 2:
        print("  Not enough lexicon entries for true negatives.")
        return negs

    attempts = 0
    while len(negs) < PAIR_CAP and attempts < TRUE_NEG_SAMPLE_ATTEMPTS:
        attempts += 1
        if attempts % 50_000 == 0:
            print(f"  Attempt {attempts:,}, negatives so far: {len(negs):,}")

        # Pick two random entries
        key_a = random.choice(all_keys)
        key_b = random.choice(all_keys)
        iso_a, cid_a = key_a
        iso_b, cid_b = key_b

        # Must be different concepts
        if cid_a == cid_b:
            continue
        # Must be different families
        fam_a = get_top_family(iso_a, lang_paths, family_map)
        fam_b = get_top_family(iso_b, lang_paths, family_map)
        if fam_a == fam_b:
            continue
        # Must be different languages
        if iso_a == iso_b:
            continue

        entries_a = lexicon[key_a]
        entries_b = lexicon[key_b]
        ea = _pick_best_entry(entries_a)
        eb = _pick_best_entry(entries_b)
        if ea is None or eb is None:
            continue
        if not ea[2] or not eb[2]:
            continue

        sca_sim = normalised_similarity(ea[2], eb[2])
        if sca_sim >= 0.4:
            continue

        # Use concept_a for the record (arbitrary; both concepts are different)
        rec = make_pair_record(
            iso_a, ea[0], ea[1], ea[2],
            iso_b, eb[0], eb[1], eb[2],
            f"{cid_a} / {cid_b}", "true_negative", lang_paths,
            source="random_sample",
            score_override=sca_sim,
        )
        negs.append(rec)

    print(f"  Generated {len(negs):,} true negatives in {attempts:,} attempts")
    return negs


# ---------------------------------------------------------------------------
# Step 6: Borrowings
# ---------------------------------------------------------------------------

def generate_borrowings(
    borrowing_pairs: list[dict[str, str]],
    lexicon: dict[tuple[str, str], list[LexEntry]],
    lang_paths: dict[str, list[str]],
) -> list[dict[str, str]]:
    """Process borrowing pairs from WOLD."""
    print("Step 6: Processing borrowing pairs ...")
    rows: list[dict[str, str]] = []

    for row in borrowing_pairs:
        lang_a = row.get("Lang_A", "")
        lang_b = row.get("Lang_B", "")
        if not lang_a or not lang_b:
            continue

        cid = row.get("Concept_ID", "")
        word_a = row.get("Word_A", "")
        word_b = row.get("Word_B", "")
        ipa_a = row.get("IPA_A", "")
        ipa_b = row.get("IPA_B", "")

        sca_a = _lookup_sca(lexicon, lang_a, cid, word_a, ipa_a)
        sca_b = _lookup_sca(lexicon, lang_b, cid, word_b, ipa_b)

        score_str = row.get("Score", "0")
        try:
            score = float(score_str)
        except (ValueError, TypeError):
            score = 0.0

        if sca_a and sca_b:
            sca_sim = normalised_similarity(sca_a, sca_b)
        else:
            sca_sim = score

        rec = make_pair_record(
            lang_a, word_a, ipa_a, sca_a,
            lang_b, word_b, ipa_b, sca_b,
            cid, "borrowing", lang_paths,
            source=row.get("Source", "wold"),
            score_override=sca_sim,
        )
        rows.append(rec)

    print(f"  Processed {len(rows):,} borrowing pairs")
    return rows


# ---------------------------------------------------------------------------
# Step 7: Religious subsets
# ---------------------------------------------------------------------------

def generate_religious_pairs(
    all_pairs: list[dict[str, str]],
    lexicon: dict[tuple[str, str], list[LexEntry]],
    concept_langs: dict[str, list[str]],
    lang_paths: dict[str, list[str]],
    family_map: dict[str, str],
) -> tuple[
    list[dict[str, str]],
    dict[str, list[dict[str, str]]],
    dict[str, list[dict[str, str]]],
]:
    """Filter existing pairs for religious concepts and generate additional ones.

    Returns (all_religious_pairs, per_family_dict, subdomain_dict).
    """
    print("Step 7: Building religious concept subsets ...")

    # 7a: Filter all existing pairs — SKIP compound concept IDs (true negatives)
    religious: list[dict[str, str]] = []
    skipped_compound = 0
    for rec in all_pairs:
        cid = rec.get("Concept_ID", "")
        # Skip compound concept IDs (true negatives use "cid_a / cid_b")
        if "/" in cid:
            skipped_compound += 1
            continue
        if is_religious(cid):
            religious.append(rec)

    print(f"  Filtered {len(religious):,} religious pairs from existing data "
          f"(skipped {skipped_compound:,} compound IDs)")

    # 7b: Generate additional within-family and cross-family pairs for
    #     religious concepts not already covered
    religious_concepts = [c for c in concept_langs if is_religious(c)]
    print(f"  Found {len(religious_concepts)} religious concepts in lexicon")

    additional = 0
    for cid in religious_concepts:
        langs = concept_langs[cid]
        if len(langs) < 2:
            continue

        # Group by family
        family_groups: dict[str, list[str]] = defaultdict(list)
        for iso in langs:
            fam = get_top_family(iso, lang_paths, family_map)
            family_groups[fam].append(iso)

        # Within-family pairs
        for fam, fam_langs in family_groups.items():
            if len(fam_langs) < 2:
                continue
            sample_size = min(len(fam_langs), 20)
            sampled = random.sample(fam_langs, sample_size) if len(fam_langs) > sample_size else fam_langs
            for i in range(len(sampled)):
                for j in range(i + 1, len(sampled)):
                    iso_a, iso_b = sampled[i], sampled[j]
                    entries_a = lexicon.get((iso_a, cid), [])
                    entries_b = lexicon.get((iso_b, cid), [])
                    if not entries_a or not entries_b:
                        continue
                    ea = _pick_best_entry(entries_a)
                    eb = _pick_best_entry(entries_b)
                    if ea is None or eb is None:
                        continue
                    sca_sim = normalised_similarity(ea[2], eb[2]) if ea[2] and eb[2] else 0.0
                    _, level = compute_distance(iso_a, iso_b, lang_paths)
                    label = "true_cognate" if level in ("L1", "L2", "L3") and sca_sim >= 0.4 else "false_positive"
                    rec = make_pair_record(
                        iso_a, ea[0], ea[1], ea[2],
                        iso_b, eb[0], eb[1], eb[2],
                        cid, label, lang_paths,
                        source="religious_gen",
                        score_override=sca_sim,
                    )
                    religious.append(rec)
                    additional += 1

        # Cross-family pairs (limited)
        families = list(family_groups.keys())
        if len(families) >= 2:
            cross_count = 0
            for fi in range(len(families)):
                for fj in range(fi + 1, len(families)):
                    if cross_count >= 10:
                        break
                    iso_a = random.choice(family_groups[families[fi]])
                    iso_b = random.choice(family_groups[families[fj]])
                    entries_a = lexicon.get((iso_a, cid), [])
                    entries_b = lexicon.get((iso_b, cid), [])
                    if not entries_a or not entries_b:
                        continue
                    ea = _pick_best_entry(entries_a)
                    eb = _pick_best_entry(entries_b)
                    if ea is None or eb is None:
                        continue
                    sca_sim = normalised_similarity(ea[2], eb[2]) if ea[2] and eb[2] else 0.0
                    rec = make_pair_record(
                        iso_a, ea[0], ea[1], ea[2],
                        iso_b, eb[0], eb[1], eb[2],
                        cid, "false_positive", lang_paths,
                        source="religious_gen",
                        score_override=sca_sim,
                    )
                    religious.append(rec)
                    additional += 1
                    cross_count += 1

    print(f"  Generated {additional:,} additional religious pairs")
    print(f"  Total religious pairs: {len(religious):,}")

    # Build per-family subsets
    per_family: dict[str, list[dict[str, str]]] = defaultdict(list)
    for rec in religious:
        fam_a = get_top_family(rec["Lang_A"], lang_paths, family_map)
        fam_b = get_top_family(rec["Lang_B"], lang_paths, family_map)
        if fam_a in _TOP_FAMILY_SET:
            per_family[fam_a].append(rec)
        if fam_b in _TOP_FAMILY_SET and fam_b != fam_a:
            per_family[fam_b].append(rec)

    # Build sub-domain subsets
    subdomain_pairs: dict[str, list[dict[str, str]]] = {}
    for sd_name, sd_concepts in RELIGIOUS_SUBDOMAINS.items():
        sd_list: list[dict[str, str]] = []
        for rec in religious:
            cid = rec.get("Concept_ID", "")
            if _in_subdomain(cid, sd_concepts):
                sd_list.append(rec)
        subdomain_pairs[sd_name] = sd_list
        print(f"  Sub-domain {sd_name}: {len(sd_list):,} pairs")

    return religious, dict(per_family), subdomain_pairs


# ---------------------------------------------------------------------------
# Step 8: Timespan stratification
# ---------------------------------------------------------------------------

def stratify_by_timespan(
    all_pairs: list[dict[str, str]],
) -> dict[str, list[dict[str, str]]]:
    """Split all pairs into timespan buckets."""
    print("Step 8: Stratifying by timespan ...")
    buckets: dict[str, list[dict[str, str]]] = defaultdict(list)
    for rec in all_pairs:
        ts = rec.get("Timespan", "modern_modern")
        buckets[ts].append(rec)
    for ts, pairs in sorted(buckets.items()):
        print(f"  {ts}: {len(pairs):,}")
    return dict(buckets)


# ---------------------------------------------------------------------------
# Step 9: Per-family sets
# ---------------------------------------------------------------------------

def stratify_by_family(
    all_pairs: list[dict[str, str]],
    lang_paths: dict[str, list[str]],
    family_map: dict[str, str],
) -> dict[str, list[dict[str, str]]]:
    """Split pairs into per-family buckets for TOP_FAMILIES."""
    print("Step 9: Stratifying by family ...")
    buckets: dict[str, list[dict[str, str]]] = defaultdict(list)
    for rec in all_pairs:
        fam_a = get_top_family(rec["Lang_A"], lang_paths, family_map)
        fam_b = get_top_family(rec["Lang_B"], lang_paths, family_map)
        # Include pair if either language belongs to a top family
        if fam_a == fam_b and fam_a in _TOP_FAMILY_SET:
            buckets[fam_a].append(rec)
        else:
            # Cross-family pair: include in both relevant families
            if fam_a in _TOP_FAMILY_SET:
                buckets[fam_a].append(rec)
            if fam_b in _TOP_FAMILY_SET:
                buckets[fam_b].append(rec)

    for fam in TOP_FAMILIES:
        count = len(buckets.get(fam, []))
        print(f"  {fam}: {count:,}")
    return dict(buckets)


# ---------------------------------------------------------------------------
# Step 10: Statistics
# ---------------------------------------------------------------------------

def write_stats(
    output_dir: Path,
    l1: list, l2: list, l3: list,
    fps: list, negs: list, borrows: list,
    religious: list,
    timespan_buckets: dict[str, list],
    family_buckets: dict[str, list],
    religious_by_family: dict[str, list],
) -> None:
    """Write validation_stats.tsv with summary counts."""
    print("Step 10: Writing statistics ...")
    stats_path = output_dir / "validation_stats.tsv"
    rows: list[tuple[str, str, str]] = []

    rows.append(("Category", "Subset", "Count"))
    rows.append(("true_cognates", "L1", str(len(l1))))
    rows.append(("true_cognates", "L2", str(len(l2))))
    rows.append(("true_cognates", "L3", str(len(l3))))
    rows.append(("true_cognates", "total", str(len(l1) + len(l2) + len(l3))))
    rows.append(("false_positives", "all", str(len(fps))))
    rows.append(("true_negatives", "all", str(len(negs))))
    rows.append(("borrowings", "all", str(len(borrows))))
    rows.append(("religious", "all", str(len(religious))))

    for ts_name in ["ancient_ancient", "ancient_modern", "medieval_modern", "modern_modern"]:
        count = len(timespan_buckets.get(ts_name, []))
        rows.append(("timespan", ts_name, str(count)))

    for fam in TOP_FAMILIES:
        count = len(family_buckets.get(fam, []))
        rows.append(("per_family", fam, str(count)))

    for fam in sorted(religious_by_family.keys()):
        count = len(religious_by_family[fam])
        rows.append(("religious_by_family", fam, str(count)))

    total_all = len(l1) + len(l2) + len(l3) + len(fps) + len(negs) + len(borrows)
    rows.append(("total", "all_pairs", str(total_all)))

    # Compute label distribution
    label_counts: dict[str, int] = defaultdict(int)
    for pairs_list in [l1, l2, l3, fps, negs, borrows]:
        for rec in pairs_list:
            label_counts[rec.get("Label", "unknown")] += 1
    for label, count in sorted(label_counts.items()):
        rows.append(("label_distribution", label, str(count)))

    # Compute era distribution
    era_counts: dict[str, int] = defaultdict(int)
    for pairs_list in [l1, l2, l3, fps, negs, borrows]:
        for rec in pairs_list:
            ts = rec.get("Timespan", "unknown")
            era_counts[ts] += 1
    for era, count in sorted(era_counts.items()):
        rows.append(("era_distribution", era, str(count)))

    # Unique languages
    all_langs: set[str] = set()
    for pairs_list in [l1, l2, l3, fps, negs, borrows]:
        for rec in pairs_list:
            all_langs.add(rec.get("Lang_A", ""))
            all_langs.add(rec.get("Lang_B", ""))
    all_langs.discard("")
    rows.append(("coverage", "unique_languages", str(len(all_langs))))

    # Unique concepts
    all_concepts: set[str] = set()
    for pairs_list in [l1, l2, l3, fps, negs, borrows]:
        for rec in pairs_list:
            cid = rec.get("Concept_ID", "")
            if cid:
                all_concepts.add(cid)
    rows.append(("coverage", "unique_concepts", str(len(all_concepts))))

    # Unique families
    family_set: set[str] = set()
    for lang in all_langs:
        fam = get_top_family(lang, _global_lang_paths, _global_family_map)
        family_set.add(fam)
    rows.append(("coverage", "unique_families", str(len(family_set))))

    with stats_path.open("w", encoding="utf-8", newline="") as fh:
        writer = csv.writer(fh, delimiter="\t")
        for row in rows:
            writer.writerow(row)

    print(f"  Wrote stats to {stats_path.relative_to(REPO_ROOT)}")
    print(f"  Total pairs across main sets: {total_all:,}")
    print(f"  Unique languages: {len(all_langs):,}")
    print(f"  Unique concepts: {len(all_concepts):,}")


# Global references set in main() for use in stats helper
_global_lang_paths: dict[str, list[str]] = {}
_global_family_map: dict[str, str] = {}

# Fast word→SCA index: (iso, word) → sca, built in main()
_word_sca_index: dict[tuple[str, str], str] = {}


def build_word_sca_index(
    lexicon: dict[tuple[str, str], list[LexEntry]],
) -> dict[tuple[str, str], str]:
    """Build (iso, word) → SCA index for fast cross-concept lookups."""
    idx: dict[tuple[str, str], str] = {}
    for (iso, _cid), entries in lexicon.items():
        for word, _ipa, sca in entries:
            if sca and (iso, word) not in idx:
                idx[(iso, word)] = sca
    return idx


# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------

def main() -> None:
    global _global_lang_paths, _global_family_map

    random.seed(SEED)
    print("=" * 70)
    print("build_validation_sets.py — Stratified ML Validation Datasets")
    print("=" * 70)

    # ----- Step 1: Build and resolve phylogenetic tree --------------------
    print("\nStep 1: Building phylogenetic tree ...")

    if not FAMILY_MAP_PATH.exists():
        print(f"ERROR: family_map.json not found at {FAMILY_MAP_PATH}", file=sys.stderr)
        sys.exit(1)

    with FAMILY_MAP_PATH.open(encoding="utf-8") as fh:
        family_map: dict[str, str] = json.load(fh)
    print(f"  Loaded family_map.json: {len(family_map):,} languages")

    raw_tree = build_raw_tree()
    tree = resolve_tree(raw_tree, family_map)
    lang_paths = build_lang_paths(tree)
    print(f"  Tree covers {len(lang_paths):,} languages")

    # Store globals for stats
    _global_lang_paths = lang_paths
    _global_family_map = family_map

    # Write phylo_tree.json
    OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
    tree_path = OUTPUT_DIR / "phylo_tree.json"
    with tree_path.open("w", encoding="utf-8") as fh:
        json.dump(tree, fh, indent=2, ensure_ascii=False)
    print(f"  Wrote {tree_path.relative_to(REPO_ROOT)}")

    # Quick distance sanity checks
    for pair, expected in [
        (("eng", "ang"), "L1"),
        (("eng", "deu"), "L2"),
        (("eng", "fra"), "L3"),
        (("eng", "fin"), "L4"),
    ]:
        _, level = compute_distance(pair[0], pair[1], lang_paths)
        status = "OK" if level == expected else f"MISMATCH (got {level})"
        print(f"  Distance {pair[0]}-{pair[1]}: {level} ({status})")

    # ----- Step 2: Load data ----------------------------------------------
    print("\nStep 2: Loading data ...")

    if not LEXICONS_DIR.exists():
        print(f"ERROR: Lexicons directory not found: {LEXICONS_DIR}", file=sys.stderr)
        sys.exit(1)

    lexicon = load_lexicons(LEXICONS_DIR)
    concept_langs = build_concept_index(lexicon)
    print(f"  {len(concept_langs):,} unique concepts across all lexicons")

    # Build fast word→SCA index for cross-concept lookups
    global _word_sca_index
    _word_sca_index = build_word_sca_index(lexicon)
    print(f"  Built word-SCA index: {len(_word_sca_index):,} entries")

    inherited_path = COGNATE_DIR / "cognate_pairs_inherited.tsv"
    borrowing_path = COGNATE_DIR / "cognate_pairs_borrowing.tsv"
    similarity_path = COGNATE_DIR / "cognate_pairs_similarity.tsv"

    # For very large files, stream-sample instead of loading everything
    print("  Loading cognate pair files (may take a moment for large files) ...")
    inherited_pairs = _load_cognate_pairs_sampled(inherited_path, max_rows=200_000)
    borrowing_pairs = load_cognate_pairs(borrowing_path)
    similarity_pairs = load_cognate_pairs(similarity_path)

    # ----- Step 3: True cognates ------------------------------------------
    print("\nStep 3: Generating true cognate pairs ...")
    l1, l2, l3 = generate_true_cognates(
        lexicon, concept_langs, lang_paths, family_map, inherited_pairs,
    )

    write_pairs_tsv(OUTPUT_DIR / "true_cognates_L1.tsv", l1)
    write_pairs_tsv(OUTPUT_DIR / "true_cognates_L2.tsv", l2)
    write_pairs_tsv(OUTPUT_DIR / "true_cognates_L3.tsv", l3)

    # ----- Step 4: False positives ----------------------------------------
    print("\nStep 4: Generating false positives ...")
    fps = generate_false_positives(
        lexicon, concept_langs, lang_paths, family_map, similarity_pairs,
    )
    write_pairs_tsv(OUTPUT_DIR / "false_positives.tsv", fps)

    # ----- Step 5: True negatives -----------------------------------------
    print("\nStep 5: Generating true negatives ...")
    negs = generate_true_negatives(lexicon, lang_paths, family_map)
    write_pairs_tsv(OUTPUT_DIR / "true_negatives.tsv", negs)

    # ----- Step 6: Borrowings --------------------------------------------
    print("\nStep 6: Processing borrowings ...")
    borrows = generate_borrowings(borrowing_pairs, lexicon, lang_paths)
    write_pairs_tsv(OUTPUT_DIR / "borrowings.tsv", borrows)

    # ----- Collect all pairs for downstream splits ------------------------
    all_pairs: list[dict[str, str]] = l1 + l2 + l3 + fps + negs + borrows

    # ----- Step 7: Religious subsets --------------------------------------
    print("\nStep 7: Building religious subsets ...")
    religious, religious_by_family, subdomain_pairs = generate_religious_pairs(
        all_pairs, lexicon, concept_langs, lang_paths, family_map,
    )

    # Write to religious/ subdirectory
    rel_dir = OUTPUT_DIR / "religious"
    rel_dir.mkdir(parents=True, exist_ok=True)
    write_pairs_tsv(rel_dir / "all_pairs.tsv", religious)

    # Split by label
    rel_true_cog = [r for r in religious if r.get("Label") == "true_cognate"]
    rel_false_pos = [r for r in religious if r.get("Label") == "false_positive"]
    rel_borrowings = [r for r in religious if r.get("Label") == "borrowing"]
    write_pairs_tsv(rel_dir / "true_cognates.tsv", rel_true_cog)
    write_pairs_tsv(rel_dir / "false_positives.tsv", rel_false_pos)
    write_pairs_tsv(rel_dir / "borrowings.tsv", rel_borrowings)

    # Sub-domain files
    for sd_name, sd_pairs in sorted(subdomain_pairs.items()):
        write_pairs_tsv(rel_dir / f"{sd_name}.tsv", sd_pairs)

    # Per-family under religious/by_family/
    rel_family_dir = rel_dir / "by_family"
    rel_family_dir.mkdir(parents=True, exist_ok=True)
    for fam, fam_pairs in sorted(religious_by_family.items()):
        write_pairs_tsv(rel_family_dir / f"{fam}.tsv", fam_pairs)

    # Clean up old flat files if they exist
    old_religious = OUTPUT_DIR / "religious_pairs.tsv"
    if old_religious.exists():
        old_religious.unlink()
        print(f"  Removed old {old_religious.relative_to(REPO_ROOT)}")
    old_rel_family = OUTPUT_DIR / "religious_by_family"
    if old_rel_family.exists() and old_rel_family.is_dir():
        import shutil
        shutil.rmtree(old_rel_family)
        print(f"  Removed old {old_rel_family.relative_to(REPO_ROOT)}")

    # ----- Step 8: Timespan stratification --------------------------------
    print("\nStep 8: Stratifying by timespan ...")
    timespan_buckets = stratify_by_timespan(all_pairs)
    for ts_name in ["ancient_ancient", "ancient_modern", "medieval_modern", "modern_modern"]:
        ts_pairs = timespan_buckets.get(ts_name, [])
        write_pairs_tsv(OUTPUT_DIR / f"timespan_{ts_name}.tsv", ts_pairs)

    # ----- Step 9: Per-family sets ----------------------------------------
    print("\nStep 9: Writing per-family sets ...")
    family_buckets = stratify_by_family(all_pairs, lang_paths, family_map)

    per_family_dir = OUTPUT_DIR / "per_family"
    per_family_dir.mkdir(parents=True, exist_ok=True)
    for fam in TOP_FAMILIES:
        fam_pairs = family_buckets.get(fam, [])
        write_pairs_tsv(per_family_dir / f"{fam}.tsv", fam_pairs)

    # ----- Step 10: Statistics --------------------------------------------
    print("\nStep 10: Writing statistics ...")
    write_stats(
        OUTPUT_DIR,
        l1, l2, l3,
        fps, negs, borrows,
        religious,
        timespan_buckets,
        family_buckets,
        religious_by_family,
    )

    print("\n" + "=" * 70)
    print("Done!  Output written to:")
    print(f"  {OUTPUT_DIR.relative_to(REPO_ROOT)}/")
    print("=" * 70)


def _load_cognate_pairs_sampled(
    path: Path,
    max_rows: int = 200_000,
) -> list[dict[str, str]]:
    """Load cognate pairs with reservoir sampling for very large files.

    For files with millions of rows, we use reservoir sampling to get a
    representative sample of at most *max_rows* entries.
    """
    if not path.exists():
        print(f"  WARNING: {path} not found, skipping.")
        return []

    # First pass: count rows to decide whether to sample
    total = 0
    with path.open(encoding="utf-8") as fh:
        header = fh.readline()  # skip header
        if not header:
            return []
        for _ in fh:
            total += 1

    print(f"  {path.name}: {total:,} rows total", end="")

    if total <= max_rows:
        # Small enough — load everything
        print(" (loading all)")
        return load_cognate_pairs(path)

    # Reservoir sampling
    print(f" (sampling {max_rows:,})")
    reservoir: list[dict[str, str]] = []
    with path.open(encoding="utf-8") as fh:
        reader = csv.DictReader(fh, delimiter="\t")
        for i, row in enumerate(reader):
            if i < max_rows:
                reservoir.append(dict(row))
            else:
                j = random.randint(0, i)
                if j < max_rows:
                    reservoir[j] = dict(row)

    print(f"  Sampled {len(reservoir):,} pairs from {path.name}")
    return reservoir


if __name__ == "__main__":
    main()