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

V2: Major quality overhaul based on Gemini review of 6,938 chunks.
    Fixes: HTML noise, URN placeholders, figure-axis gibberish, author
    fragments, excessive overlap, URL-only captions.
V5: Data cleaning overhaul based on manual review of 4,567 chunks.
    Fixes: OCR 'ris' stripping restoration, stronger reference-list
    filtering, caption merging, content-hash dedup, section path validation.
V6: Sanitizer based on Gemini 3.1 Pro Preview audit of 4,060 chunks.
    Fixes: context-dependent k/e/Pa OCR fixes, +→C PDF glyph fix,
    digit-density garbage filter, strengthened ref/boilerplate filtering,
    expanded section path validation.

Output: rag/chunks.jsonl  (one JSON object per line)
"""

import json
import re
import sys
import argparse
import hashlib
from pathlib import Path
from typing import Optional

import tiktoken

# ── Configuration ──────────────────────────────────────────────────────────────
PARSED_DIR = Path(__file__).parent / "parsed"
PARSED_LEVANTE_DIR = Path(__file__).parent / "parsed_levante"
OUTPUT_FILE = Path(__file__).parent / "chunks.jsonl"
OUTPUT_LEVANTE_FILE = Path(__file__).parent / "chunks_levante.jsonl"

MAX_TOKENS = 1000       # target cap per chunk
TABLE_MAX_TOKENS = 1200 # hard cap for table chunks (larger allowed)
MIN_TOKENS = 80         # merge if below this
MIN_QUALITY_TOKENS = 30 # absolute minimum to emit a chunk
OVERLAP_RATIO = 0.05    # 5% overlap (reduced from 10% — review showed excessive)
ABSTRACT_SOLO = True    # abstract always gets its own chunk

# Sections to EXCLUDE from RAG (noise for retrieval)
EXCLUDE_SECTIONS = {
    # Academic boilerplate
    "references", "bibliography", "acknowledgements", "acknowledgments",
    "author information", "authors and affiliations", "contributions",
    "author contributions", "corresponding author", "corresponding authors",
    "ethics declarations", "competing interests", "conflict of interest",
    "additional information", "supplementary information", "supplementary material",
    "supplementary materials", "supplementary data",
    "rights and permissions", "about this article", "cite this article",
    "this article is cited by", "data availability", "data availability statement",
    "code availability", "code and data availability", "declarations", "funding",
    "financial support", "review statement", "disclaimer",
    "change history", "ethics and inclusion statement",
    "information & authors", "submission history", "notes",
    "peer review information", "peer review", "publisher's note",
    # V3: Front/back matter from Gemini review
    "lead authors", "contributing authors", "how to cite",
    "table of contents", "contents", "orcidids", "orcids",
    "correspondence", "correspondence to", "edited by", "reviewed by",
    "copyright", "open access", "license",
    "author affiliations", "affiliations",
    "create a new account",  # web UI bleed
    # V6: Boilerplate / publisher noise
    "general rights", "take down policy", "preamble",
    "citation for published version", "citation for published version:",
    "fair data use statement",
    "resources",  # PMC sidebar
    # Journal navigation (Nature, Wiley, AGU, PNAS, etc.)
    "explore content", "about the journal", "publish with us",
    "search", "quick links", "nature.com sitemap",
    "about nature portfolio", "discover content", "publishing policies",
    "author & researcher services", "libraries & institutions",
    "advertising & partnerships", "professional development",
    "regional websites", "similar content being viewed by others",
    "access options", "additional access options:", "subjects",
    "access through your institution", "buy or subscribe",
    # Wiley-specific
    "citing literature", "article metrics", "related articles",
    "connect with wiley", "change password", "forgot your password?",
    "request username", "login", "login / register",
    # PNAS-specific
    "sign up for pnas alerts", "metrics",
    # PMC-specific
    "links to ncbi databases", "cited by other articles",
    # IOP-specific
    "you may also like",
    # General
    "privacy preference center", "manage consent preferences",
    "essential cookies", "performance cookies", "functional cookies",
    "cookie list", "reviewpaper",
}

# Text patterns that indicate HTML navigation noise
NOISE_PATTERNS = [
    r"^skip to (?:main )?content$",
    r"^skip to article$",
    r"^thank you for visiting nature\.com",
    r"^you are using a browser version",
    r"^the best experience",
    r"^internet explorer\b",
    r"^this site uses cookies",
    r"^we use cookies",
    r"^accept all cookies",
    r"^jump to content$",
    r"^page not found$",
    r"^accessibility links$",
    r"^advertisement$",
    r"^log in$",
    r"^sign up$",
    r"^sign in$",
    r"^subscribe$",
    r"^view all",
    # Wiley / AGU / journal navigation
    r"^privacy policy$",
    r"^terms of use$",
    r"^about cookies$",
    r"^manage cookies$",
    r"^accessibility$",
    r"^wiley online library$",
    r"^publication (?:award|policies|ethics)",
    r"^submit a paper$",
    r"^usage statistics$",
    r"^scientific ethics$",
    r"^copyright ©",
    r"^© \d{4}",
    r"^volume \d+.*issue \d+",
    r"^\d+ pages?$",
    r"^open access$",
    r"^full access$",
    r"^free access$",
    r"^download pdf$",
    r"^share$",
    r"^cite$",
    r"^figures?$",
    r"^tables?$",
    r"^related$",
    r"^information$",
    r"^metrics$",
    r"^\s*doi:\s*$",
    # V2: Additional patterns from Gemini review
    r"^download (?:xlsx|pdf|csv|print version)$",
    r"^open in figure viewer$",
    r"^check for updates",
    r"^verify currency and authenticity",
    r"^crossmark$",
    r"^scite metrics$",
    r"^share qr code$",
    r"^altmetric",
    r"^article has an altmetric score",
    r"^forgot your password",
    r"^request username$",
    r"^change password$",
    r"^congrats!$",
    r"^your password must have",
    r"^a lower case character",
    r"^an upper case character",
    r"^a special character",
    r"^or a digit$",
    r"^send email$",
    r"^recipient\(s\) will receive",
    r"^article activity alert$",
    r"^\d+ publications? \d+ supporting",
    r"^this article also appears in",
    r"^multiple terms:",
    r"^we are sorry, but your search",
    r"^turn mathjax on$",
    r"^creative commons attribution",
    r"^data protection$",
    r"^full-text xml$",
    r"^bibtex$",
    r"^ris$",
    r"^endnote$",
    r"^sciencedirect$",
    r"^journals & books$",
    r"^my account$",
    r"^dieses dialogfeld schlie",
    r"^datenschutzrichtlinie",
    r"^geoscientific model development",
    r"^pnas nexus$",
    # URN placeholders (Wiley media refs)
    r"^urn:x-wiley:",
    # Standalone URLs
    r"^https?://",
    # Journal/publisher names as standalone text
    r"^nature climate change$",
    r"^nature communications$",
    r"^nature food$",
    r"^nature reviews",
    r"^scientific data$",
    r"^communications earth",
]
_noise_re = [re.compile(p, re.IGNORECASE) for p in NOISE_PATTERNS]

# Additional exact-match noise strings (lowercased)
_noise_exact = {
    "pdf", "xml", "ris", "abstract", "figures", "references", "related",
    "information", "metrics", "share", "cite", "tables", "home",
    "about", "help", "contact", "feedback", "search",
    "open menu", "close menu", "sections", "tools",
    "download", "save", "print", "export", "alerts",
    "sign in", "register", "my account", "cart",
    "back to top", "next", "previous", "show more",
    "supplementary data", "supplementary materials",
    "view article", "crossref", "google scholar",
    "pubmed", "web of science",
}

# Labels to always skip
SKIP_LABELS = {"page_header", "page_footer", "footnote"}

# ── V5: OCR "ris" Restoration ─────────────────────────────────────────────────
# Docling PDF parser strips the ligature "ris" from words. This dictionary
# maps corrupted forms → correct forms using strict word boundaries.
# Only SAFE corrections with \b boundaries are included.

_OCR_RIS_CORRECTIONS = {
    # ── High-frequency scientific vocabulary ──
    r"\bcompaon\b": "comparison",
    r"\bcompaons\b": "comparisons",
    r"\bcharactetics\b": "characteristics",
    r"\bcharactetic\b": "characteristic",
    r"\bcharacteing\b": "characterising",
    r"\bcharacteed\b": "characterised",
    r"\bcharactee\b": "characterise",
    r"\bcharactees\b": "characterises",
    r"\bcharacteze\b": "characterize",
    r"\bcharactezed\b": "characterized",
    r"\bcharactezes\b": "characterizes",
    r"\bcharactezing\b": "characterizing",
    r"\bcharactezation\b": "characterization",
    r"\bparameteation\b": "parameterisation",
    r"\bparameteations\b": "parameterisations",
    r"\bparameteize\b": "parameterize",
    r"\bparameteized\b": "parameterized",
    r"\bparameteizes\b": "parameterizes",
    r"\bparameteizing\b": "parameterizing",
    r"\bparameteization\b": "parameterization",
    r"\bparameteizations\b": "parameterizations",
    r"\bcompe\b": "comprise",
    r"\bcomped\b": "comprised",
    r"\bcompes\b": "comprises",
    r"\bcomping\b": "comprising",
    r"\bsurpe\b": "surprise",
    r"\bsurped\b": "surprised",
    r"\bsurpes\b": "surprises",
    r"\bsurping\b": "surprising",
    r"\bsurpingly\b": "surprisingly",
    r"\bheutic\b": "heuristic",
    r"\bheutics\b": "heuristics",
    r"\bptine\b": "pristine",
    r"\btoum\b": "tourism",
    r"\btout\b": "tourist",
    r"\btouts\b": "tourists",
    r"\bnouhment\b": "nourishment",
    r"\bdeb\b": "debris",
    r"\ben\b": "risen",
    r"\baes\b": "arises",
    r"\baing\b": "arising",
    r"\bsummaed\b": "summarised",
    r"\bsummaes\b": "summarises",
    r"\bsummae\b": "summarise",
    r"\bregulaed\b": "regularised",
    r"\bregulae\b": "regularise",
    r"\bautherise\b": "authorise",
    r"\bautheed\b": "authorised",
    # ── Author names (case-sensitive) ──
    r"\bChtian\b": "Christian",
    r"\bChtians\b": "Christians",
    r"\bChtianity\b": "Christianity",
    r"\bChtopher\b": "Christopher",
    r"\bChtensen\b": "Christensen",
    r"\bChtoffersen\b": "Christoffersen",
    r"\bChtoph\b": "Christoph",
    r"\bChtophe\b": "Christophe",
    r"\bBbane\b": "Brisbane",
    r"\bKtie\b": "Katie",
    r"\bKtjansson\b": "Kristjansson",
    r"\bKtensen\b": "Kristensen",
    # ── Multi-word phrase fixes (safe context-dependent) ──
    r"\bgives e to\b": "gives rise to",
    r"\bgave e to\b": "gave rise to",
    r"\bgiven e to\b": "given rise to",
    r"\bgiving e to\b": "giving rise to",
    r"\bat k\b": "at risk",
    r"\bat k of\b": "at risk of",
    r"\bthe e of\b": "the rise of",
    r"\bthe e in\b": "the rise in",
    r"\bon the e\b": "on the rise",
    r"\btemperature e\b": "temperature rise",
    r"\bsea level e\b": "sea level rise",
    r"\bsea-level e\b": "sea-level rise",
    r"\bhigh k\b": "high risk",
    r"\blow k\b": "low risk",
    r"\bk assessment\b": "risk assessment",
    r"\bk assessments\b": "risk assessments",
    r"\bk factor\b": "risk factor",
    r"\bk factors\b": "risk factors",
    r"\bk management\b": "risk management",
    r"\bk of\b": "risk of",
    # V6: Expanded context-dependent "k" = risk
    r"\bk reduction\b": "risk reduction",
    r"\bk tolerance\b": "risk tolerance",
    r"\bk Information\b": "risk Information",
    r"\bflood k\b": "flood risk",
    r"\bfire k\b": "fire risk",
    r"\bmortality k\b": "mortality risk",
    r"\benvironmental k\b": "environmental risk",
    r"\bdisaster k\b": "disaster risk",
    r"\bclimate k\b": "climate risk",
    r"\bcompound ks\b": "compound risks",
    r"\bincreasing ks\b": "increasing risks",
    r"\bmeteo-hydrological ks\b": "meteo-hydrological risks",
    r"\bks ae\b": "risks arise",
    r"\bks from\b": "risks from",
    r"\bks and\b": "risks and",
    r"\bks to\b": "risks to",
    r"\bks of\b": "risks of",
    # V6: Expanded context-dependent "e" = rise
    r"\bGMSL e\b": "GMSL rise",
    r"\bing sea level\b": "rising sea level",
    r"\bing temperatures\b": "rising temperatures",
    r"\bing CO2\b": "rising CO2",
    r"\bing food prices\b": "rising food prices",
    r"\bmarked e\b": "marked rise",
    r"\brapid e\b": "rapid rise",
    r"\bglobal e\b": "global rise",
    # V6: "Pa" = Paris
    r"\bPa Agreement\b": "Paris Agreement",
    r"\bglobal climate cis\b": "global climate crisis",
    # V6: "+" → "C" PDF glyph fix
    r"\bHistorical C SSP\b": "Historical + SSP",
}

# Substring-based corrections — these are SAFE because the corrupted forms
# NEVER appear as valid English words/substrings. Used for compound words
# where \b word boundaries fail (e.g., "intercompaon", "compaons").
_OCR_SUBSTR_CORRECTIONS = {
    "compaon": "comparison",  # intercompaon, compaons, etc.
    "charactetic": "characteristic",  # charactetics, charactetically
    "characteing": "characterising",
    "characteed": "characterised",
    "characteze": "characterize",
    "charactezed": "characterized",
    "charactezing": "characterizing",
    "charactezation": "characterization",
    "parameteation": "parameterisation",
    "parameteization": "parameterization",
    "parameteize": "parameterize",
    "parameteized": "parameterized",
    # V6: Additional compound-word substrate fixes
    "enterpe": "enterprise",     # enterprise → enterpe
    "polaing": "polarising",     # polarising → polaing
    "Ctofanelli": "Cristofanelli",  # author name
    "Pco": "Prisco",              # author name
    "Kmer": "Krismer",             # author name
    " fi ": " fi",  # ligature: "signi fi cant" → "significant"
    " fl ": " fl",  # ligature: "in fl uence" → "influence"
    " fi\n": " fi\n",  # fi at line end — SKIP, leave as-is
}

# Build safe substring corrections: the fi/fl ligature fix needs special care.
# "signi fi cant" → rejoin then the word is correct: "significant"
# Strategy: remove the space around fi/fl to rejoin the word.
_OCR_LIGATURE_PATTERNS = [
    (re.compile(r'\b(\w+)\s+fi\s+(\w+)\b'), r'\1fi\2'),   # "signi fi cant" → "significant"
    (re.compile(r'\b(\w+)\s+fl\s+(\w+)\b'), r'\1fl\2'),   # "in fl uence" → "influence"
    (re.compile(r'\b(\w+)\s+ff\s+(\w+)\b'), r'\1ff\2'),   # "e ff ect" → "effect"
]

# Pre-compile word-boundary patterns for speed
_ocr_ris_compiled = [(re.compile(pat), repl) for pat, repl in _OCR_RIS_CORRECTIONS.items()]

# Pre-compile substring patterns (just plain string replace, no regex needed)
_ocr_substr_safe = [
    ("compaon", "comparison"),
    ("charactetic", "characteristic"),
    ("characteing", "characterising"),
    ("characteed", "characterised"),
    ("characteze", "characterize"),
    ("charactezed", "characterized"),
    ("charactezing", "characterizing"),
    ("charactezation", "characterization"),
    ("parameteation", "parameterisation"),
    ("parameteization", "parameterization"),
    ("parameteize", "parameterize"),
    ("parameteized", "parameterized"),
]


def fix_ocr_ris_stripping(text: str) -> str:
    """Fix systematic OCR corruption where 'ris' ligature is stripped from words.
    
    Three-pass approach:
    1. Word-boundary regex for isolated corrupted words
    2. Substring replacement for compound words (intercompaon, etc.)
    3. Ligature rejoining for split fi/fl/ff ligatures
    
    Safe: will never turn a valid word into something wrong.
    """
    # Pass 1: word-boundary corrections
    for pattern, replacement in _ocr_ris_compiled:
        text = pattern.sub(replacement, text)
    
    # Pass 2: substring corrections for compound words
    for old, new in _ocr_substr_safe:
        if old in text:
            text = text.replace(old, new)
    
    # Pass 3: rejoin split fi/fl/ff ligatures
    for pattern, replacement in _OCR_LIGATURE_PATTERNS:
        text = pattern.sub(replacement, text)
    
    return text


# ── V5: Garbage Section Path Detection ────────────────────────────────────────

_JOURNAL_NAME_SECTIONS = {
    "journal of advances in modeling earth systems",
    "reviews of geophysics",
    "geoscientific model development",
    "earth system dynamics",
    "earth system science data",
    "nature climate change",
    "nature communications",
    "nature geoscience",
    "nature food",
    "scientific data",
    "communications earth & environment",
    "environmental research letters",
    "global change biology",
    "journal of climate",
    "pnas",
    "pnas nexus",
    "science advances",
    "science",
}

_garbage_section_re = re.compile(
    r"^-?\d+\.?\d*\s+\d+\.?\d*[°ºÅ]?$"  # coordinate-like: "-25 60", "0 180°"
    r"|^\d{1,4}$"                         # bare numbers: "691"
    r"|^[°ºÅ\d\s.,-]+$"                   # pure numeric/degree strings
    r"|^\w{1,3}$"                          # single tiny word: "net"
    # V6: More garbage patterns
    r"|^PUBLISHED$"                        # Wiley boilerplate
    r"|^Data:?$"                           # floating label
    r"|^[A-Z]{2,4}\s+[A-Z]{2,4}$"         # chart legend: "WCA ECA", "CAU EAU"
    r"|^\d+\|"                             # axis tick prefix: "210|"
    r"|^Figures?\s*\d"                     # "Figures 414", "Figure 3"
    r"|^Supplementary\s+Table\b"           # "Supplementary Table 1..."
    r"|^NPP:\s*"                           # "NPP: MODIS" axis label
)


def is_garbage_section_path(section_name: str) -> bool:
    """Detect section paths that are garbled coordinates, journal names, or gibberish."""
    s = section_name.strip()
    if not s:
        return True
    sl = s.lower()
    if sl in _JOURNAL_NAME_SECTIONS:
        return True
    if _garbage_section_re.match(s):
        return True
    return False

# ── V2: Advanced Noise Detectors ──────────────────────────────────────────────

_urn_re = re.compile(r"urn:x-wiley:", re.IGNORECASE)
_url_only_re = re.compile(r"^\s*https?://\S+\s*$")
_affiliation_re = re.compile(
    r"(?:department|school|university|institute|laboratory|center|centre|faculty)"
    r"|(?:@[a-z0-9.-]+\.[a-z]{2,})"
    r"|(?:orcid\.org)"
    r"|(?:\d{4}-\d{4}-\d{4}-\d{3}[0-9X])",
    re.IGNORECASE
)
_degree_coord_re = re.compile(r"[°ºÅ][NSEW]", re.IGNORECASE)
_ui_button_re = re.compile(
    r"(?:Download|Open in figure viewer|PowerPoint|Print Version|Download XLSX"
    r"|Download PDF|Download CSV|Full-text XML|BibTeX|EndNote|RIS)",
    re.IGNORECASE
)


def is_urn_placeholder(text: str) -> bool:
    """Check if text is mostly Wiley URN placeholders."""
    lines = text.strip().split("\n")
    urn_lines = sum(1 for l in lines if _urn_re.search(l))
    return urn_lines > len(lines) * 0.5


def is_url_only(text: str) -> bool:
    """Check if text is just a URL."""
    return bool(_url_only_re.match(text.strip()))


def is_affiliation_fragment(text: str) -> bool:
    """Check if text is a standalone author affiliation chunk."""
    t = text.strip()
    # Short text with affiliation markers
    if len(t) > 500:
        return False
    matches = len(_affiliation_re.findall(t))
    words = len(t.split())
    if words < 3:
        return False
    # High density of affiliation markers = likely affiliation
    return matches >= 2 and matches / max(words, 1) > 0.05


def is_figure_axis_gibberish(text: str) -> bool:
    """Detect text extracted from figure axes/legends (word-salad)."""
    t = text.strip()
    if len(t) < 30:
        return False
    
    # Heuristic: many degree/coordinate symbols
    coord_matches = len(_degree_coord_re.findall(t))
    if coord_matches > 5:
        return True
    
    # Heuristic: very fragmented text (many very short lines)
    lines = [l.strip() for l in t.split("\n") if l.strip()]
    if len(lines) > 5:
        short_lines = sum(1 for l in lines if len(l.split()) <= 3)
        if short_lines / len(lines) > 0.7:
            return True
    
    # Heuristic: repetitive short fragments separated by spaces
    words = t.split()
    if len(words) > 20:
        # Count 1-2 char "words" (likely axis ticks)
        tiny = sum(1 for w in words if len(w) <= 2 and not w.isalpha())
        if tiny / len(words) > 0.3:
            return True
    
    # V3: Short verb-less lines = axis labels (e.g. "RCP8.5", "Buenos Aires")
    if len(lines) > 8:
        # Check if most lines lack verbs (proxy: no words ending in common verb suffixes)
        verbless = 0
        for line in lines:
            wds = line.split()
            has_verb_like = any(
                w.lower().endswith(('ing', 'tion', 'ted', 'tes', 'ses', 'ize', 'ise', 'ate'))
                for w in wds if len(w) > 3
            )
            if not has_verb_like and len(wds) <= 5:
                verbless += 1
        if verbless / len(lines) > 0.6:
            return True
    
    return False


def is_digit_heavy_garbage(text: str, threshold: float = 0.30) -> bool:
    """V6: Detect chunks that are mostly numbers/symbols (axis data, coordinates).
    
    If >30% of characters are digits and special symbols, this is likely
    visual garbage from chart axes, coordinate grids, or figure annotations.
    """
    t = text.strip()
    if len(t) < 50:
        return False
    symbols = sum(1 for c in t if c.isdigit() or c in "°±+-.,|<>[]{}()=×÷")
    return symbols / len(t) > threshold


def is_boilerplate_noise(text: str) -> bool:
    """V6: Detect publisher boilerplate, copyright text, and preprint disclaimers."""
    t = text.strip().lower()
    boilerplate_markers = [
        "copyright and moral rights",
        "research square preprints are preliminary",
        "in the format provided by the authors and unedited",
        "take down policy",
        "general rights",
        "citation for published version",
        "verify currency and authenticity",
        "version of record",
    ]
    matches = sum(1 for m in boilerplate_markers if m in t)
    return matches >= 2 or (matches >= 1 and len(t) < 300)


# V3/V5: Reference-like text detector (strengthened in V5)
_ref_pattern = re.compile(
    r"(?:[A-Z][a-z]+(?:,\s*[A-Z]\.?)+\s*(?:,|&|and)\s*){2,}"
    r"|(?:\(\d{4}[a-z]?\))"
    r"|(?:et\s+al\.?,\s*\d{4})"
    r"|(?:doi:\s*10\.\d{4,})",
    re.IGNORECASE
)
_doi_re_v5 = re.compile(r"10\.\d{4,9}/\S+")
_year_bracket_re = re.compile(r"\(\d{4}[a-z]?\)")

def is_reference_block(text: str) -> bool:
    """Detect if text is mostly bibliographic references.
    
    V5: Added DOI density and year-bracket density checks.
    V6: Lowered thresholds (DOI 5→3, years 8→6), added "et al." density.
    """
    t = text.strip()
    if len(t) < 100:
        return False
    
    # V6: DOI density check — if 3+ DOIs in one chunk, it's a ref block
    doi_count = len(_doi_re_v5.findall(t))
    if doi_count >= 3:
        return True
    
    # V6: Year-bracket density — 6+ year citations like (2019) in one chunk
    year_count = len(_year_bracket_re.findall(t))
    if year_count >= 6:
        return True
    
    # V6: "et al." density — 6+ occurrences = bibliography
    et_al_count = t.lower().count("et al")
    if et_al_count >= 6:
        return True
    
    # V3: Line-based detection
    lines = [l.strip() for l in t.split("\n") if l.strip()]
    if len(lines) < 3:
        return False
    ref_lines = sum(1 for l in lines if _ref_pattern.search(l))
    # If >60% of lines look like references
    return ref_lines / len(lines) > 0.6


def has_repeating_loop(text: str, min_repeat: int = 3) -> bool:
    """Detect text with repeating string loops (e.g. 'Coral: Bard...' x10)."""
    t = text.strip()
    if len(t) < 200:
        return False
    # Check for any substring of 20+ chars repeating 3+ times
    for length in (50, 30, 20):
        for start in range(0, min(len(t) - length, 500), 10):
            substr = t[start:start + length]
            if t.count(substr) >= min_repeat:
                return True
    return False


_line_noise_re = re.compile(
    r"^(?:"
    r"urn:x-wiley:|"
    r"https?://\S+$|"
    r"Dieses Dialogfeld|"
    r"Datenschutzrichtlinie|"
    r"This site uses cookies|"
    r"We use cookies|"
    r"Accept all cookies|"
    r"Forgot your password|"
    r"Request Username|"
    r"Change Password|"
    r"Your password must have|"
    r"a lower case character|"
    r"an upper case character|"
    r"a special character|"
    r"or a digit|"
    r"Congrats!|"
    r"Login / Register|"
    r"Scite metrics|"
    r"Share QR Code|"
    r"Access through your institution|"
    r"Buy or subscribe|"
    r"Check for updates|"
    r"Open in figure viewer|"
    r"Wiley Online Library|"
    r"Article Activity Alert|"
    r"Send Email|"
    r"Recipient\(s\) will receive|"
    r"Article has an altmetric score|"
    r"\d+ publications? \d+ supporting|"
    r"Download & links|"
    r"Full-text XML|"
    r"BibTeX|"
    r"Multiple terms:|"
    r"We are sorry, but your search|"
    r"Turn MathJax on|"
    r"Creative Commons|"
    r"Connect with Wiley|"
    r"Privacy Preference Center|"
    r"Manage Consent Preferences|"
    r"Essential cookies|"
    r"Performance cookies|"
    r"Functional cookies|"
    r"Cookie List|"
    # V3: Additional boilerplate patterns
    r"Correspondence to:|"
    r"Received:\s+\d|"
    r"Accepted:\s+\d|"
    r"Published:\s+\d|"
    r"Edited by:|"
    r"Reviewed by:|"
    r"Lead Authors?:|"
    r"Contributing Authors?:|"
    r"How to cite|"
    r"Crown copyright|"
    r"Attribution \d\.\d License|"
    r"An official website of the United States|"
    r"Search PMC|"
    r"Sorry, we could not find|"
    r"Go to Figure|"
    r"Open all in viewer|"
    r"There are no results for"
    r")",
    re.IGNORECASE
)


def clean_ui_from_text(text: str) -> str:
    """Strip embedded UI elements and noise lines from text."""
    # Remove "Open in figure viewer PowerPoint" etc.
    text = _ui_button_re.sub("", text)
    # Remove "Check for updates" boilerplate
    text = re.sub(r"Check for updates\.?\s*Verify currency and authenticity via CrossMark\.?", "", text)

    # V2: Line-level noise removal — strip individual noise lines
    lines = text.split("\n")
    clean_lines = []
    for line in lines:
        stripped = line.strip()
        if not stripped:
            clean_lines.append(line)
            continue
        if _line_noise_re.match(stripped):
            continue  # skip this line
        # Skip pure URN lines
        if stripped.startswith("urn:"):
            continue
        clean_lines.append(line)

    text = "\n".join(clean_lines)

    # Remove excessive blank lines
    text = re.sub(r"\n{3,}", "\n\n", text)
    return text.strip()

# ── Tokenizer ──────────────────────────────────────────────────────────────────
_enc = tiktoken.get_encoding("cl100k_base")


def count_tokens(text: str) -> int:
    """Count tokens using cl100k_base (≈same as Gemini tokenization)."""
    return len(_enc.encode(text))


# ── Noise Detection ────────────────────────────────────────────────────────────

def is_noise_text(text: str) -> bool:
    """Return True if text is HTML navigation / cookie banner noise."""
    t = text.strip()
    if len(t) < 3:
        return True
    tl = t.lower()
    if tl in _noise_exact:
        return True
    for pat in _noise_re:
        if pat.search(t):
            return True
    # V2: URN placeholders
    if is_urn_placeholder(t):
        return True
    # V2: Standalone URLs
    if is_url_only(t):
        return True
    return False


def is_excluded_section(section_name: str) -> bool:
    """Return True if section should be excluded from RAG."""
    return section_name.strip().lower() in EXCLUDE_SECTIONS


# ── Document Tree Walker ───────────────────────────────────────────────────────

class DocNode:
    """A node in the document tree."""
    __slots__ = ("label", "text", "children", "ref", "table_data")

    def __init__(self, label: str, text: str = "", ref: str = "",
                 table_data: Optional[dict] = None):
        self.label = label
        self.text = text
        self.children: list["DocNode"] = []
        self.ref = ref
        self.table_data = table_data


def build_item_index(doc: dict) -> dict:
    """Build a ref -> raw item lookup from the docling document."""
    items = {}
    for collection in ("texts", "groups", "tables", "pictures",
                       "key_value_items", "form_items"):
        for item in doc.get(collection, []):
            ref = item.get("self_ref", "")
            if ref:
                items[ref] = item
    return items


def resolve_ref(child_ptr: dict) -> str:
    """Extract the reference string from a child pointer."""
    return child_ptr.get("cref", child_ptr.get("$ref", ""))


def build_tree(doc: dict) -> DocNode:
    """Build a tree of DocNodes from the docling document body."""
    items = build_item_index(doc)
    root = DocNode(label="root", text="document")

    def _build(children_list: list) -> list[DocNode]:
        nodes = []
        for child_ptr in children_list:
            ref = resolve_ref(child_ptr)
            raw = items.get(ref, {})
            label = raw.get("label", "unknown")
            text = raw.get("text", "")

            # For tables, preserve the full data
            table_data = None
            if label == "table" or "tables" in ref:
                table_data = raw

            node = DocNode(label=label, text=text, ref=ref,
                           table_data=table_data)

            # Recurse into children
            if "children" in raw:
                node.children = _build(raw["children"])

            nodes.append(node)
        return nodes

    body = doc.get("body", {})
    root.children = _build(body.get("children", []))
    return root


# ── Section Collector ──────────────────────────────────────────────────────────

class Section:
    """A logical section of the document."""
    __slots__ = ("name", "path", "paragraphs", "tables", "captions", "level")

    def __init__(self, name: str, path: str, level: int = 0):
        self.name = name
        self.path = path
        self.level = level
        self.paragraphs: list[str] = []  # text blocks
        self.tables: list[dict] = []     # table data
        self.captions: list[str] = []    # figure/table captions


def collect_sections(root: DocNode) -> list[Section]:
    """Walk the document tree and collect sections with their content."""
    sections: list[Section] = []
    current_section = Section(name="Preamble", path="Preamble", level=0)

    def _walk(node: DocNode, section_path_parts: list[str], depth: int):
        nonlocal current_section

        # Skip noise
        if node.label in SKIP_LABELS:
            return
        if node.label in ("text", "list_item") and is_noise_text(node.text):
            return

        # Section header → start new section
        if node.label == "section_header":
            header_text = node.text.strip()
            if not header_text:
                return

            # Check if this section should be excluded
            if is_excluded_section(header_text):
                # Still process children but mark section as excluded
                excluded = Section(name=header_text,
                                   path=" > ".join(section_path_parts + [header_text]),
                                   level=depth)
                excluded.paragraphs.append("__EXCLUDED__")
                sections.append(excluded)
                return

            # Save current section if it has content
            if current_section.paragraphs or current_section.tables or current_section.captions:
                sections.append(current_section)

            new_path = section_path_parts + [header_text]
            current_section = Section(
                name=header_text,
                path=" > ".join(new_path),
                level=depth,
            )
            # Process children under this section header
            for child in node.children:
                _walk(child, new_path, depth + 1)
            return

        # Text content
        if node.label in ("text", "list_item"):
            text = node.text.strip()
            if text and len(text) > 5:
                current_section.paragraphs.append(text)

        # Caption
        elif node.label == "caption":
            text = node.text.strip()
            if text:
                current_section.captions.append(text)

        # Table
        elif node.label == "table" or node.table_data:
            current_section.tables.append(node.table_data or {"text": node.text})

        # Key-value area, list, group, picture, inline → recurse
        for child in node.children:
            _walk(child, section_path_parts, depth)

    for child in root.children:
        _walk(child, [], 0)

    # Don't forget the last section
    if current_section.paragraphs or current_section.tables or current_section.captions:
        sections.append(current_section)

    return sections


# ── Markdown Section Parser (MinerU VLM) ───────────────────────────────────────

_md_header_re = re.compile(r'^(#{1,6})\s+(.+)$', re.MULTILINE)
_md_table_line_re = re.compile(r'^\|.*\|\s*$')
_md_figure_caption_re = re.compile(
    r'^(?:Figure|Fig\.|Table|Plate|Scheme)\s+\d+',
    re.IGNORECASE
)
_md_image_ref_re = re.compile(r'^!\[.*\]\(.*\)$')


def parse_markdown_sections(md_text: str) -> list["Section"]:
    """Parse MinerU VLM markdown into Section objects using # headers.
    
    Handles:
    - # / ## / ### headers → section boundaries
    - Markdown tables (| col | col |) → table entries
    - Figure/Table captions → caption entries
    - Image references ![...](...) → skipped
    - Everything else → text paragraphs
    """
    sections: list[Section] = []
    current_section = Section(name="Preamble", path="Preamble", level=0)
    section_stack: list[tuple[int, str]] = []  # (level, name) for building paths
    
    lines = md_text.split('\n')
    i = 0
    
    while i < len(lines):
        line = lines[i]
        stripped = line.strip()
        
        # Skip empty lines
        if not stripped:
            i += 1
            continue
        
        # Skip image references
        if _md_image_ref_re.match(stripped):
            i += 1
            continue
        
        # Check for header
        header_match = _md_header_re.match(stripped)
        if header_match:
            level = len(header_match.group(1))  # number of #s
            header_text = header_match.group(2).strip()
            
            if not header_text:
                i += 1
                continue
            
            # Save current section if it has content
            if current_section.paragraphs or current_section.tables or current_section.captions:
                sections.append(current_section)
            
            # Update section stack
            while section_stack and section_stack[-1][0] >= level:
                section_stack.pop()
            section_stack.append((level, header_text))
            
            # Build section path from stack
            path_parts = [name for _, name in section_stack]
            section_path = " > ".join(path_parts)
            
            # Check if excluded
            if is_excluded_section(header_text):
                current_section = Section(name=header_text, path=section_path, level=level)
                current_section.paragraphs.append("__EXCLUDED__")
                sections.append(current_section)
                # Skip content until next header of same or higher level
                i += 1
                while i < len(lines):
                    next_match = _md_header_re.match(lines[i].strip())
                    if next_match and len(next_match.group(1)) <= level:
                        break
                    i += 1
                current_section = Section(name="[continued]", path="[continued]", level=0)
                continue
            
            current_section = Section(name=header_text, path=section_path, level=level)
            i += 1
            continue
        
        # Check for markdown table block
        if _md_table_line_re.match(stripped):
            table_lines = []
            while i < len(lines) and _md_table_line_re.match(lines[i].strip()):
                table_lines.append(lines[i].strip())
                i += 1
            if table_lines:
                table_text = '\n'.join(table_lines)
                current_section.tables.append({"text": table_text})
            continue
        
        # Check for figure/table caption
        if _md_figure_caption_re.match(stripped):
            # Collect multi-line caption
            caption_lines = [stripped]
            i += 1
            while i < len(lines) and lines[i].strip() and not _md_header_re.match(lines[i].strip()):
                if _md_table_line_re.match(lines[i].strip()):
                    break
                if _md_image_ref_re.match(lines[i].strip()):
                    i += 1
                    continue
                if _md_figure_caption_re.match(lines[i].strip()):
                    break  # new caption starts
                caption_lines.append(lines[i].strip())
                i += 1
            current_section.captions.append(' '.join(caption_lines))
            continue
        
        # Regular text — skip noise
        if is_noise_text(stripped):
            i += 1
            continue
        
        # Collect paragraph (consecutive non-empty, non-header lines)
        para_lines = [stripped]
        i += 1
        while i < len(lines):
            next_stripped = lines[i].strip()
            if not next_stripped:  # blank line = paragraph break
                break
            if _md_header_re.match(next_stripped):
                break
            if _md_table_line_re.match(next_stripped):
                break
            if _md_image_ref_re.match(next_stripped):
                i += 1
                continue
            if is_noise_text(next_stripped):
                i += 1
                continue
            para_lines.append(next_stripped)
            i += 1
        
        para_text = ' '.join(para_lines)
        if len(para_text) > 5:
            current_section.paragraphs.append(para_text)
    
    # Don't forget the last section
    if current_section.paragraphs or current_section.tables or current_section.captions:
        sections.append(current_section)
    
    return sections


def chunk_markdown_document(md_path: Path, paper_id: str) -> list[dict]:
    """Chunk a MinerU VLM markdown file using the same pipeline as docling.
    
    Reuses: all filters, OCR fixes, overlap, token budget, dedup, etc.
    """
    with open(md_path, 'r', encoding='utf-8', errors='replace') as f:
        md_text = f.read()
    
    meta_path = md_path.with_suffix(".meta.json")
    meta = {}
    if meta_path.exists():
        with open(meta_path, 'r', encoding='utf-8') as mf:
            try:
                meta = json.load(mf)
            except Exception:
                pass

    # Extract DOI from paper_id (folder name or meta)
    doi = meta.get("doi")
    if not doi:
        parts = paper_id.split('_', 2)
        if len(parts) >= 3 and parts[0] == '10':
            doi = f"10.{parts[1]}/{parts[2].replace('_', '.')}"
        else:
            doi = paper_id.replace('_', '/')
    
    title = meta.get("title", "")
    year = meta.get("year", "")
    journal = meta.get("journal", "")
    tier = meta.get("tier", "UNKNOWN")
    
    # Parse markdown into sections
    sections = parse_markdown_sections(md_text)
    
    # ── Reuse the EXACT same chunking pipeline ──
    chunks_out = []
    chunk_counter = 0
    seen_hashes = set()
    
    for section in sections:
        if section.paragraphs == ["__EXCLUDED__"]:
            continue
        
        section_path = section.path
        if is_garbage_section_path(section.name):
            section_path = "[section unknown]"
        
        # ── Text chunks ──
        if section.paragraphs:
            full_text = "\n\n".join(section.paragraphs)
            full_text = fix_ocr_ris_stripping(full_text)
            text_tokens = count_tokens(full_text)
            
            is_abstract = section.name.strip().lower() == "abstract"
            chunk_type = "abstract" if is_abstract else "text"
            
            if text_tokens <= MAX_TOKENS:
                raw_chunks = [full_text]
            else:
                raw_chunks = chunk_text_block(full_text, MAX_TOKENS)
            
            if len(raw_chunks) > 1:
                raw_chunks = add_overlap(raw_chunks, OVERLAP_RATIO)
            
            capped = []
            for rc in raw_chunks:
                if count_tokens(rc) > MAX_TOKENS + 50:
                    capped.extend(chunk_text_block(rc, MAX_TOKENS))
                else:
                    capped.append(rc)
            raw_chunks = capped
            
            for i_chunk, chunk_text in enumerate(raw_chunks):
                ct = count_tokens(chunk_text)
                if ct < MIN_QUALITY_TOKENS:
                    continue
                chunk_text = clean_ui_from_text(chunk_text)
                if not chunk_text or count_tokens(chunk_text) < MIN_QUALITY_TOKENS:
                    continue
                if is_figure_axis_gibberish(chunk_text):
                    continue
                if is_digit_heavy_garbage(chunk_text):
                    continue
                if is_boilerplate_noise(chunk_text):
                    continue
                if is_affiliation_fragment(chunk_text):
                    continue
                if is_reference_block(chunk_text):
                    continue
                if has_repeating_loop(chunk_text):
                    continue
                
                content_hash = hashlib.md5(chunk_text.encode()).hexdigest()
                if content_hash in seen_hashes:
                    continue
                seen_hashes.add(content_hash)
                
                prefix = f'Paper: "{title}"' if title else f'Paper: {paper_id}'
                if year:
                    prefix += f" ({year}"
                    if journal:
                        prefix += f", {journal}"
                    prefix += ")"
                elif journal:
                    prefix += f" ({journal})"
                prefix += f"\nDOI: {doi}"
                prefix += f"\nSection: {section_path}"
                prefix += "\n---\n"
                
                text_with_prefix = prefix + chunk_text
                chunk_id = f"{paper_id}__{content_hash[:12]}"
                
                chunks_out.append({
                    "chunk_id": chunk_id,
                    "paper_id": doi,
                    "doi": doi,
                    "title": title,
                    "year": int(year) if str(year).isdigit() else year,
                    "journal": journal,
                    "tier": tier,
                    "section_path": section_path,
                    "section_name": section.name,
                    "chunk_type": chunk_type,
                    "chunk_index": chunk_counter,
                    "token_count": count_tokens(text_with_prefix),
                    "text_with_prefix": text_with_prefix,
                    "text_raw": chunk_text,
                })
                chunk_counter += 1
        
        # ── Table chunks ──
        for j, tbl in enumerate(section.tables):
            tbl_text = tbl.get("text", "")
            if not tbl_text or count_tokens(tbl_text) < 10:
                continue
            
            caption = ""
            if j < len(section.captions):
                caption = section.captions[j]
            
            context = f"[TABLE in section: {section_path}]"
            if caption:
                context += f"\nCaption: {caption}"
            full_table = context + "\n\n" + tbl_text
            
            prefix = f'Paper: "{title}"' if title else f'Paper: {paper_id}'
            if year:
                prefix += f" ({year}"
                if journal:
                    prefix += f", {journal}"
                prefix += ")"
            prefix += f"\nDOI: {doi}"
            prefix += f"\nSection: {section_path}"
            prefix += "\n---\n"
            
            text_with_prefix = prefix + full_table
            chunk_id_raw = f"{doi}__table__{section_path}__{j}"
            chunk_id = hashlib.md5(chunk_id_raw.encode()).hexdigest()[:12]
            chunk_id = f"{paper_id}__tbl_{chunk_id}"
            
            # Truncate oversized tables
            if count_tokens(tbl_text) > TABLE_MAX_TOKENS:
                tbl_lines = tbl_text.split('\n')
                kept = []
                tok_count = 0
                for tl in tbl_lines:
                    lt = count_tokens(tl)
                    if tok_count + lt > TABLE_MAX_TOKENS - 20:
                        break
                    kept.append(tl)
                    tok_count += lt
                tbl_text = '\n'.join(kept) + f"\n[... TABLE TRUNCATED ...]"
                full_table = context + "\n\n" + tbl_text
                text_with_prefix = prefix + full_table
            
            chunks_out.append({
                "chunk_id": chunk_id,
                "paper_id": doi,
                "doi": doi,
                "title": title,
                "year": int(year) if str(year).isdigit() else year,
                "journal": journal,
                "tier": tier,
                "section_path": section_path,
                "section_name": section.name,
                "chunk_type": "table",
                "chunk_index": chunk_counter,
                "token_count": count_tokens(text_with_prefix),
                "text_with_prefix": text_with_prefix,
                "text_raw": full_table,
            })
            chunk_counter += 1
        
        # ── Standalone captions ──
        unpaired = section.captions[len(section.tables):]
        for k, cap in enumerate(unpaired):
            if count_tokens(cap) < 10:
                continue
            if is_url_only(cap):
                continue
            cap = clean_ui_from_text(cap)
            if not cap or count_tokens(cap) < 10:
                continue
            cap = fix_ocr_ris_stripping(cap)
            
            prefix = f'Paper: "{title}"' if title else f'Paper: {paper_id}'
            if year:
                prefix += f" ({year}"
                if journal:
                    prefix += f", {journal}"
                prefix += ")"
            prefix += f"\nDOI: {doi}"
            prefix += f"\nSection: {section_path}"
            prefix += "\n---\n"
            
            text_with_prefix = prefix + f"[FIGURE CAPTION]\n{cap}"
            chunk_id_raw = f"{doi}__caption__{section_path}__{k}"
            chunk_id = hashlib.md5(chunk_id_raw.encode()).hexdigest()[:12]
            chunk_id = f"{paper_id}__cap_{chunk_id}"
            
            chunks_out.append({
                "chunk_id": chunk_id,
                "paper_id": doi,
                "doi": doi,
                "title": title,
                "year": int(year) if str(year).isdigit() else year,
                "journal": journal,
                "tier": tier,
                "section_path": section_path,
                "section_name": section.name,
                "chunk_type": "caption",
                "chunk_index": chunk_counter,
                "token_count": count_tokens(text_with_prefix),
                "text_with_prefix": text_with_prefix,
                "text_raw": cap,
            })
            chunk_counter += 1
    
    # ── Post-process: merge tiny chunks ──
    MIN_CAPTION_STANDALONE = 150
    merged = []
    ii = 0
    while ii < len(chunks_out):
        chunk = chunks_out[ii]
        if (chunk["token_count"] < MIN_TOKENS and
                chunk["chunk_type"] == "text" and
                ii + 1 < len(chunks_out) and
                chunks_out[ii + 1]["section_path"] == chunk["section_path"] and
                chunks_out[ii + 1]["chunk_type"] == "text"):
            next_chunk = chunks_out[ii + 1]
            merged_text = chunk["text_raw"] + "\n\n" + next_chunk["text_raw"]
            merged_prefix = chunk["text_with_prefix"].split("---\n", 1)[0] + "---\n" + merged_text
            next_chunk["text_raw"] = merged_text
            next_chunk["text_with_prefix"] = merged_prefix
            next_chunk["token_count"] = count_tokens(merged_prefix)
            ii += 1
        elif (chunk["chunk_type"] == "caption" and
              chunk["token_count"] < MIN_CAPTION_STANDALONE and
              merged and
              merged[-1]["section_path"] == chunk["section_path"] and
              merged[-1]["chunk_type"] == "text"):
            prev = merged[-1]
            appended_text = prev["text_raw"] + "\n\n[Figure caption: " + chunk["text_raw"] + "]"
            appended_prefix = prev["text_with_prefix"].split("---\n", 1)[0] + "---\n" + appended_text
            prev["text_raw"] = appended_text
            prev["text_with_prefix"] = appended_prefix
            prev["token_count"] = count_tokens(appended_prefix)
            ii += 1
        else:
            merged.append(chunk)
            ii += 1
    
    for idx, c in enumerate(merged):
        c["chunk_index"] = idx
    
    return merged


# ── Sentence Splitter ──────────────────────────────────────────────────────────

_sent_re = re.compile(
    r'(?<=[.!?])\s+(?=[A-Z])'    # Split after sentence-ending punct + space + capital
    r'|(?<=[.!?])\s*\n'          # or after punct + newline
)


def split_sentences(text: str) -> list[str]:
    """Split text into sentences (conservative)."""
    parts = _sent_re.split(text)
    return [s.strip() for s in parts if s.strip()]


# ── Smart Chunking ─────────────────────────────────────────────────────────────

def chunk_text_block(text: str, max_tokens: int = MAX_TOKENS) -> list[str]:
    """Split a text block into chunks respecting sentence boundaries."""
    sentences = split_sentences(text)
    if not sentences:
        return [text] if text.strip() else []

    chunks = []
    current = []
    current_tokens = 0

    for sent in sentences:
        sent_tokens = count_tokens(sent)

        # If single sentence exceeds max, force-split by words
        if sent_tokens > max_tokens:
            if current:
                chunks.append(" ".join(current))
                current = []
                current_tokens = 0
            words = sent.split()
            buf = []
            buf_tokens = 0
            for w in words:
                wt = count_tokens(w + " ")
                if buf_tokens + wt > max_tokens and buf:
                    chunks.append(" ".join(buf))
                    buf = []
                    buf_tokens = 0
                buf.append(w)
                buf_tokens += wt
            if buf:
                chunks.append(" ".join(buf))
            continue

        if current_tokens + sent_tokens > max_tokens and current:
            chunks.append(" ".join(current))
            current = []
            current_tokens = 0

        current.append(sent)
        current_tokens += sent_tokens

    if current:
        chunks.append(" ".join(current))

    return chunks


def add_overlap(chunks: list[str], ratio: float = OVERLAP_RATIO) -> list[str]:
    """Add sentence-level overlap between consecutive chunks."""
    if len(chunks) <= 1:
        return chunks

    result = [chunks[0]]
    for i in range(1, len(chunks)):
        prev_sents = split_sentences(chunks[i - 1])
        if not prev_sents:
            result.append(chunks[i])
            continue

        # Take last N sentences as overlap
        overlap_tokens_target = int(count_tokens(chunks[i - 1]) * ratio)
        overlap_sents = []
        overlap_tokens = 0
        for s in reversed(prev_sents):
            st = count_tokens(s)
            if overlap_tokens + st > overlap_tokens_target and overlap_sents:
                break
            overlap_sents.insert(0, s)
            overlap_tokens += st

        overlap_text = " ".join(overlap_sents)
        result.append(overlap_text + " " + chunks[i])

    return result


def table_to_text(table_data: dict, max_tokens: int = TABLE_MAX_TOKENS) -> str:
    """Convert a Docling table to text representation, truncating if needed."""
    if not table_data:
        return ""

    raw = ""
    # Try to extract grid data
    grid = table_data.get("data", {}).get("grid", [])
    if grid:
        lines = []
        for row in grid:
            cells = []
            for cell in row:
                text = cell.get("text", "")
                cells.append(text)
            lines.append(" | ".join(cells))
        raw = "\n".join(lines)
    else:
        # Fallback: use text or markdown representation
        raw = table_data.get("text", "")

    if not raw:
        return "[Table content not extractable]"

    # Truncate oversized tables
    if count_tokens(raw) > max_tokens:
        # Keep first N rows that fit within token budget
        lines = raw.split("\n")
        kept = []
        tok_count = 0
        for line in lines:
            lt = count_tokens(line)
            if tok_count + lt > max_tokens - 20:  # leave room for truncation marker
                break
            kept.append(line)
            tok_count += lt
        raw = "\n".join(kept) + f"\n[... TABLE TRUNCATED, {len(lines) - len(kept)} more rows ...]"

    return raw


# ── Main Chunking Pipeline ─────────────────────────────────────────────────────

def chunk_document(docling_path: Path, meta_path: Path) -> list[dict]:
    """Chunk a single document into retrieval-ready pieces."""
    # Load docling JSON (raw, fast)
    with open(docling_path) as f:
        doc = json.load(f)

    # Load metadata
    meta = {}
    if meta_path.exists():
        with open(meta_path) as f:
            meta = json.load(f)

    doi = meta.get("doi", docling_path.stem.replace("_", "/", 1)
                   .replace("_", ".", 1))
    title = meta.get("title", doc.get("name", "Unknown"))
    year = meta.get("year", "")
    journal = meta.get("journal", "")
    tier = meta.get("tier", "CORE")
    paper_id = doi

    # Build tree and collect sections
    tree = build_tree(doc)
    sections = collect_sections(tree)

    chunks_out = []
    chunk_counter = 0
    seen_hashes = set()  # V5: content-hash deduplication

    for section in sections:
        # Skip excluded sections
        if section.paragraphs == ["__EXCLUDED__"]:
            continue

        section_path = section.path
        # V5: Fix garbage section paths
        if is_garbage_section_path(section.name):
            section_path = f"[section unknown]"

        # ── Text chunks ──
        if section.paragraphs:
            full_text = "\n\n".join(section.paragraphs)
            # V5: Apply OCR "ris" restoration
            full_text = fix_ocr_ris_stripping(full_text)
            text_tokens = count_tokens(full_text)

            # Determine chunk type
            is_abstract = section.name.strip().lower() == "abstract"
            chunk_type = "abstract" if is_abstract else "text"

            if text_tokens <= MAX_TOKENS:
                # Section fits in one chunk
                raw_chunks = [full_text]
            else:
                # Split by sentence boundaries
                raw_chunks = chunk_text_block(full_text, MAX_TOKENS)

            # Add overlap between chunks in same section
            if len(raw_chunks) > 1:
                raw_chunks = add_overlap(raw_chunks, OVERLAP_RATIO)

            # Hard cap: re-split any chunks that exceeded MAX_TOKENS after overlap
            capped = []
            for rc in raw_chunks:
                if count_tokens(rc) > MAX_TOKENS + 50:  # small slack
                    capped.extend(chunk_text_block(rc, MAX_TOKENS))
                else:
                    capped.append(rc)
            raw_chunks = capped

            for i, chunk_text in enumerate(raw_chunks):
                ct = count_tokens(chunk_text)
                if ct < MIN_QUALITY_TOKENS:
                    continue

                # V2: Clean UI remnants from text
                chunk_text = clean_ui_from_text(chunk_text)
                if not chunk_text or count_tokens(chunk_text) < MIN_QUALITY_TOKENS:
                    continue

                # V2: Skip figure axis gibberish
                if is_figure_axis_gibberish(chunk_text):
                    continue

                # V6: Skip digit-heavy garbage (axis data, coordinate grids)
                if is_digit_heavy_garbage(chunk_text):
                    continue

                # V6: Skip publisher boilerplate
                if is_boilerplate_noise(chunk_text):
                    continue

                # V2: Skip affiliation fragments
                if is_affiliation_fragment(chunk_text):
                    continue

                # V3/V6: Skip reference blocks (refs hidden under wrong section headers)
                if is_reference_block(chunk_text):
                    continue

                # V3: Skip repeating string loops
                if has_repeating_loop(chunk_text):
                    continue

                # V5: Content-hash deduplication
                content_hash = hashlib.md5(chunk_text.encode()).hexdigest()
                if content_hash in seen_hashes:
                    continue
                seen_hashes.add(content_hash)

                # Build metadata prefix
                prefix = f'Paper: "{title}"'
                if year:
                    prefix += f" ({year}"
                    if journal:
                        prefix += f", {journal}"
                    prefix += ")"
                elif journal:
                    prefix += f" ({journal})"
                prefix += f"\nDOI: {doi}"
                prefix += f"\nSection: {section_path}"
                prefix += "\n---\n"

                text_with_prefix = prefix + chunk_text

                # V5: Generate content-based chunk ID (stable, dedup-safe)
                chunk_id = f"{doi.replace('/', '_').replace('.', '_')}__{content_hash[:12]}"

                chunks_out.append({
                    "chunk_id": chunk_id,
                    "paper_id": paper_id,
                    "doi": doi,
                    "title": title,
                    "year": int(year) if str(year).isdigit() else year,
                    "journal": journal,
                    "tier": tier,
                    "section_path": section_path,
                    "section_name": section.name,
                    "chunk_type": chunk_type,
                    "chunk_index": chunk_counter,
                    "token_count": count_tokens(text_with_prefix),
                    "text_with_prefix": text_with_prefix,
                    "text_raw": chunk_text,
                })
                chunk_counter += 1

        # ── Table chunks (atomic) ──
        for j, tbl in enumerate(section.tables):
            tbl_text = table_to_text(tbl)
            if not tbl_text or count_tokens(tbl_text) < 10:
                continue

            # Include relevant captions
            caption = ""
            if j < len(section.captions):
                caption = section.captions[j]

            context = f"[TABLE in section: {section_path}]"
            if caption:
                context += f"\nCaption: {caption}"
            full_table = context + "\n\n" + tbl_text

            prefix = f'Paper: "{title}"'
            if year:
                prefix += f" ({year}"
                if journal:
                    prefix += f", {journal}"
                prefix += ")"
            prefix += f"\nDOI: {doi}"
            prefix += f"\nSection: {section_path}"
            prefix += "\n---\n"

            text_with_prefix = prefix + full_table
            chunk_id_raw = f"{paper_id}__table__{section_path}__{j}"
            chunk_id = hashlib.md5(chunk_id_raw.encode()).hexdigest()[:12]
            chunk_id = f"{doi.replace('/', '_').replace('.', '_')}__tbl_{chunk_id}"

            chunks_out.append({
                "chunk_id": chunk_id,
                "paper_id": paper_id,
                "doi": doi,
                "title": title,
                "year": int(year) if str(year).isdigit() else year,
                "journal": journal,
                "tier": tier,
                "section_path": section_path,
                "section_name": section.name,
                "chunk_type": "table",
                "chunk_index": chunk_counter,
                "token_count": count_tokens(text_with_prefix),
                "text_with_prefix": text_with_prefix,
                "text_raw": full_table,
            })
            chunk_counter += 1

        # ── Standalone captions (not paired with tables) ──
        unpaired_captions = section.captions[len(section.tables):]
        for k, cap in enumerate(unpaired_captions):
            if count_tokens(cap) < 10:
                continue

            # V2: Skip URL-only captions
            if is_url_only(cap):
                continue

            # V2: Clean UI from captions
            cap = clean_ui_from_text(cap)
            if not cap or count_tokens(cap) < 10:
                continue

            # V5: Apply OCR fix to captions
            cap = fix_ocr_ris_stripping(cap)

            prefix = f'Paper: "{title}"'
            if year:
                prefix += f" ({year}"
                if journal:
                    prefix += f", {journal}"
                prefix += ")"
            prefix += f"\nDOI: {doi}"
            prefix += f"\nSection: {section_path}"
            prefix += "\n---\n"

            text_with_prefix = prefix + f"[FIGURE CAPTION]\n{cap}"
            chunk_id_raw = f"{paper_id}__caption__{section_path}__{k}"
            chunk_id = hashlib.md5(chunk_id_raw.encode()).hexdigest()[:12]
            chunk_id = f"{doi.replace('/', '_').replace('.', '_')}__cap_{chunk_id}"

            chunks_out.append({
                "chunk_id": chunk_id,
                "paper_id": paper_id,
                "doi": doi,
                "title": title,
                "year": int(year) if str(year).isdigit() else year,
                "journal": journal,
                "tier": tier,
                "section_path": section_path,
                "section_name": section.name,
                "chunk_type": "caption",
                "chunk_index": chunk_counter,
                "token_count": count_tokens(text_with_prefix),
                "text_with_prefix": text_with_prefix,
                "text_raw": cap,
            })
            chunk_counter += 1

    # ── Post-process: merge tiny chunks with neighbors ──
    # V5: Also merge tiny captions into preceding text chunks
    MIN_CAPTION_STANDALONE = 150  # captions below this get merged
    merged = []
    i = 0
    while i < len(chunks_out):
        chunk = chunks_out[i]
        # Merge tiny TEXT chunks into next text chunk in same section
        if (chunk["token_count"] < MIN_TOKENS and
                chunk["chunk_type"] == "text" and
                i + 1 < len(chunks_out) and
                chunks_out[i + 1]["section_path"] == chunk["section_path"] and
                chunks_out[i + 1]["chunk_type"] == "text"):
            next_chunk = chunks_out[i + 1]
            merged_text = chunk["text_raw"] + "\n\n" + next_chunk["text_raw"]
            merged_prefix = chunk["text_with_prefix"].split("---\n", 1)[0] + "---\n" + merged_text
            next_chunk["text_raw"] = merged_text
            next_chunk["text_with_prefix"] = merged_prefix
            next_chunk["token_count"] = count_tokens(merged_prefix)
            i += 1  # skip current, will pick up merged next
        # V5: Merge tiny CAPTION chunks into preceding text chunk
        elif (chunk["chunk_type"] == "caption" and
              chunk["token_count"] < MIN_CAPTION_STANDALONE and
              merged and
              merged[-1]["section_path"] == chunk["section_path"] and
              merged[-1]["chunk_type"] == "text"):
            prev = merged[-1]
            appended_text = prev["text_raw"] + "\n\n[Figure caption: " + chunk["text_raw"] + "]"
            appended_prefix = prev["text_with_prefix"].split("---\n", 1)[0] + "---\n" + appended_text
            prev["text_raw"] = appended_text
            prev["text_with_prefix"] = appended_prefix
            prev["token_count"] = count_tokens(appended_prefix)
            i += 1  # skip caption, it's merged
        else:
            merged.append(chunk)
            i += 1

    # Re-index
    for idx, c in enumerate(merged):
        c["chunk_index"] = idx

    return merged


# ── Main ───────────────────────────────────────────────────────────────────────

def find_markdown_papers(input_dir: Path) -> list[tuple[str, Path]]:
    """Find all MinerU VLM markdown files in parsed_levante or cleaned_levante structure.
    
    Structure 1 (parsed): {input_dir}/{DOI_folder}/vlm/{DOI_folder}.md
    Structure 2 (cleaned): {input_dir}/{DOI_filename}.md
    Returns: list of (paper_id, md_path) tuples
    """
    papers = []
    for item in sorted(input_dir.iterdir()):
        if item.is_dir():
            paper_id = item.name
            # Look for vlm/*.md
            vlm_dir = item / "vlm"
            if vlm_dir.is_dir():
                md_files = list(vlm_dir.glob("*.md"))
                if md_files:
                    papers.append((paper_id, md_files[0]))
            else:
                # Maybe .md directly in the folder
                md_files = list(item.glob("*.md"))
                if md_files:
                    papers.append((paper_id, md_files[0]))
        elif item.is_file() and item.suffix == ".md":
            # Flat directory structure (cleaned_levante)
            paper_id = item.stem
            papers.append((paper_id, item))
    return papers


def print_summary(all_chunks: list, total_papers: int, errors: list, output_path: Path):
    """Print chunking summary statistics."""
    print(f"\n{'='*60}")
    print(f"CHUNKING COMPLETE")
    print(f"{'='*60}")
    print(f"Papers processed: {total_papers - len(errors)}/{total_papers}")
    print(f"Errors: {len(errors)}")
    print(f"Total chunks: {len(all_chunks)}")

    if all_chunks:
        tokens = [c["token_count"] for c in all_chunks]
        print(f"Token range: {min(tokens)}-{max(tokens)}")
        print(f"Mean tokens: {sum(tokens)/len(tokens):.0f}")
        print(f"Median tokens: {sorted(tokens)[len(tokens)//2]}")

        buckets = {"<100": 0, "100-200": 0, "200-500": 0, "500-1000": 0,
                   "1000-1200": 0, ">1200": 0}
        for t in tokens:
            if t < 100: buckets["<100"] += 1
            elif t < 200: buckets["100-200"] += 1
            elif t < 500: buckets["200-500"] += 1
            elif t < 1000: buckets["500-1000"] += 1
            elif t < 1200: buckets["1000-1200"] += 1
            else: buckets[">1200"] += 1
        print(f"\nToken distribution:")
        for k, v in buckets.items():
            pct = v / len(tokens) * 100
            bar = "█" * int(pct / 2)
            print(f"  {k:>10}: {v:5d} ({pct:5.1f}%) {bar}")

        types = {}
        for c in all_chunks:
            ct = c["chunk_type"]
            types[ct] = types.get(ct, 0) + 1
        print(f"\nChunk types:")
        for ct, count in sorted(types.items()):
            print(f"  {ct}: {count}")

        papers = set(c["paper_id"] for c in all_chunks)
        print(f"\nUnique papers: {len(papers)}")

    if errors:
        print(f"\nFailed papers ({len(errors)}):")
        for stem, err in errors[:20]:
            print(f"  {stem}: {err}")
        if len(errors) > 20:
            print(f"  ... and {len(errors) - 20} more")

    print(f"\nOutput: {output_path}")


def main():
    parser = argparse.ArgumentParser(description="CMIP6 RAG Chunker V6")
    parser.add_argument("--input-dir", type=str, default=None,
                        help="Input directory (auto-detects docling vs markdown)")
    parser.add_argument("--output", type=str, default=None,
                        help="Output JSONL file path")
    parser.add_argument("--max-papers", type=int, default=None,
                        help="Max papers to process (for testing)")
    args = parser.parse_args()

    input_dir = Path(args.input_dir) if args.input_dir else None

    # ── Auto-detect mode ──
    use_markdown = False
    if input_dir:
        # Check if input_dir has VLM markdown structure
        test_dirs = [d for d in input_dir.iterdir() if d.is_dir()][:5]
        has_vlm = any((d / "vlm").is_dir() for d in test_dirs)
        has_md_nested = any(list(d.glob("*.md")) for d in test_dirs if d.is_dir())
        has_md_flat = any(list(input_dir.glob("*.md"))[:1])
        has_docling = any(list(input_dir.glob("*.docling.json"))[:1])

        if has_vlm or (has_md_nested and not has_docling) or (has_md_flat and not has_docling):
            use_markdown = True
    else:
        # Default: try parsed_levante first, then parsed
        if PARSED_LEVANTE_DIR.exists() and any(PARSED_LEVANTE_DIR.iterdir()):
            input_dir = PARSED_LEVANTE_DIR
            use_markdown = True
        else:
            input_dir = PARSED_DIR
            use_markdown = False

    if use_markdown:
        # ── MinerU VLM Markdown Mode ──
        output_path = Path(args.output) if args.output else OUTPUT_LEVANTE_FILE
        papers = find_markdown_papers(input_dir)
        if args.max_papers:
            papers = papers[:args.max_papers]
        print(f"Mode: MinerU VLM Markdown")
        print(f"Found {len(papers)} papers in {input_dir}")
        print(f"Output: {output_path}")
        print()

        if not papers:
            print("ERROR: No markdown files found!")
            return

        all_chunks = []
        errors = []

        for i, (paper_id, md_path) in enumerate(papers):
            try:
                chunks = chunk_markdown_document(md_path, paper_id)
                all_chunks.extend(chunks)
                tokens = [c["token_count"] for c in chunks]
                avg_t = sum(tokens) / len(tokens) if tokens else 0
                if (i + 1) % 100 == 0 or (i + 1) == len(papers) or i < 5:
                    print(f"[{i+1:5d}/{len(papers)}] {paper_id}: "
                          f"{len(chunks)} chunks, "
                          f"avg {avg_t:.0f} tokens")
            except Exception as e:
                print(f"[{i+1:5d}/{len(papers)}] ERROR {paper_id}: {e}")
                errors.append((paper_id, str(e)))

        with open(output_path, "w") as f:
            for chunk in all_chunks:
                f.write(json.dumps(chunk, ensure_ascii=False) + "\n")

        print_summary(all_chunks, len(papers), errors, output_path)

    else:
        # ── Original Docling JSON Mode ──
        output_path = Path(args.output) if args.output else OUTPUT_FILE
        docling_files = sorted(input_dir.glob("*.docling.json"))
        if args.max_papers:
            docling_files = docling_files[:args.max_papers]
        print(f"Mode: Docling JSON")
        print(f"Found {len(docling_files)} docling files in {input_dir}")

        if not docling_files:
            print("ERROR: No .docling.json files found!")
            return

        all_chunks = []
        errors = []

        for i, dp in enumerate(docling_files):
            stem = dp.name.replace(".docling.json", "")
            meta_path = input_dir / f"{stem}.json"

            try:
                chunks = chunk_document(dp, meta_path)
                all_chunks.extend(chunks)
                tokens = [c["token_count"] for c in chunks]
                avg_t = sum(tokens) / len(tokens) if tokens else 0
                print(f"[{i+1:3d}/{len(docling_files)}] {stem}: "
                      f"{len(chunks)} chunks, "
                      f"avg {avg_t:.0f} tokens, "
                      f"range [{min(tokens) if tokens else 0}-{max(tokens) if tokens else 0}]")
            except Exception as e:
                print(f"[{i+1:3d}/{len(docling_files)}] ERROR {stem}: {e}")
                errors.append((stem, str(e)))

        with open(output_path, "w") as f:
            for chunk in all_chunks:
                f.write(json.dumps(chunk, ensure_ascii=False) + "\n")

        print_summary(all_chunks, len(docling_files), errors, output_path)


if __name__ == "__main__":
    main()