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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
"""Evidence-grounded structured extraction from the interim IMF corpus.

This is a transparent deterministic baseline, not an LLM-generated gold set.
Every observation, recommendation, and relationship includes page evidence and
an explicit extraction method/confidence. Contextual links are labeled as such
and are never represented as explicit causal claims.
"""

from __future__ import annotations

import argparse
import concurrent.futures
import datetime as dt
import hashlib
import json
import os
import re
import shutil
import sys
import tempfile
from collections import Counter, defaultdict
from pathlib import Path
from typing import Any, Iterable, Sequence

import jsonschema

SCHEMA_VERSION = "1.1.0"
EXTRACTOR_VERSION = "1.1.0"
EXTRACTION_METHOD = "deterministic_evidence_baseline"

HEADING_RE = re.compile(r"^\s*#{1,6}\s+(.+?)\s*$")
TABLE_SEPARATOR_RE = re.compile(r"^\s*\|?\s*:?-{3,}")
DOI_RE = re.compile(r"\b10\.5089/[A-Za-z0-9._;()/:-]+", re.I)
ISBN_RE = re.compile(r"\b(?:97[89][ -]?)?(?:\d[ -]?){9}[\dXx]\b")
PARAGRAPH_NUMBER_RE = re.compile(r"(?:¶|paragraph\s+)?(\d{1,3})", re.I)

RECOMMENDATION_HEADING_RE = re.compile(
    r"\b(recommendations?|recommended actions?|recomendaciones|recomenda(?:ç|c)[õo]es|recommandations?|"
    r"рекомендации|рекомендация)\b|التوصيات|توصيات",
    re.I,
)
OBSERVATION_HEADING_RE = re.compile(
    r"\b(executive summary|key findings?|main findings?|assessment|diagnostic|observations?|"
    r"resumen ejecutivo|principales hallazgos|constatations|sum[aá]rio executivo|"
    r"резюме|основные выводы|результаты)\b|ملخص|النتائج|الملاحظات",
    re.I,
)
EXCLUDED_SECTION_RE = re.compile(
    r"\b(contents|table of contents|glossary|preface|appendi(?:x|ces)|annex|bibliography|references)\b",
    re.I,
)
STRONG_EXPLICIT_RECOMMENDATION_RE = re.compile(
    r"\b(the mission (?:recommends?|recommended)|is recommended|are recommended|"
    r"we recommend|recommendation is to|it is recommended|se recomienda|recomenda-se|"
    r"il est recommand[ée]|рекомендуется)\b|توصي البعثة",
    re.I,
)
RECOMMENDATION_TABLE_HEADER_RE = re.compile(
    r"^(?:(?:main|key|priority)\s+)?recommendations?$|"
    r"^(?:short|medium|long)[- ]term projections?$|^recommended actions?$",
    re.I,
)

RECOMMENDATION_MODAL_RE = re.compile(
    r"\b(should|must|needs? to|is recommended|are recommended|the mission recommends?|"
    r"recommended that|recommendation is to|priority is to|deber[ií]a|debe(?:n)?|se recomienda|"
    r"devrait|doit|il est recommand[ée]|deveria|deve(?:m)?|recomenda-se|"
    r"следует|необходимо|долж(?:ен|на|ны)|рекомендуется)\b|ينبغي|يجب|يوصى",
    re.I,
)
IMPERATIVE_RE = re.compile(
    r"^(strengthen|establish|develop|adopt|implement|improve|ensure|create|prepare|finalize|"
    r"introduce|increase|reduce|review|revise|update|set up|initiate|start|continue|conduct|"
    r"align|clarify|define|enhance|formalize|operationalize|provide|require|maintain|"
    r"fortalecer|establecer|desarrollar|implementar|mejorar|garantizar|adoptar|"
    r"renforcer|[ée]tablir|am[ée]liorer|mettre en œuvre|adopter|"
    r"refor[çc]ar|estabelecer|desenvolver|implementar|melhorar|adotar|"
    r"укрепить|создать|разработать|внедрить|улучшить|обеспечить|принять)\b|"
    r"^(?:تعزيز|إنشاء|تطوير|تنفيذ|تحسين|ضمان|اعتماد)",
    re.I,
)
OBSERVATION_SIGNAL_RE = re.compile(
    r"\b(found|finds|finding|remains?|lacks?|weak(?:ness|nesses)?|limited|insufficient|"
    r"constraint|gap|shortcoming|challenge|risk|vulnerab|deficien|not yet|does not|do not|"
    r"has not|have not|however|progress|improved|effective|ineffective|fragmented|outdated|"
    r"ausencia|débil|limitad|insuficient|deficien|desaf[ií]o|riesgo|"
    r"faible|limit[ée]|insuffisant|lacune|risque|"
    r"fraco|limitado|insuficiente|defici[êe]ncia|desafio|risco|"
    r"недостат|слаб|огранич|риск|проблем|отсутств)\w*\b|"
    r"ضعف|يفتقر|محدود|تحديات|مخاطر|عدم",
    re.I,
)

MONTHS = {
    "january": 1,
    "february": 2,
    "march": 3,
    "april": 4,
    "may": 5,
    "june": 6,
    "july": 7,
    "august": 8,
    "september": 9,
    "october": 10,
    "november": 11,
    "december": 12,
}
MONTH_PATTERN = "|".join(MONTHS)
SAME_MONTH_RANGE_RE = re.compile(
    rf"\b(?P<month>{MONTH_PATTERN})\s+(?P<start>\d{{1,2}})\s*[–—-]\s*"
    rf"(?P<end>\d{{1,2}}),?\s+(?P<year>20\d{{2}})\b",
    re.I,
)
CROSS_MONTH_RANGE_RE = re.compile(
    rf"\b(?P<month1>{MONTH_PATTERN})\s+(?P<start>\d{{1,2}})\s*[–—-]\s*"
    rf"(?P<month2>{MONTH_PATTERN})\s+(?P<end>\d{{1,2}}),?\s+(?P<year>20\d{{2}})\b",
    re.I,
)
SINGLE_DATE_RE = re.compile(
    rf"\b(?P<month>{MONTH_PATTERN})\s+(?P<day>\d{{1,2}}),?\s+(?P<year>20\d{{2}})\b",
    re.I,
)

_GLOBAL_FIGURES_CACHE: dict[str, dict[str, list[dict[str, Any]]]] = {}

STOPWORDS = {
    "the", "a", "an", "and", "or", "of", "to", "in", "for", "on", "with", "by",
    "that", "this", "these", "those", "is", "are", "be", "should", "must", "it", "its",
    "as", "from", "at", "has", "have", "will", "would", "could", "their", "which", "into",
    "imf", "mission", "recommend", "recommended", "recommendation",
}


def utc_now() -> str:
    return dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat()


def load_json(path: Path) -> Any:
    return json.loads(path.read_text(encoding="utf-8"))


def load_jsonl(path: Path) -> list[dict[str, Any]]:
    if not path.exists():
        return []
    with path.open(encoding="utf-8") as source:
        return [json.loads(line) for line in source if line.strip()]


def write_json(path: Path, value: Any) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    temporary = path.with_suffix(path.suffix + ".tmp")
    temporary.write_text(
        json.dumps(value, ensure_ascii=False, indent=2, sort_keys=False) + "\n",
        encoding="utf-8",
    )
    os.replace(temporary, path)


def write_jsonl(path: Path, rows: Iterable[dict[str, Any]]) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    temporary = path.with_suffix(path.suffix + ".tmp")
    with temporary.open("w", encoding="utf-8") as output:
        for row in rows:
            output.write(json.dumps(row, ensure_ascii=False, sort_keys=True) + "\n")
    os.replace(temporary, path)


def clean_markdown(value: str) -> str:
    value = re.sub(r"!\[[^\]]*\]\([^)]+\)", "", value)
    value = re.sub(r"\[([^\]]+)\]\([^)]+\)", r"\1", value)
    value = re.sub(r"<br\s*/?>", " ", value, flags=re.I)
    value = re.sub(r"</?[^>]+>", " ", value)
    value = re.sub(r"^\s*#{1,6}\s*", "", value)
    value = value.replace("**", "").replace("__", "").replace("`", "")
    value = value.replace("_", " ")
    value = re.sub(r"^\s*[-*•]\s+", "", value)
    value = re.sub(r"\s+", " ", value)
    return value.strip(" |\t\r\n")


def normalize_evidence(value: str) -> str:
    value = value.replace("_", " ")
    return re.sub(r"[^\w]+", " ", value.lower(), flags=re.UNICODE).strip()


def evidence_id(report_id: str, page: int, quote: str) -> str:
    digest = hashlib.sha256(
        f"{report_id}|{page}|{normalize_evidence(quote)}".encode("utf-8")
    ).hexdigest()[:16]
    return f"ev-{digest}"


def evidence(report_id: str, page: int, quote: str, source: str = "document") -> dict[str, Any]:
    return {
        "evidence_id": evidence_id(report_id, page, quote),
        "page": page,
        "quote": quote,
        "source": source,
    }


def token_set(value: str) -> set[str]:
    return {
        token
        for token in re.findall(r"\b[^\W\d_]\w{2,}\b", value.lower(), flags=re.UNICODE)
        if token not in STOPWORDS
    }


def similarity(left: str, right: str) -> float:
    left_tokens, right_tokens = token_set(left), token_set(right)
    if not left_tokens or not right_tokens:
        return 0.0
    return len(left_tokens & right_tokens) / len(left_tokens | right_tokens)


def split_sentences(paragraph: str) -> list[str]:
    paragraph = re.sub(r"\s*\n\s*", " ", paragraph).strip()
    if not paragraph:
        return []
    pieces = re.split(r"(?<=[.!?؟])\s+(?=\S)", paragraph)
    return [piece.strip() for piece in pieces if piece.strip()]


def parse_table_cells(line: str) -> list[str]:
    line = line.strip().strip("|")
    return [clean_markdown(cell) for cell in re.split(r"(?<!\\)\|", line)]


def table_blocks(markdown: str) -> list[list[str]]:
    blocks: list[list[str]] = []
    current: list[str] = []
    for line in markdown.splitlines():
        if line.strip().startswith("|") and line.count("|") >= 2:
            current.append(line)
        else:
            if len(current) >= 2:
                blocks.append(current)
            current = []
    if len(current) >= 2:
        blocks.append(current)
    return blocks


def column_index(headers: list[str], aliases: tuple[str, ...]) -> int | None:
    for index, header in enumerate(headers):
        lowered = header.lower()
        if any(alias in lowered for alias in aliases):
            return index
    return None


def fingerprint(value: str) -> str:
    return " ".join(sorted(token_set(value)))


def add_unique(
    collection: list[dict[str, Any]],
    item: dict[str, Any],
    *,
    similarity_threshold: float = 0.88,
) -> int:
    item_fp = fingerprint(item["verbatim"])
    for index, existing in enumerate(collection):
        existing_fp = existing.get("_fingerprint", "")
        if item_fp == existing_fp or similarity(item["verbatim"], existing["verbatim"]) >= similarity_threshold:
            known = {entry["evidence_id"] for entry in existing["evidence"]}
            existing["evidence"].extend(
                entry for entry in item["evidence"] if entry["evidence_id"] not in known
            )
            if item["confidence"] > existing["confidence"]:
                for key in (
                    "text", "verbatim", "actor", "priority", "timeframe",
                    "section", "extraction_method", "confidence", "_page", "_paragraph_key",
                ):
                    if key in item:
                        existing[key] = item[key]
            return index
    item["_fingerprint"] = item_fp
    collection.append(item)
    return len(collection) - 1


def parse_priority(value: str) -> str | None:
    match = re.search(r"\b(high|medium|low|critical|alta|media|baja|haute|moyenne|faible)\b", value, re.I)
    return match.group(1).lower() if match else None


def parse_timeframe(value: str) -> str | None:
    match = re.search(
        r"\b(near[- ]term|short[- ]term|medium[- ]term|long[- ]term|immediate|"
        r"NT|ST|MT|LT|\d+\s*(?:months?|years?))\b",
        value,
        re.I,
    )
    return match.group(1) if match else None


def recommendation_item(
    report_id: str,
    page: int,
    value: str,
    *,
    section: str,
    method: str,
    confidence: float,
    actor: str | None = None,
    priority: str | None = None,
    timeframe: str | None = None,
    paragraph_key: str | None = None,
) -> dict[str, Any]:
    quote = clean_markdown(value)
    paragraph_match = PARAGRAPH_NUMBER_RE.search(quote)
    return {
        "text": quote,
        "verbatim": quote,
        "actor": actor,
        "priority": priority,
        "timeframe": timeframe,
        "report_paragraph": int(paragraph_match.group(1)) if paragraph_match and "¶" in quote else None,
        "section": section or None,
        "evidence": [evidence(report_id, page, quote)],
        "confidence": confidence,
        "extraction_method": method,
        "review_status": "unreviewed",
        "_page": page,
        "_paragraph_key": paragraph_key,
    }


def observation_item(
    report_id: str,
    page: int,
    value: str,
    *,
    section: str,
    method: str,
    confidence: float,
    paragraph_key: str | None = None,
) -> dict[str, Any]:
    quote = clean_markdown(value)
    return {
        "text": quote,
        "verbatim": quote,
        "topic": section or None,
        "severity": None,
        "evidence": [evidence(report_id, page, quote)],
        "confidence": confidence,
        "extraction_method": method,
        "review_status": "unreviewed",
        "_page": page,
        "_paragraph_key": paragraph_key,
    }


def extract_tables(
    report_id: str,
    pages: list[dict[str, Any]],
    recommendations: list[dict[str, Any]],
    observations: list[dict[str, Any]],
) -> list[tuple[int, int, dict[str, Any]]]:
    explicit_links: list[tuple[int, int, dict[str, Any]]] = []
    for page in pages:
        page_number = page["page"]
        for table_number, lines in enumerate(table_blocks(page["markdown"]), start=1):
            cells = [parse_table_cells(line) for line in lines]
            if len(cells) < 2:
                continue
            headers = cells[0]
            row_start = 2 if len(cells) > 1 and TABLE_SEPARATOR_RE.match(lines[1]) else 1
            rec_col = column_index(
                headers,
                (
                    "recommend", "recommended action", "action required", "proposed action",
                    "recomenda", "рекоменд", "توص",
                ),
            )
            rtl_recommendation_table = False
            if (
                rec_col is None
                and len(headers) == 3
                and re.search(r"[\u0600-\u06ff\ufb50-\ufdff\ufe70-\ufeff]", " ".join(headers))
                and page_number <= 10
            ):
                # Arabic PDF extraction may emit presentation-form glyphs in
                # table headers. IMF action-plan tables consistently place the
                # recommendation/action in the center column after extraction.
                rec_col = 1
                rtl_recommendation_table = True
            if rec_col is None:
                continue
            obs_col = column_index(
                headers,
                (
                    "observation", "finding", "issue", "challenge", "weakness", "rationale",
                    "constat", "вывод", "проблем", "ملاحظ", "نتائج", "قضايا",
                ),
            )
            actor_col = column_index(
                headers, ("responsible", "authority", "institution", "agency", "actor")
            )
            if rtl_recommendation_table:
                actor_col = None
            priority_col = column_index(headers, ("priority", "prioridad", "priorité"))
            time_col = column_index(
                headers, ("timeframe", "timing", "timeline", "deadline", "term")
            )
            section = f"recommendation table {table_number}"
            for row_number, row in enumerate(cells[row_start:], start=1):
                if rec_col >= len(row):
                    continue
                rec_text = row[rec_col]
                if (
                    len(rec_text) < 15
                    or len(token_set(rec_text)) < 3
                    or RECOMMENDATION_HEADING_RE.fullmatch(rec_text)
                    or RECOMMENDATION_TABLE_HEADER_RE.fullmatch(rec_text)
                ):
                    continue
                actor = row[actor_col] if actor_col is not None and actor_col < len(row) else None
                priority_raw = row[priority_col] if priority_col is not None and priority_col < len(row) else ""
                time_raw = row[time_col] if time_col is not None and time_col < len(row) else ""
                paragraph_key = f"p{page_number}-table{table_number}-row{row_number}"
                rec_index = add_unique(
                    recommendations,
                    recommendation_item(
                        report_id,
                        page_number,
                        rec_text,
                        section=section,
                        method="recommendation_table",
                        confidence=0.98,
                        actor=actor or None,
                        priority=parse_priority(priority_raw),
                        timeframe=time_raw or parse_timeframe(rec_text),
                        paragraph_key=paragraph_key,
                    ),
                )
                if obs_col is not None and obs_col < len(row) and len(row[obs_col]) >= 15:
                    obs_text = row[obs_col]
                    obs_index = add_unique(
                        observations,
                        observation_item(
                            report_id,
                            page_number,
                            obs_text,
                            section=section,
                            method="observation_recommendation_table",
                            confidence=0.98,
                            paragraph_key=paragraph_key,
                        ),
                    )
                    explicit_links.append(
                        (
                            obs_index,
                            rec_index,
                            {
                                "relation": "addresses",
                                "link_basis": "explicit_table_row",
                                "confidence": 1.0,
                                "evidence": [evidence(report_id, page_number, " | ".join(row))],
                                "review_status": "unreviewed",
                            },
                        )
                    )
    return explicit_links


def paragraphs_with_sections(pages: list[dict[str, Any]]) -> list[dict[str, Any]]:
    output: list[dict[str, Any]] = []
    section = ""
    for page in pages:
        markdown = page["markdown"]
        table_line_numbers = {
            index
            for index, line in enumerate(markdown.splitlines())
            if line.strip().startswith("|") and line.count("|") >= 2
        }
        current: list[str] = []
        paragraph_counter = 0

        def flush() -> None:
            nonlocal paragraph_counter
            value = "\n".join(current).strip()
            current.clear()
            cleaned = clean_markdown(value)
            if cleaned:
                paragraph_counter += 1
                output.append(
                    {
                        "page": page["page"],
                        "section": section,
                        "raw": value,
                        "text": cleaned,
                        "key": f"p{page['page']}-para{paragraph_counter}",
                    }
                )

        for line_number, line in enumerate(markdown.splitlines()):
            heading_match = HEADING_RE.match(line)
            if heading_match:
                flush()
                section = clean_markdown(heading_match.group(1))
                continue
            if line_number in table_line_numbers:
                flush()
                continue
            if not line.strip():
                flush()
            else:
                current.append(line)
        flush()
    return output


def valid_candidate(value: str) -> bool:
    if not 25 <= len(value) <= 900:
        return False
    if value.count("_") > 5 or re.search(r"_{5,}|\.{5,}", value):
        return False
    if re.fullmatch(r"[\W\d_]+", value):
        return False
    if re.search(r"IMF (?:Technical Assistance|Country) Report\s*\|?\s*\d+", value, re.I):
        return False
    return True


def extract_body_candidates(
    report_id: str,
    pages: list[dict[str, Any]],
    recommendations: list[dict[str, Any]],
    observations: list[dict[str, Any]],
) -> None:
    for paragraph in paragraphs_with_sections(pages):
        section = paragraph["section"]
        if EXCLUDED_SECTION_RE.search(section):
            continue
        recommendation_section = bool(RECOMMENDATION_HEADING_RE.search(section))
        observation_section = bool(OBSERVATION_HEADING_RE.search(section))
        raw_starts_bullet = bool(re.match(r"\s*(?:[-*•]|\d+[.)])\s+", paragraph["raw"]))
        for sentence in split_sentences(paragraph["text"]):
            sentence = clean_markdown(sentence)
            if not valid_candidate(sentence):
                continue
            has_modal = bool(RECOMMENDATION_MODAL_RE.search(sentence))
            imperative = bool(IMPERATIVE_RE.search(sentence))
            if has_modal or (recommendation_section and (imperative or raw_starts_bullet)):
                confidence = 0.88 if recommendation_section else 0.72
                method = (
                    "recommendation_section_sentence"
                    if recommendation_section
                    else "explicit_recommendation_modal"
                )
                add_unique(
                    recommendations,
                    recommendation_item(
                        report_id,
                        paragraph["page"],
                        sentence,
                        section=section,
                        method=method,
                        confidence=confidence,
                        priority=parse_priority(sentence),
                        timeframe=parse_timeframe(sentence),
                        paragraph_key=paragraph["key"],
                    ),
                )
                continue
            has_signal = bool(OBSERVATION_SIGNAL_RE.search(sentence))
            numbered_finding = bool(re.match(r"^\d+\.\s+", paragraph["text"]))
            if has_signal and (observation_section or numbered_finding or len(sentence) >= 50):
                confidence = 0.82 if observation_section else 0.62
                add_unique(
                    observations,
                    observation_item(
                        report_id,
                        paragraph["page"],
                        sentence,
                        section=section,
                        method=(
                            "finding_section_sentence"
                            if observation_section
                            else "diagnostic_signal_sentence"
                        ),
                        confidence=confidence,
                        paragraph_key=paragraph["key"],
                    ),
                )


def parse_iso_date(year: int, month: int, day: int) -> str | None:
    try:
        return dt.date(year, month, day).isoformat()
    except ValueError:
        return None


def extract_date_mentions(
    report_id: str,
    title: str,
    pages: list[dict[str, Any]],
    publication_date: str | None,
    source_page_url: str | None,
) -> list[dict[str, Any]]:
    dates: list[dict[str, Any]] = []
    url_date = None
    if source_page_url:
        match = re.search(r"/issues/(\d{4})/(\d{2})/(\d{2})/", source_page_url, re.I)
        if match:
            url_date = parse_iso_date(int(match.group(1)), int(match.group(2)), int(match.group(3)))
    primary_publication_date = url_date or (publication_date[:10] if publication_date else None)
    if primary_publication_date:
        dates.append(
            {
                "type": "publication",
                "start": primary_publication_date,
                "end": primary_publication_date,
                "precision": "day",
                "verbatim": primary_publication_date,
                "evidence": [
                    {"source": "imf_publication_url" if url_date else "imf_index_metadata"}
                ],
                "confidence": 1.0 if not url_date else 0.98,
            }
        )
    if publication_date and publication_date[:10] != primary_publication_date:
        dates.append(
            {
                "type": "imf_index_date",
                "start": publication_date[:10],
                "end": publication_date[:10],
                "precision": "day",
                "verbatim": publication_date,
                "evidence": [{"source": "imf_index_metadata"}],
                "confidence": 1.0,
            }
        )
    search_sources = [(0, title)] + [
        (page["page"], page["text"]) for page in pages[:6]
    ]
    seen: set[tuple[str, str | None, str | None]] = set()
    for page_number, text in search_sources:
        for pattern, cross_month in ((CROSS_MONTH_RANGE_RE, True), (SAME_MONTH_RANGE_RE, False)):
            for match in pattern.finditer(text):
                year = int(match.group("year"))
                if cross_month:
                    start_month = MONTHS[match.group("month1").lower()]
                    end_month = MONTHS[match.group("month2").lower()]
                else:
                    start_month = end_month = MONTHS[match.group("month").lower()]
                start = parse_iso_date(year, start_month, int(match.group("start")))
                end = parse_iso_date(year, end_month, int(match.group("end")))
                key = ("mission_or_report_range", start, end)
                if start and end and key not in seen:
                    seen.add(key)
                    quote = match.group(0)
                    dates.append(
                        {
                            "type": "mission_or_report_range",
                            "start": start,
                            "end": end,
                            "precision": "day",
                            "verbatim": quote,
                            "evidence": (
                                [evidence(report_id, page_number, quote)]
                                if page_number
                                else [{"source": "title", "quote": quote}]
                            ),
                            "confidence": 0.8,
                        }
                    )
        for match in SINGLE_DATE_RE.finditer(text):
            year = int(match.group("year"))
            value = parse_iso_date(year, MONTHS[match.group("month").lower()], int(match.group("day")))
            key = ("date_mention", value, value)
            if value and key not in seen:
                seen.add(key)
                quote = match.group(0)
                dates.append(
                    {
                        "type": "date_mention",
                        "start": value,
                        "end": value,
                        "precision": "day",
                        "verbatim": quote,
                        "evidence": (
                            [evidence(report_id, page_number, quote)]
                            if page_number
                            else [{"source": "title", "quote": quote}]
                        ),
                        "confidence": 0.65,
                    }
                )
    return dates


def prepared_by_statement(pages: list[dict[str, Any]]) -> tuple[int, str, str] | None:
    stop_re = re.compile(
        r"^(?:authoring\s+)?departments?\b|^approved\b|^authorized\b|"
        r"^international monetary fund\b|^the mission\b|^prepared for\b",
        re.I,
    )
    department_phrase_re = re.compile(
        r"\b(fiscal affairs|monetary and capital markets|statistics|legal|"
        r"institute for capacity development|finance|research|department)\b",
        re.I,
    )
    for page in pages[:8]:
        lines = [line.strip(" \t:;") for line in page["text"].splitlines()]
        for index, line in enumerate(lines):
            match = re.search(r"\bPrepared\s+by\b\s*[:\-]?\s*(.*)$", line, re.I)
            if not match:
                continue
            collected = [match.group(1).strip()] if match.group(1).strip() else []
            stop_line = ""
            for candidate in lines[index + 1 : index + 10]:
                if not candidate:
                    continue
                if stop_re.search(candidate):
                    stop_line = candidate
                    break
                if re.fullmatch(r"(?:[A-Z][A-Z .&/-]+|\d{4})", candidate) and collected:
                    break
                collected.append(candidate)
                if len(collected) >= 4:
                    break
            if stop_line.lower() == "department" and len(collected) > 1:
                if department_phrase_re.search(collected[-1]):
                    collected.pop()
            statement = re.sub(
                r"\s+", " ", " ".join(collected).replace("_", " ")
            ).strip(" .,;")
            if 2 <= len(statement) <= 300:
                raw_quote = "Prepared By\n" + "\n".join(collected)
                return page["page"], statement, raw_quote
    return None


def split_prepared_by_names(statement: str) -> list[str]:
    normalized = re.sub(r"\s+(?:and|&)\s+", ",", statement, flags=re.I)
    parts = [part.strip(" .;,") for part in re.split(r"[,;]", normalized)]
    plausible = []
    for part in parts:
        words = re.findall(r"[^\W\d_]+", part, flags=re.UNICODE)
        if 2 <= len(words) <= 10 and not re.search(r"\b(department|division|team|staff)\b", part, re.I):
            plausible.append(part)
    return plausible or [statement]


def extract_authors(
    report_id: str, report: dict[str, Any], document: dict[str, Any], pages: list[dict[str, Any]]
) -> list[dict[str, Any]]:
    authors: list[dict[str, Any]] = []
    indexed = report.get("author_indexed")
    if indexed:
        authors.append(
            {
                "name": indexed,
                "role": "indexed_institutional_author",
                "evidence": [{"source": "imf_index_metadata"}],
                "confidence": 1.0,
            }
        )
    pdf_author = (document.get("pdf_metadata") or {}).get("author")
    if pdf_author and pdf_author.lower() not in {str(indexed).lower(), "imf"}:
        authors.append(
            {
                "name": pdf_author,
                "role": "pdf_metadata_author",
                "evidence": [{"source": "pdf_metadata"}],
                "confidence": 0.9,
            }
        )
    prepared = prepared_by_statement(pages)
    if prepared:
        page_number, statement, quote = prepared
        for name in split_prepared_by_names(statement):
            if all(name.lower() != author["name"].lower() for author in authors):
                authors.append(
                    {
                        "name": name,
                        "role": "prepared_by",
                        "verbatim_statement": statement,
                        "evidence": [evidence(report_id, page_number, quote)],
                        "confidence": 0.82,
                    }
                )
    return authors


def extract_authoring_departments(report_id: str, pages: list[dict[str, Any]]) -> list[dict[str, Any]]:
    departments: list[dict[str, Any]] = []
    known_re = re.compile(
        r"\b(Fiscal Affairs Department|Monetary and Capital Markets Department|"
        r"Statistics Department|Legal Department|Institute for Capacity Development|"
        r"Research Department|Finance Department)\b",
        re.I,
    )
    for page in pages[:8]:
        for match in known_re.finditer(re.sub(r"\s+", " ", page["text"])):
            name = match.group(1)
            if all(name.lower() != item["name"].lower() for item in departments):
                departments.append(
                    {
                        "name": name,
                        "evidence": [evidence(report_id, page["page"], match.group(0))],
                        "confidence": 0.9,
                    }
                )
    return departments


def extract_identifiers(pages: list[dict[str, Any]], report: dict[str, Any]) -> dict[str, Any]:
    text = "\n".join(page["text"] for page in pages[:8])
    dois = sorted({match.group(0).rstrip(".,;)") for match in DOI_RE.finditer(text)})
    isbns = []
    for match in ISBN_RE.finditer(text):
        compact = re.sub(r"[ -]", "", match.group(0)).upper()
        if len(compact) in {10, 13} and compact not in isbns:
            isbns.append(compact)
    return {
        "series": report.get("series", []),
        "series_volume_no": report.get("series_volume_no"),
        "doi": dois,
        "isbn": isbns,
        "subjects": report.get("subjects", []),
        "topics": report.get("topics", []),
        "keywords": report.get("keywords", []),
        "description_indexed": report.get("description"),
    }


def classify_recommendation(item: dict[str, Any]) -> None:
    """Assign an explicitness taxonomy without discarding recall-oriented candidates."""
    text = item["verbatim"]
    method = item["extraction_method"]
    strong_explicit = bool(STRONG_EXPLICIT_RECOMMENDATION_RE.search(text))
    direct_action = bool(IMPERATIVE_RE.search(text) or RECOMMENDATION_MODAL_RE.search(text))

    if method == "recommendation_table":
        recommendation_type = "explicit_table"
        explicitness = "explicit"
        tier = "high"
        conservative = True
        confidence = 0.98
    elif strong_explicit:
        recommendation_type = "explicit_attributed_statement"
        explicitness = "explicit"
        tier = "high"
        conservative = True
        confidence = 0.92
    elif method == "recommendation_section_sentence" and direct_action:
        recommendation_type = "direct_action_in_recommendation_section"
        explicitness = "direct_normative"
        tier = "high"
        conservative = True
        confidence = 0.85
    elif method == "explicit_recommendation_modal":
        recommendation_type = "normative_modal_candidate"
        explicitness = "implicit_candidate"
        tier = "medium"
        conservative = False
        confidence = 0.65
    else:
        recommendation_type = "recommendation_section_context_candidate"
        explicitness = "context_candidate"
        tier = "low"
        conservative = False
        confidence = 0.35

    item["recommendation_type"] = recommendation_type
    item["explicitness"] = explicitness
    item["confidence_tier"] = tier
    item["in_conservative_set"] = conservative
    item["confidence"] = confidence


def finalize_entities(
    report_id: str,
    recommendations: list[dict[str, Any]],
    observations: list[dict[str, Any]],
    explicit_links: list[tuple[int, int, dict[str, Any]]],
) -> tuple[list[dict[str, Any]], list[dict[str, Any]], list[dict[str, Any]]]:
    for item in recommendations:
        classify_recommendation(item)
    recommendations.sort(key=lambda item: (item["_page"], -item["confidence"], item["verbatim"]))
    observations.sort(key=lambda item: (item["_page"], -item["confidence"], item["verbatim"]))
    # Sorting invalidates explicit temporary indices, so remap by paragraph keys and
    # text. Explicit rows have unique shared paragraph keys.
    rec_by_paragraph = defaultdict(list)
    obs_by_paragraph = defaultdict(list)
    for index, item in enumerate(recommendations):
        rec_by_paragraph[item.get("_paragraph_key")].append(index)
    for index, item in enumerate(observations):
        obs_by_paragraph[item.get("_paragraph_key")].append(index)

    for index, item in enumerate(recommendations, start=1):
        item["recommendation_id"] = f"{report_id}-rec-{index:04d}"
    for index, item in enumerate(observations, start=1):
        item["observation_id"] = f"{report_id}-obs-{index:04d}"

    links: list[dict[str, Any]] = []
    seen_pairs: set[tuple[str, str, str]] = set()

    # Reconstruct explicit table-row links from matching paragraph keys.
    explicit_keys = {
        recommendations[rec_index].get("_paragraph_key")
        for _, rec_index, _ in explicit_links
        if 0 <= rec_index < len(recommendations)
    }
    # The list above may refer to pre-sort indices; all explicit rows are also
    # identifiable by the table-row paragraph key.
    explicit_keys.update(
        item.get("_paragraph_key")
        for item in recommendations
        if item.get("extraction_method") == "recommendation_table"
    )
    for key in explicit_keys:
        if not key:
            continue
        for obs_index in obs_by_paragraph.get(key, []):
            for rec_index in rec_by_paragraph.get(key, []):
                obs = observations[obs_index]
                rec = recommendations[rec_index]
                pair = (obs["observation_id"], rec["recommendation_id"], "explicit_table_row")
                if pair in seen_pairs:
                    continue
                seen_pairs.add(pair)
                links.append(
                    {
                        "observation_id": obs["observation_id"],
                        "recommendation_id": rec["recommendation_id"],
                        "relation": "addresses",
                        "link_basis": "explicit_table_row",
                        "evidence": rec["evidence"],
                        "confidence": 1.0,
                        "review_status": "unreviewed",
                        "recommendation_type": rec["recommendation_type"],
                        "recommendation_confidence_tier": rec["confidence_tier"],
                        "conservative_recommendation": rec["in_conservative_set"],
                    }
                )

    # Same-paragraph modal links are strong contextual evidence, but not declared causal.
    for rec in recommendations:
        key = rec.get("_paragraph_key")
        if not key:
            continue
        for obs_index in obs_by_paragraph.get(key, []):
            obs = observations[obs_index]
            pair = (obs["observation_id"], rec["recommendation_id"], "same_paragraph")
            if any(existing[:2] == pair[:2] for existing in seen_pairs):
                continue
            seen_pairs.add(pair)
            links.append(
                {
                    "observation_id": obs["observation_id"],
                    "recommendation_id": rec["recommendation_id"],
                    "relation": "responds_to_context",
                    "link_basis": "same_paragraph",
                    "evidence": rec["evidence"],
                    "confidence": 0.78,
                    "review_status": "unreviewed",
                    "recommendation_type": rec["recommendation_type"],
                    "recommendation_confidence_tier": rec["confidence_tier"],
                    "conservative_recommendation": rec["in_conservative_set"],
                }
            )

    # If no stronger link exists, retain one clearly labeled lexical/contextual link.
    linked_recommendations = {link["recommendation_id"] for link in links}
    for rec in recommendations:
        if rec["recommendation_id"] in linked_recommendations:
            continue
        candidates = []
        for obs in observations:
            if abs(obs["_page"] - rec["_page"]) > 1:
                continue
            score = similarity(obs["verbatim"], rec["verbatim"])
            if score >= 0.12:
                candidates.append((score, obs))
        if candidates:
            score, obs = max(candidates, key=lambda item: item[0])
            links.append(
                {
                    "observation_id": obs["observation_id"],
                    "recommendation_id": rec["recommendation_id"],
                    "relation": "contextually_associated_with",
                    "link_basis": "same_or_adjacent_page_lexical_similarity",
                    "evidence": rec["evidence"],
                    "confidence": round(min(0.65, 0.4 + score), 3),
                    "review_status": "unreviewed",
                    "recommendation_type": rec["recommendation_type"],
                    "recommendation_confidence_tier": rec["confidence_tier"],
                    "conservative_recommendation": rec["in_conservative_set"],
                }
            )

    for collection in (recommendations, observations):
        for item in collection:
            for key in list(item):
                if key.startswith("_"):
                    del item[key]
    links.sort(key=lambda item: (item["recommendation_id"], item["observation_id"]))
    return recommendations, observations, links


def report_schema() -> dict[str, Any]:
    evidence_schema = {
        "type": "object",
        "properties": {
            "evidence_id": {"type": "string"},
            "page": {"type": "integer", "minimum": 1},
            "quote": {"type": "string"},
            "source": {"type": "string"},
        },
        "required": ["source"],
        "additionalProperties": True,
    }
    return {
        "$schema": "https://json-schema.org/draft/2020-12/schema",
        "$id": "https://cd-eval.local/schemas/report.schema.json",
        "title": "IMF Technical Assistance Structured Report",
        "type": "object",
        "required": [
            "schema_version", "report_id", "source_sha256", "title", "authors",
            "countries", "dates", "metadata", "observations", "recommendations",
            "observation_recommendation_links", "figures", "extraction",
        ],
        "properties": {
            "schema_version": {"const": SCHEMA_VERSION},
            "report_id": {"type": "string"},
            "source_sha256": {"type": "string", "pattern": "^[0-9a-f]{64}$"},
            "title": {"type": "string"},
            "language": {"type": "array", "items": {"type": "string"}},
            "authors": {"type": "array", "items": {"type": "object"}},
            "countries": {"type": "array", "items": {"type": "object"}},
            "dates": {"type": "array", "items": {"type": "object"}},
            "metadata": {"type": "object"},
            "observations": {
                "type": "array",
                "items": {
                    "type": "object",
                    "required": ["observation_id", "text", "verbatim", "evidence", "confidence"],
                    "properties": {"evidence": {"type": "array", "items": evidence_schema}},
                    "additionalProperties": True,
                },
            },
            "recommendations": {
                "type": "array",
                "items": {
                    "type": "object",
                    "required": [
                        "recommendation_id", "text", "verbatim", "evidence", "confidence",
                        "recommendation_type", "explicitness", "confidence_tier",
                        "in_conservative_set",
                    ],
                    "properties": {"evidence": {"type": "array", "items": evidence_schema}},
                    "additionalProperties": True,
                },
            },
            "observation_recommendation_links": {
                "type": "array",
                "items": {
                    "type": "object",
                    "required": [
                        "observation_id", "recommendation_id", "relation", "link_basis",
                        "evidence", "confidence",
                    ],
                    "additionalProperties": True,
                },
            },
            "figures": {"type": "array", "items": {"type": "object"}},
            "extraction": {"type": "object"},
        },
        "additionalProperties": False,
    }


def validate_evidence_grounding(record: dict[str, Any], pages: list[dict[str, Any]]) -> list[str]:
    errors: list[str] = []
    page_text = {page["page"]: normalize_evidence(page["text"] + " " + page["markdown"]) for page in pages}
    page_count = len(pages)
    for kind in ("observations", "recommendations"):
        for item in record[kind]:
            if not item.get("evidence"):
                errors.append(f"{kind}:{item.get(kind[:-1] + '_id')}: missing evidence")
            for entry in item.get("evidence", []):
                page = entry.get("page")
                quote = normalize_evidence(entry.get("quote", ""))
                if not isinstance(page, int) or not 1 <= page <= page_count:
                    errors.append(f"{kind}: invalid page {page}")
                elif quote and quote not in page_text.get(page, ""):
                    # Layout table extraction can normalize hyphenation or collapse
                    # spaces between adjacent PDF text spans differently.
                    compact_quote = re.sub(r"\s+", "", quote)
                    compact_page = re.sub(r"\s+", "", page_text.get(page, ""))
                    quote_tokens = token_set(quote)
                    page_tokens = token_set(page_text.get(page, ""))
                    token_coverage = len(quote_tokens & page_tokens) / max(1, len(quote_tokens))
                    if compact_quote not in compact_page and token_coverage < 0.9:
                        errors.append(f"{kind}: evidence not grounded on page {page}: {entry.get('quote','')[:80]}")
    observation_ids = {item["observation_id"] for item in record["observations"]}
    recommendation_ids = {item["recommendation_id"] for item in record["recommendations"]}
    for link in record["observation_recommendation_links"]:
        if link["observation_id"] not in observation_ids:
            errors.append(f"link unknown observation {link['observation_id']}")
        if link["recommendation_id"] not in recommendation_ids:
            errors.append(f"link unknown recommendation {link['recommendation_id']}")
    return errors


def global_figures_for_report(interim_dir: Path, report_id: str) -> list[dict[str, Any]]:
    cache_key = interim_dir.resolve().as_posix()
    if cache_key not in _GLOBAL_FIGURES_CACHE:
        grouped: dict[str, list[dict[str, Any]]] = defaultdict(list)
        for figure in load_jsonl(interim_dir / "figures.jsonl"):
            grouped[figure["report_id"]].append(figure)
        _GLOBAL_FIGURES_CACHE[cache_key] = dict(grouped)
    return _GLOBAL_FIGURES_CACHE[cache_key].get(report_id, [])


def extract_one(job: dict[str, Any]) -> dict[str, Any]:
    report = job["report"]
    source = job["manifest"]
    report_id = report["report_id"]
    interim_report_dir = Path(job["interim_dir"]) / report_id
    processed_dir = Path(job["processed_dir"])
    final_path = processed_dir / "reports" / f"{report_id}.json"
    refresh = bool(job.get("refresh"))

    if final_path.exists() and not refresh:
        existing = load_json(final_path)
        if (
            existing.get("source_sha256") == source["sha256"]
            and existing.get("extraction", {}).get("extractor_version") == EXTRACTOR_VERSION
        ):
            return {
                "report_id": report_id,
                "status": "existing",
                "record": existing,
                "validation_errors": [],
            }

    pages = load_jsonl(interim_report_dir / "pages.jsonl")
    document = load_json(interim_report_dir / "document.json")
    figures = global_figures_for_report(Path(job["interim_dir"]), report_id)
    if not pages:
        raise RuntimeError(f"missing interim pages for {report_id}")

    recommendations: list[dict[str, Any]] = []
    observations: list[dict[str, Any]] = []
    explicit_links = extract_tables(report_id, pages, recommendations, observations)
    extract_body_candidates(report_id, pages, recommendations, observations)
    # Keep a conservative upper bound and favor higher-confidence candidates.
    if len(recommendations) > 250:
        recommendations = sorted(recommendations, key=lambda item: -item["confidence"])[:250]
    if len(observations) > 300:
        observations = sorted(observations, key=lambda item: -item["confidence"])[:300]
    recommendations, observations, links = finalize_entities(
        report_id, recommendations, observations, explicit_links
    )

    countries = []
    formal = report.get("formal_countries", [])
    iso_codes = report.get("iso_codes", [])
    names = report.get("countries", []) or formal
    country_source = "imf_index_metadata"
    country_confidence = 1.0
    if not names and ":" in (report.get("title") or ""):
        names = [(report["title"].split(":", 1)[0]).strip()]
        country_source = "title_prefix_fallback"
        country_confidence = 0.9
    fallback_iso = {
        "armenia": "ARM",
        "republic of armenia": "ARM",
        "kosovo": "XKX",
        "republic of kosovo": "XKX",
        "democratic republic of the congo": "COD",
    }
    for index, name in enumerate(names):
        countries.append(
            {
                "name": name,
                "formal_name": formal[index] if index < len(formal) else None,
                "iso3": (
                    iso_codes[index]
                    if index < len(iso_codes)
                    else fallback_iso.get(name.lower())
                ),
                "evidence": [{"source": country_source}],
                "confidence": country_confidence,
            }
        )

    record = {
        "schema_version": SCHEMA_VERSION,
        "report_id": report_id,
        "source_sha256": source["sha256"],
        "title": report.get("title") or "",
        "language": report.get("language", []),
        "authors": extract_authors(report_id, report, document, pages),
        "countries": countries,
        "dates": extract_date_mentions(
            report_id,
            report.get("title") or "",
            pages,
            report.get("publication_date"),
            report.get("source_page_url"),
        ),
        "metadata": {
            **extract_identifiers(pages, report),
            "authoring_departments": extract_authoring_departments(report_id, pages),
            "source_page_url": report.get("source_page_url"),
            "source_pdf_url": source.get("source_pdf_url"),
            "page_count": document["page_count"],
            "interim_extraction_method": document["extraction_method"],
            "needs_ocr_pages": document.get("needs_ocr_pages", []),
        },
        "observations": observations,
        "recommendations": recommendations,
        "observation_recommendation_links": links,
        "figures": figures,
        "extraction": {
            "method": EXTRACTION_METHOD,
            "extractor_version": EXTRACTOR_VERSION,
            "generated_at": utc_now(),
            "review_status": "unreviewed",
            "evidence_requirement": "page-grounded verbatim source span",
            "limitations": [
                "Automated deterministic baseline; not a human-annotated gold record.",
                "The recommendations array is recall-oriented and includes classified candidates; use in_conservative_set=true for the higher-precision subset.",
                "Contextual links are proximity/lexical associations unless link_basis is explicit_table_row.",
                "Priority, timeframe, and actor are null when not explicit in a recommendation table or sentence.",
            ],
        },
    }
    schema_errors = [error.message for error in jsonschema.Draft202012Validator(report_schema()).iter_errors(record)]
    grounding_errors = validate_evidence_grounding(record, pages)
    errors = schema_errors + grounding_errors
    final_path.parent.mkdir(parents=True, exist_ok=True)
    write_json(final_path, record)
    return {
        "report_id": report_id,
        "status": "extracted",
        "record": record,
        "validation_errors": errors,
    }


def flatten_outputs(
    results: list[dict[str, Any]], processed_dir: Path, failures: list[dict[str, str]]
) -> dict[str, Any]:
    records = [result["record"] for result in results]
    records.sort(key=lambda record: record["report_id"])
    write_jsonl(processed_dir / "reports.jsonl", records)
    write_jsonl(
        processed_dir / "observations.jsonl",
        (
            {"report_id": record["report_id"], **item}
            for record in records
            for item in record["observations"]
        ),
    )
    write_jsonl(
        processed_dir / "recommendations.jsonl",
        (
            {"report_id": record["report_id"], **item}
            for record in records
            for item in record["recommendations"]
        ),
    )
    write_jsonl(
        processed_dir / "recommendations_conservative.jsonl",
        (
            {"report_id": record["report_id"], **item}
            for record in records
            for item in record["recommendations"]
            if item["in_conservative_set"]
        ),
    )
    write_jsonl(
        processed_dir / "observation_recommendation_links.jsonl",
        (
            {"report_id": record["report_id"], **item}
            for record in records
            for item in record["observation_recommendation_links"]
        ),
    )
    write_jsonl(
        processed_dir / "observation_recommendation_links_conservative.jsonl",
        (
            {"report_id": record["report_id"], **item}
            for record in records
            for item in record["observation_recommendation_links"]
            if item.get("conservative_recommendation")
        ),
    )
    write_jsonl(
        processed_dir / "figures.jsonl",
        (
            item for record in records for item in record["figures"]
        ),
    )
    validation_errors = [
        {"report_id": result["report_id"], "errors": result["validation_errors"]}
        for result in results
        if result["validation_errors"]
    ]
    recommendation_type_counts = Counter(
        item["recommendation_type"]
        for record in records
        for item in record["recommendations"]
    )
    recommendation_tier_counts = Counter(
        item["confidence_tier"]
        for record in records
        for item in record["recommendations"]
    )
    conservative_recommendation_count = sum(
        item["in_conservative_set"]
        for record in records
        for item in record["recommendations"]
    )
    conservative_link_count = sum(
        item.get("conservative_recommendation", False)
        for record in records
        for item in record["observation_recommendation_links"]
    )
    reports_with_no_conservative_recommendations = [
        record["report_id"]
        for record in records
        if not any(item["in_conservative_set"] for item in record["recommendations"])
    ]
    summary = {
        "updated_at": utc_now(),
        "schema_version": SCHEMA_VERSION,
        "extractor_version": EXTRACTOR_VERSION,
        "method": EXTRACTION_METHOD,
        "report_count": len(records),
        "observation_count": sum(len(record["observations"]) for record in records),
        "recommendation_count": sum(len(record["recommendations"]) for record in records),
        "recommendation_candidate_count": sum(
            len(record["recommendations"]) for record in records
        ),
        "conservative_recommendation_count": conservative_recommendation_count,
        "conservative_recommendation_report_count": (
            len(records) - len(reports_with_no_conservative_recommendations)
        ),
        "reports_with_no_conservative_recommendations": (
            reports_with_no_conservative_recommendations
        ),
        "recommendation_type_counts": dict(sorted(recommendation_type_counts.items())),
        "recommendation_confidence_tier_counts": dict(
            sorted(recommendation_tier_counts.items())
        ),
        "link_count": sum(len(record["observation_recommendation_links"]) for record in records),
        "conservative_link_count": conservative_link_count,
        "explicit_table_link_count": sum(
            link["link_basis"] == "explicit_table_row"
            for record in records
            for link in record["observation_recommendation_links"]
        ),
        "figure_count": sum(len(record["figures"]) for record in records),
        "reports_with_no_observations": [
            record["report_id"] for record in records if not record["observations"]
        ],
        "reports_with_no_recommendations": [
            record["report_id"] for record in records if not record["recommendations"]
        ],
        "validation_error_report_count": len(validation_errors),
        "validation_errors": validation_errors,
        "failed_count": len(failures),
        "failures": failures,
        "review_status": "unreviewed_automated_baseline",
        "recommendation_taxonomy": {
            "explicit_table": "A recommendation/action row in a report table explicitly designated for recommendations or an action plan.",
            "explicit_attributed_statement": "Text explicitly attributed as a recommendation (for example, 'the mission recommends' or 'is recommended').",
            "direct_action_in_recommendation_section": "An imperative or normative action inside a recommendation section.",
            "normative_modal_candidate": "A should/must/need-to statement outside a recommendation section; retained for recall but not in the conservative set.",
            "recommendation_section_context_candidate": "Context in a recommendation section without a direct action signal; low-confidence candidate.",
        },
    }
    write_json(processed_dir / "validation_summary.json", summary)
    write_json(
        processed_dir / "recommendation_taxonomy.json",
        {
            "schema_version": SCHEMA_VERSION,
            "definitions": summary["recommendation_taxonomy"],
            "type_counts": summary["recommendation_type_counts"],
            "confidence_tier_counts": summary[
                "recommendation_confidence_tier_counts"
            ],
            "candidate_count": summary["recommendation_candidate_count"],
            "conservative_count": summary["conservative_recommendation_count"],
        },
    )
    write_json(processed_dir / "schemas" / "report.schema.json", report_schema())
    return summary


def extract_corpus(
    inventory: list[dict[str, Any]],
    manifest: list[dict[str, Any]],
    *,
    interim_dir: Path,
    processed_dir: Path,
    workers: int,
    refresh: bool,
) -> dict[str, Any]:
    source_by_id = {row["report_id"]: row for row in manifest}
    jobs = [
        {
            "report": report,
            "manifest": source_by_id[report["report_id"]],
            "interim_dir": interim_dir.as_posix(),
            "processed_dir": processed_dir.as_posix(),
            "refresh": refresh,
        }
        for report in inventory
    ]
    results: list[dict[str, Any]] = []
    failures: list[dict[str, str]] = []
    with concurrent.futures.ProcessPoolExecutor(max_workers=max(1, workers)) as pool:
        futures = {pool.submit(extract_one, job): job for job in jobs}
        for future in concurrent.futures.as_completed(futures):
            job = futures[future]
            try:
                result = future.result()
                results.append(result)
                status = result["status"]
            except Exception as exc:
                failures.append(
                    {
                        "report_id": job["report"]["report_id"],
                        "error": f"{type(exc).__name__}: {exc}",
                    }
                )
                status = "failed"
            print(
                f"extract: {len(results) + len(failures)}/{len(jobs)} {status}: "
                f"{job['report']['report_id']}",
                file=sys.stderr,
            )
    summary = flatten_outputs(results, processed_dir, failures)
    return summary


def select_reports(
    inventory: list[dict[str, Any]], limit: int | None, ids: str | None
) -> list[dict[str, Any]]:
    if ids:
        selected_ids = {value.strip() for value in ids.split(",") if value.strip()}
        missing = selected_ids - {row["report_id"] for row in inventory}
        if missing:
            raise SystemExit(f"unknown report IDs: {sorted(missing)}")
        inventory = [row for row in inventory if row["report_id"] in selected_ids]
    if limit is not None:
        inventory = inventory[:limit]
    return inventory


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(description="Extract structured IMF recommendations and observations")
    parser.add_argument("--raw-dir", type=Path, default=Path("data/raw"))
    parser.add_argument("--interim-dir", type=Path, default=Path("data/interim"))
    parser.add_argument("--processed-dir", type=Path, default=Path("data/processed"))
    parser.add_argument("--workers", type=int, default=min(8, os.cpu_count() or 1))
    parser.add_argument("--limit", type=int)
    parser.add_argument("--ids", help="comma-separated report IDs")
    parser.add_argument("--refresh", action="store_true")
    return parser


def main(argv: Sequence[str] | None = None) -> int:
    args = build_parser().parse_args(argv)
    inventory = load_jsonl(args.raw_dir / "manifests" / "inventory.jsonl")
    manifest = load_jsonl(args.raw_dir / "manifests" / "download_manifest.jsonl")
    if not inventory or not manifest:
        raise SystemExit("raw inventory/download manifest is missing")
    inventory = select_reports(inventory, args.limit, args.ids)
    missing_interim = [
        report["report_id"]
        for report in inventory
        if not (args.interim_dir / report["report_id"] / "document.json").exists()
    ]
    if missing_interim:
        raise SystemExit(
            f"interim conversion missing for {len(missing_interim)} report(s); "
            "run imf-process convert first"
        )
    summary = extract_corpus(
        inventory,
        manifest,
        interim_dir=args.interim_dir,
        processed_dir=args.processed_dir,
        workers=args.workers,
        refresh=args.refresh,
    )
    print(json.dumps(summary, ensure_ascii=False, indent=2), file=sys.stderr)
    return 1 if summary["failed_count"] else 0


if __name__ == "__main__":
    raise SystemExit(main())