xberg 1.1.1

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

use axum::body::to_bytes;
use axum::extract::{FromRequest, Multipart, Request};
use axum::http::{HeaderMap, StatusCode, header};
use axum::{Json, extract::State, response::IntoResponse};
use base64::{Engine as _, engine::general_purpose::STANDARD};
use bytes::Bytes;

use crate::cache;
use crate::core::config::{ExtractInput, ExtractInputKind, ExtractionResult};

use std::sync::Arc;

use super::{
    error::{ApiError, JsonApi, MultipartApi},
    types::{
        ApiState, AsyncJobResponse, CacheClearResponse, CacheStatsResponse, DetectResponse, HealthResponse,
        InfoResponse, JobStatusResponse, ManifestEntryResponse, ManifestResponse, VersionResponse, WarmRequest,
        WarmResponse,
    },
};

/// Multipart field names accepted by `/extract` and `/extract-async`.
///
/// Validation is an allowlist: a field outside this set is rejected rather than
/// silently dropped, so a typo (`configuration`, `outputFormat`) fails loudly
/// instead of being ignored and quietly falling back to the server defaults (#248).
const ACCEPTED_EXTRACT_MULTIPART_FIELDS: [&str; 8] = [
    "file",
    "files",
    "urls",
    "inputs",
    "config",
    "output_format",
    "pdf_password",
    "format",
];

/// Build the rejection for a multipart field name outside the allowlist.
fn unknown_multipart_field_error(field_name: &str) -> ApiError {
    ApiError::validation(crate::error::XbergError::validation(format!(
        "Unknown multipart field '{}'. Accepted fields: {}",
        field_name,
        ACCEPTED_EXTRACT_MULTIPART_FIELDS.join(", ")
    )))
}

/// Unified extraction input accepted by `/extract` and `/extract-async`.
#[derive(Debug, Clone)]
enum ApiExtractInput {
    Bytes {
        data: Bytes,
        mime_type: String,
        file_name: Option<String>,
        config: Option<crate::core::config::FileExtractionConfig>,
    },
    Uri {
        uri: String,
        mime_type: Option<String>,
        config: Option<crate::core::config::FileExtractionConfig>,
    },
}

impl ApiExtractInput {
    fn into_core_input(self) -> ExtractInput {
        match self {
            Self::Bytes {
                data,
                mime_type,
                file_name,
                config,
            } => ExtractInput {
                config,
                ..ExtractInput::from_bytes(data.to_vec(), mime_type, file_name)
            },
            Self::Uri { uri, mime_type, config } => ExtractInput {
                kind: ExtractInputKind::Uri,
                uri: Some(uri),
                mime_type,
                config,
                ..Default::default()
            },
        }
    }

    fn config(&self) -> Option<&crate::core::config::FileExtractionConfig> {
        match self {
            Self::Bytes { config, .. } | Self::Uri { config, .. } => config.as_ref(),
        }
    }
}

#[derive(Debug)]
pub(crate) struct UnifiedExtractRequest {
    inputs: Vec<ApiExtractInput>,
    config: Option<crate::core::config::ExtractionConfig>,
    output_format: Option<crate::core::config::OutputFormat>,
    pdf_passwords: Vec<String>,
    use_toon: bool,
}

impl UnifiedExtractRequest {
    fn validate_caller_config(&self) -> Result<(), ApiError> {
        if let Some(config) = &self.config {
            validate_serializable_caller_config(config)?;
        }
        for input in &self.inputs {
            if let Some(config) = input.config() {
                validate_serializable_caller_config(config)?;
            }
        }
        Ok(())
    }
}

fn validate_serializable_caller_config(config: &impl serde::Serialize) -> Result<(), ApiError> {
    let value = serde_json::to_value(config).map_err(|_| {
        ApiError::validation(crate::error::XbergError::validation(
            "Failed to validate caller extraction configuration",
        ))
    })?;
    crate::core::config::request_security::validate_caller_extraction_config(&value)
        .map_err(|message| ApiError::validation(crate::error::XbergError::validation(message)))
}

#[derive(Debug, serde::Deserialize)]
struct JsonUnifiedExtractRequest {
    inputs: Vec<JsonExtractInput>,
    #[serde(default)]
    config: Option<crate::core::config::ExtractionConfig>,
    #[serde(default)]
    format: Option<String>,
}

#[derive(Debug, serde::Deserialize)]
#[serde(untagged)]
enum JsonExtractInput {
    Uri(String),
    // Boxed: the object form is ~6 KB, so an unboxed variant made every `JsonExtractInput`
    // that size even for the bare-URI case. Private to this module, so this is not an API
    // change.
    Object(Box<JsonExtractInputObject>),
}

#[derive(Debug, serde::Deserialize)]
struct JsonExtractInputObject {
    #[serde(default)]
    kind: Option<String>,
    #[serde(default, rename = "type")]
    input_type: Option<String>,
    #[serde(default)]
    uri: Option<String>,
    #[serde(default)]
    url: Option<String>,
    #[serde(default)]
    path: Option<String>,
    #[serde(default)]
    data: Option<String>,
    #[serde(default)]
    text: Option<String>,
    #[serde(default)]
    mime_type: Option<String>,
    #[serde(default)]
    filename: Option<String>,
    /// Per-input extraction overrides, merged over the request-level config.
    ///
    /// Threaded into [`ExtractInput::config`], which the engine merges via
    /// `ExtractionConfig::with_file_overrides`. Without this the HTTP API could
    /// only ever apply one config to every input in a batch (#247).
    #[serde(default)]
    config: Option<crate::core::config::FileExtractionConfig>,
}

impl<S> FromRequest<S> for UnifiedExtractRequest
where
    S: Send + Sync,
{
    type Rejection = ApiError;

    async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> {
        let content_type = req
            .headers()
            .get(header::CONTENT_TYPE)
            .and_then(|value| value.to_str().ok())
            .unwrap_or("");

        let request = if content_type.starts_with("multipart/form-data") {
            parse_multipart_extract_request(req, state).await
        } else if is_json_content_type(content_type) {
            parse_json_extract_request(req).await
        } else {
            Err(ApiError::new(
                StatusCode::UNSUPPORTED_MEDIA_TYPE,
                crate::error::XbergError::validation(
                    "Expected Content-Type application/json or multipart/form-data for extraction",
                ),
            ))
        }?;
        request.validate_caller_config()?;
        Ok(request)
    }
}

fn is_json_content_type(content_type: &str) -> bool {
    let lower = content_type.to_ascii_lowercase();
    lower.starts_with("application/json") || lower.contains("+json")
}

async fn parse_json_extract_request(req: Request) -> Result<UnifiedExtractRequest, ApiError> {
    let bytes = to_bytes(req.into_body(), usize::MAX).await.map_err(|_| {
        ApiError::new(
            StatusCode::BAD_REQUEST,
            crate::error::XbergError::Other("Failed to read request body".to_string()),
        )
    })?;
    let body: JsonUnifiedExtractRequest = serde_json::from_slice(&bytes).map_err(|e| {
        ApiError::new(
            StatusCode::BAD_REQUEST,
            crate::error::XbergError::validation(format!("Invalid extraction request JSON: {e}")),
        )
    })?;

    let inputs = body
        .inputs
        .into_iter()
        .map(json_input_to_api_input)
        .collect::<Result<Vec<_>, _>>()?;

    Ok(UnifiedExtractRequest {
        inputs,
        config: body.config,
        output_format: None,
        pdf_passwords: Vec::new(),
        use_toon: body
            .format
            .as_deref()
            .is_some_and(|format| format.eq_ignore_ascii_case("toon")),
    })
}

async fn parse_multipart_extract_request<S>(req: Request, state: &S) -> Result<UnifiedExtractRequest, ApiError>
where
    S: Send + Sync,
{
    let mut multipart = Multipart::from_request(req, state)
        .await
        .map_err(|rejection| ApiError {
            status: StatusCode::BAD_REQUEST,
            body: super::types::ErrorResponse {
                error_type: "MultipartError".to_string(),
                message: rejection.body_text(),
                traceback: None,
                status_code: StatusCode::BAD_REQUEST.as_u16(),
            },
        })?;

    let mut inputs = Vec::new();
    let mut config: Option<crate::core::config::ExtractionConfig> = None;
    let mut output_format = None;
    let mut pdf_passwords = Vec::new();
    let mut use_toon = false;

    while let Some(field) = multipart
        .next_field()
        .await
        .map_err(|e| ApiError::validation(crate::error::XbergError::validation(e.to_string())))?
    {
        let field_name = field.name().unwrap_or("").to_string();

        match field_name.as_str() {
            "file" | "files" => {
                let file_name = field.file_name().map(|s| s.to_string());
                let content_type = field.content_type().map(|s| s.to_string());
                let data = field
                    .bytes()
                    .await
                    .map_err(|e| ApiError::validation(crate::error::XbergError::validation(e.to_string())))?;
                let mime_type = resolve_multipart_mime(content_type);

                inputs.push(ApiExtractInput::Bytes {
                    data,
                    mime_type,
                    file_name,
                    // Multipart file parts carry no per-part config; per-input
                    // overrides are expressed through the JSON `inputs` field.
                    config: None,
                });
            }
            "urls" => {
                let urls = field
                    .text()
                    .await
                    .map_err(|e| ApiError::validation(crate::error::XbergError::validation(e.to_string())))?;
                inputs.extend(parse_urls_field(&urls)?);
            }
            "inputs" => {
                let raw_inputs = field
                    .text()
                    .await
                    .map_err(|e| ApiError::validation(crate::error::XbergError::validation(e.to_string())))?;
                inputs.extend(parse_inputs_field(&raw_inputs)?);
            }
            "config" => {
                let config_str = field
                    .text()
                    .await
                    .map_err(|e| ApiError::validation(crate::error::XbergError::validation(e.to_string())))?;

                config = Some(serde_json::from_str(&config_str).map_err(|e| {
                    ApiError::validation(crate::error::XbergError::validation(format!(
                        "Invalid extraction configuration: {}",
                        e
                    )))
                })?);
            }
            "output_format" => {
                let format_str = field
                    .text()
                    .await
                    .map_err(|e| ApiError::validation(crate::error::XbergError::validation(e.to_string())))?;
                output_format = Some(parse_output_format(&format_str)?);
            }
            "pdf_password" => {
                let pwd = field
                    .text()
                    .await
                    .map_err(|e| ApiError::validation(crate::error::XbergError::validation(e.to_string())))?;
                pdf_passwords.push(pwd);
            }
            "format" => {
                let format_str = field
                    .text()
                    .await
                    .map_err(|e| ApiError::validation(crate::error::XbergError::validation(e.to_string())))?;
                if format_str.eq_ignore_ascii_case("toon") {
                    use_toon = true;
                }
            }
            unknown => return Err(unknown_multipart_field_error(unknown)),
        }
    }

    Ok(UnifiedExtractRequest {
        inputs,
        config,
        output_format,
        pdf_passwords,
        use_toon,
    })
}

fn resolve_multipart_mime(content_type: Option<String>) -> String {
    content_type.unwrap_or_else(|| crate::core::mime::OCTET_STREAM_MIME_TYPE.to_string())
}

fn parse_urls_field(raw: &str) -> Result<Vec<ApiExtractInput>, ApiError> {
    let value: serde_json::Value = serde_json::from_str(raw).map_err(|e| {
        ApiError::validation(crate::error::XbergError::validation(format!(
            "Invalid urls field JSON: {e}"
        )))
    })?;

    match value {
        serde_json::Value::String(uri) => Ok(vec![ApiExtractInput::Uri {
            uri,
            mime_type: None,
            config: None,
        }]),
        serde_json::Value::Array(values) => values
            .into_iter()
            .map(|value| match value {
                serde_json::Value::String(uri) => Ok(ApiExtractInput::Uri {
                    uri,
                    mime_type: None,
                    config: None,
                }),
                _ => Err(ApiError::validation(crate::error::XbergError::validation(
                    "urls field must be a JSON string or array of strings",
                ))),
            })
            .collect(),
        _ => Err(ApiError::validation(crate::error::XbergError::validation(
            "urls field must be a JSON string or array of strings",
        ))),
    }
}

fn parse_inputs_field(raw: &str) -> Result<Vec<ApiExtractInput>, ApiError> {
    let value: serde_json::Value = serde_json::from_str(raw).map_err(|e| {
        ApiError::validation(crate::error::XbergError::validation(format!(
            "Invalid inputs field JSON: {e}"
        )))
    })?;
    let inputs: Vec<JsonExtractInput> = serde_json::from_value(match value {
        serde_json::Value::Array(_) => value,
        other => serde_json::Value::Array(vec![other]),
    })
    .map_err(|e| {
        ApiError::validation(crate::error::XbergError::validation(format!(
            "Invalid inputs field shape: {e}"
        )))
    })?;

    inputs.into_iter().map(json_input_to_api_input).collect()
}

fn json_input_to_api_input(input: JsonExtractInput) -> Result<ApiExtractInput, ApiError> {
    match input {
        JsonExtractInput::Uri(uri) => Ok(ApiExtractInput::Uri {
            uri,
            mime_type: None,
            config: None,
        }),
        JsonExtractInput::Object(object) => object_to_api_input(*object),
    }
}

fn object_to_api_input(object: JsonExtractInputObject) -> Result<ApiExtractInput, ApiError> {
    let kind = object.kind.or(object.input_type).map(|kind| kind.to_ascii_lowercase());

    if matches!(kind.as_deref(), Some("bytes") | Some("base64")) || object.data.is_some() {
        let data = object.data.ok_or_else(|| {
            ApiError::validation(crate::error::XbergError::validation(
                "bytes input requires a base64 data field",
            ))
        })?;
        let decoded = STANDARD.decode(data).map_err(|e| {
            ApiError::validation(crate::error::XbergError::validation(format!(
                "Invalid base64 data field: {e}"
            )))
        })?;
        return Ok(ApiExtractInput::Bytes {
            data: Bytes::from(decoded),
            mime_type: object
                .mime_type
                .unwrap_or_else(|| crate::core::mime::OCTET_STREAM_MIME_TYPE.to_string()),
            file_name: object.filename,
            config: object.config,
        });
    }

    if matches!(kind.as_deref(), Some("text")) || object.text.is_some() {
        let text = object.text.ok_or_else(|| {
            ApiError::validation(crate::error::XbergError::validation("text input requires a text field"))
        })?;
        return Ok(ApiExtractInput::Bytes {
            data: Bytes::from(text),
            mime_type: object.mime_type.unwrap_or_else(|| "text/plain".to_string()),
            file_name: object.filename,
            config: object.config,
        });
    }

    if let Some(uri) = object.uri.or(object.url).or(object.path) {
        return Ok(ApiExtractInput::Uri {
            uri,
            mime_type: object.mime_type,
            config: object.config,
        });
    }

    Err(ApiError::validation(crate::error::XbergError::validation(
        "input must include one of uri, url, path, data, or text",
    )))
}

fn parse_output_format(format_str: &str) -> Result<crate::core::config::OutputFormat, ApiError> {
    let output_format = match format_str.to_lowercase().as_str() {
        "plain" => crate::core::config::OutputFormat::Plain,
        "markdown" => crate::core::config::OutputFormat::Markdown,
        "djot" => crate::core::config::OutputFormat::Djot,
        "html" => crate::core::config::OutputFormat::Html,
        "json" => crate::core::config::OutputFormat::Json,
        "doctags" => crate::core::config::OutputFormat::DocTags,
        _ => {
            return Err(ApiError::validation(crate::error::XbergError::validation(format!(
                "Invalid output_format: '{}'. Valid values: 'plain', 'markdown', 'djot', 'html', 'json', 'doctags'",
                format_str
            ))));
        }
    };
    Ok(output_format)
}

fn apply_multipart_config_fields(
    config: &mut crate::core::config::ExtractionConfig,
    output_format: Option<crate::core::config::OutputFormat>,
    pdf_passwords: Vec<String>,
) {
    if let Some(output_format) = output_format {
        config.output_format = output_format;
    }
    #[cfg(feature = "pdf")]
    {
        if !pdf_passwords.is_empty() {
            let pdf_opts = config.pdf_options.get_or_insert_with(Default::default);
            pdf_opts.passwords.get_or_insert_with(Vec::new).extend(pdf_passwords);
        }
    }
    #[cfg(not(feature = "pdf"))]
    let _ = pdf_passwords;
}

/// Health check endpoint handler.
///
/// GET /health
#[utoipa::path(
    get,
    path = "/health",
    tag = "health",
    responses(
        (status = 200, description = "Service is healthy", body = HealthResponse),
    )
)]
#[cfg_attr(feature = "otel", tracing::instrument(name = "api.health"))]
pub(crate) async fn health_handler() -> Json<HealthResponse> {
    let plugin_status = crate::plugins::startup_validation::PluginHealthStatus::check();

    Json(HealthResponse {
        status: "healthy".to_string(),
        version: env!("CARGO_PKG_VERSION").to_string(),
        plugins: Some(super::types::PluginStatus {
            ocr_backends_count: plugin_status.ocr_backends_count,
            ocr_backends: plugin_status.ocr_backends,
            extractors_count: plugin_status.extractors_count,
            post_processors_count: plugin_status.post_processors_count,
        }),
    })
}

/// Server info endpoint handler.
///
/// GET /info
#[utoipa::path(
    get,
    path = "/info",
    tag = "health",
    responses(
        (status = 200, description = "Server information", body = InfoResponse),
    )
)]
#[cfg_attr(feature = "otel", tracing::instrument(name = "api.info"))]
pub(crate) async fn info_handler() -> Json<InfoResponse> {
    Json(InfoResponse {
        version: env!("CARGO_PKG_VERSION").to_string(),
        rust_backend: true,
    })
}

/// Prometheus metrics endpoint handler.
///
/// GET /metrics
///
/// Returns the current OTel extraction metrics in the Prometheus text exposition format
/// (`text/plain; version=0.0.4`). Requires the `prometheus` feature.
///
/// The `SdkMeterProvider` backing these metrics is installed by
/// [`crate::telemetry::init_prometheus`] before this router's extraction service is built
/// (see `create_router_with_limits_and_server_config`), so every extraction handled by this
/// router is reflected here. If a caller embeds a custom extraction pipeline instead of this
/// router, they must call `init_prometheus()` themselves before their first extraction, or
/// this endpoint scrapes an empty registry.
#[cfg(feature = "prometheus")]
#[utoipa::path(
    get,
    path = "/metrics",
    tag = "health",
    responses(
        (status = 200, description = "Prometheus text-format extraction metrics", content_type = "text/plain"),
    )
)]
#[cfg_attr(feature = "otel", tracing::instrument(name = "api.metrics", skip(state)))]
pub(crate) async fn metrics_handler(
    State(state): State<ApiState>,
) -> Result<axum::response::Response<axum::body::Body>, ApiError> {
    use prometheus::Encoder;

    let metric_families = state.prometheus_registry.gather();
    let encoder = prometheus::TextEncoder::new();
    let mut buffer = Vec::new();
    encoder.encode(&metric_families, &mut buffer).map_err(|e| {
        ApiError::internal(crate::error::XbergError::Other(format!(
            "Failed to encode Prometheus metrics: {}",
            e
        )))
    })?;

    Ok(axum::response::Response::builder()
        .header(axum::http::header::CONTENT_TYPE, prometheus::TEXT_FORMAT)
        .body(axum::body::Body::from(buffer))
        .expect("valid response"))
}

/// Check whether TOON wire format was requested via the `Accept` header.
fn wants_toon(headers: &HeaderMap) -> bool {
    headers
        .get(axum::http::header::ACCEPT)
        .and_then(|v| v.to_str().ok())
        .is_some_and(|v| v.contains("application/toon"))
}

/// Serialize extraction results as a TOON response.
fn toon_response(results: &ExtractionResult) -> Result<axum::response::Response<axum::body::Body>, ApiError> {
    let body = serde_toon::to_string(results).map_err(|e| {
        ApiError::internal(crate::error::XbergError::Other(format!(
            "Failed to serialize response to TOON: {}",
            e
        )))
    })?;
    Ok(axum::response::Response::builder()
        .header(axum::http::header::CONTENT_TYPE, "application/toon")
        .body(axum::body::Body::from(body))
        .expect("valid response"))
}

/// Extract endpoint handler.
///
/// POST /extract
///
/// Accepts multipart form data with:
/// - `files`: One or more files to extract
/// - `config` (optional): JSON extraction configuration (overrides server defaults)
/// - `format` (optional): Wire format for the response (`json` or `toon`, default: `json`).
///   Alternatively, set the `Accept: application/toon` header.
///
/// Returns an `ExtractionResult` envelope with extraction results and summary counts.
///
/// # Size Limits
///
/// Request body size limits are enforced at the router layer via `DefaultBodyLimit` and `RequestBodyLimitLayer`.
/// Default limits:
/// - Total request body: 100 MB (all files + form data combined)
/// - Individual multipart fields: 100 MB (controlled by Axum's `DefaultBodyLimit`)
///
/// Limits can be configured via environment variables or programmatically when creating the router.
/// If a request exceeds the size limit, it will be rejected with HTTP 413 (Payload Too Large).
///
/// The server's default config (loaded from xberg.toml/yaml/json via discovery)
/// is used as the base, and any per-request config overrides those defaults.
#[utoipa::path(
    post,
    path = "/extract",
    tag = "extraction",
    request_body(content_type = "multipart/form-data"),
    responses(
        (status = 200, description = "Extraction successful", body = crate::core::config::ExtractionResult),
        (status = 400, description = "Bad request", body = crate::api::types::ErrorResponse),
        (status = 413, description = "Payload too large", body = crate::api::types::ErrorResponse),
        (status = 415, description = "Unsupported Content-Type", body = crate::api::types::ErrorResponse),
        (status = 500, description = "Internal server error", body = crate::api::types::ErrorResponse),
    )
)]
#[cfg_attr(
    feature = "otel",
    tracing::instrument(
        name = "api.extract",
        skip(state, headers, request),
        fields(files_count = tracing::field::Empty)
    )
)]
pub(crate) async fn extract_handler(
    State(state): State<ApiState>,
    headers: HeaderMap,
    request: UnifiedExtractRequest,
) -> Result<axum::response::Response<axum::body::Body>, ApiError> {
    let use_toon = wants_toon(&headers) || request.use_toon;

    #[cfg(feature = "otel")]
    tracing::Span::current().record("files_count", request.inputs.len());

    let mut final_config = request.config.unwrap_or_else(|| (*state.default_config).clone());
    apply_multipart_config_fields(&mut final_config, request.output_format, request.pdf_passwords);
    enforce_and_apply_api_uri_policy(&request.inputs, &mut final_config, api_allows_local_uri_inputs())?;
    let results = extract_unified_inputs(request.inputs, final_config).await?;

    if use_toon {
        toon_response(&results)
    } else {
        Ok(Json(results).into_response())
    }
}

async fn extract_unified_inputs(
    inputs: Vec<ApiExtractInput>,
    config: crate::core::config::ExtractionConfig,
) -> Result<ExtractionResult, ApiError> {
    if inputs.is_empty() {
        return Err(ApiError::validation(crate::error::XbergError::validation(
            "No inputs provided for extraction",
        )));
    }

    let inputs = inputs.into_iter().map(ApiExtractInput::into_core_input).collect();
    crate::extract_batch(inputs, &config).await.map_err(ApiError::from)
}

fn enforce_and_apply_api_uri_policy(
    inputs: &[ApiExtractInput],
    config: &mut crate::core::config::ExtractionConfig,
    allow_local: bool,
) -> Result<(), ApiError> {
    if allow_local {
        return Ok(());
    }
    for input in inputs {
        if let ApiExtractInput::Uri { uri, .. } = input
            && !is_remote_uri(uri)
        {
            return Err(ApiError::validation(crate::error::XbergError::validation(
                "Local path and file:// URI extraction are disabled for the HTTP API. Set XBERG_API_ALLOW_LOCAL_URI_INPUTS=1 to enable server-side local URI access.",
            )));
        }
    }
    config.url.allow_local_file_inputs = false;
    config.url.allow_file_uris = false;
    Ok(())
}

fn api_allows_local_uri_inputs() -> bool {
    std::env::var("XBERG_API_ALLOW_LOCAL_URI_INPUTS")
        .map(|value| matches!(value.to_ascii_lowercase().as_str(), "1" | "true" | "yes"))
        .unwrap_or(false)
}

fn is_remote_uri(uri: &str) -> bool {
    uri.starts_with("http://") || uri.starts_with("https://")
}

/// Formats endpoint handler.
///
/// GET /formats
///
/// Returns all supported file extensions and their corresponding MIME types.
#[utoipa::path(
    get,
    path = "/formats",
    tag = "health",
    responses(
        (status = 200, description = "Supported formats", body = Vec<crate::SupportedFormat>),
    )
)]
#[cfg_attr(feature = "otel", tracing::instrument(name = "api.formats"))]
pub(crate) async fn formats_handler() -> Json<Vec<crate::SupportedFormat>> {
    Json(crate::core::mime::list_supported_formats())
}

/// Cache stats endpoint handler.
///
/// GET /cache/stats
///
/// # Errors
///
/// Returns `ApiError::Internal` if:
/// - Current directory cannot be determined
/// - Cache directory path contains non-UTF8 characters
/// - Cache metadata retrieval fails
#[utoipa::path(
    get,
    path = "/cache/stats",
    tag = "cache",
    responses(
        (status = 200, description = "Cache statistics", body = CacheStatsResponse),
        (status = 500, description = "Internal server error", body = crate::api::types::ErrorResponse),
    )
)]
#[cfg_attr(feature = "otel", tracing::instrument(name = "api.cache_stats"))]
pub(crate) async fn cache_stats_handler() -> Result<Json<CacheStatsResponse>, ApiError> {
    let cache_dir = crate::cache_dir::resolve_cache_base();

    let cache_dir_str = cache_dir.to_str().ok_or_else(|| {
        ApiError::internal(crate::error::XbergError::Other(format!(
            "Cache directory path contains non-UTF8 characters: {}",
            cache_dir.display()
        )))
    })?;

    let stats = cache::get_cache_metadata(cache_dir_str).map_err(ApiError::internal)?;

    Ok(Json(CacheStatsResponse {
        directory: cache_dir.to_string_lossy().to_string(),
        total_files: stats.total_files,
        total_size_mb: stats.total_size_mb,
        available_space_mb: stats.available_space_mb,
        oldest_file_age_days: stats.oldest_file_age_days,
        newest_file_age_days: stats.newest_file_age_days,
    }))
}

/// Clear the Xberg-managed cache. Shared Hugging Face Hub cache files are excluded.
///
/// DELETE /cache/clear
///
/// # Errors
///
/// Returns `ApiError::Internal` if:
/// - Current directory cannot be determined
/// - Cache directory path contains non-UTF8 characters
/// - Cache clearing operation fails
#[utoipa::path(
    delete,
    path = "/cache/clear",
    tag = "cache",
    responses(
        (status = 200, description = "Xberg-managed cache cleared; shared Hugging Face cache excluded", body = CacheClearResponse),
        (status = 500, description = "Internal server error", body = crate::api::types::ErrorResponse),
    )
)]
#[cfg_attr(feature = "otel", tracing::instrument(name = "api.cache_clear"))]
pub(crate) async fn cache_clear_handler() -> Result<Json<CacheClearResponse>, ApiError> {
    let cache_dir = crate::cache_dir::resolve_cache_base();

    let cache_dir_str = cache_dir.to_str().ok_or_else(|| {
        ApiError::internal(crate::error::XbergError::Other(format!(
            "Cache directory path contains non-UTF8 characters: {}",
            cache_dir.display()
        )))
    })?;

    let (removed_files, freed_mb) = cache::clear_cache_directory(cache_dir_str).map_err(ApiError::internal)?;

    Ok(Json(CacheClearResponse {
        directory: cache_dir.to_string_lossy().to_string(),
        removed_files,
        freed_mb,
    }))
}

/// Version endpoint handler.
///
/// GET /version
///
/// Returns the current xberg version.
#[utoipa::path(
    get,
    path = "/version",
    tag = "health",
    responses(
        (status = 200, description = "Version information", body = VersionResponse),
    )
)]
#[cfg_attr(feature = "otel", tracing::instrument(name = "api.version"))]
pub(crate) async fn version_handler() -> Json<VersionResponse> {
    Json(VersionResponse {
        version: env!("CARGO_PKG_VERSION").to_string(),
    })
}

/// MIME type detection endpoint handler.
///
/// POST /detect
///
/// Accepts multipart form data with a single file and returns its detected MIME type.
///
/// # Errors
///
/// Returns `ApiError::Validation` if no file is provided.
/// Returns `ApiError::Internal` if MIME type detection fails.
#[utoipa::path(
    post,
    path = "/detect",
    tag = "extraction",
    request_body(content_type = "multipart/form-data"),
    responses(
        (status = 200, description = "MIME type detected", body = DetectResponse),
        (status = 400, description = "Bad request - no file provided", body = crate::api::types::ErrorResponse),
        (status = 500, description = "Internal server error", body = crate::api::types::ErrorResponse),
    )
)]
#[cfg_attr(feature = "otel", tracing::instrument(name = "api.detect", skip(multipart)))]
pub(crate) async fn detect_handler(
    MultipartApi(mut multipart): MultipartApi,
) -> Result<Json<DetectResponse>, ApiError> {
    let mut file_data: Option<(Vec<u8>, Option<String>)> = None;

    while let Some(field) = multipart
        .next_field()
        .await
        .map_err(|e| ApiError::validation(crate::error::XbergError::validation(e.to_string())))?
    {
        let field_name = field.name().unwrap_or("").to_string();

        if field_name == "file" || field_name == "files" {
            let file_name = field.file_name().map(|s| s.to_string());
            let data = field
                .bytes()
                .await
                .map_err(|e| ApiError::validation(crate::error::XbergError::validation(e.to_string())))?;
            file_data = Some((data.to_vec(), file_name));
            break;
        }
    }

    let (data, file_name) = file_data.ok_or_else(|| {
        ApiError::validation(crate::error::XbergError::validation(
            "No file provided for MIME type detection. Upload a file with field name 'file' or 'files'.",
        ))
    })?;

    let mime_type = crate::core::mime::detect_mime_type_from_bytes(&data).or_else(|_| {
        if let Some(ref name) = file_name {
            crate::core::mime::detect_mime_type(name, false)
        } else {
            Err(crate::error::XbergError::Other(
                "Could not detect MIME type from file content or filename".to_string(),
            ))
        }
    })?;

    Ok(Json(DetectResponse {
        mime_type,
        filename: file_name,
    }))
}

/// Model manifest endpoint handler.
///
/// GET /cache/manifest
///
/// Returns the expected model files with checksums and sizes.
#[utoipa::path(
    get,
    path = "/cache/manifest",
    tag = "cache",
    responses(
        (status = 200, description = "Model manifest", body = ManifestResponse),
    )
)]
#[cfg_attr(feature = "otel", tracing::instrument(name = "api.cache_manifest"))]
pub(crate) async fn cache_manifest_handler() -> Json<ManifestResponse> {
    #[allow(unused_mut)]
    let mut models: Vec<ManifestEntryResponse> = Vec::new();

    #[cfg(paddle_ocr)]
    {
        models.extend(
            crate::paddle_ocr::ModelManager::manifest()
                .into_iter()
                .map(|e| ManifestEntryResponse {
                    relative_path: e.relative_path,
                    sha256: e.sha256,
                    size_bytes: e.size_bytes,
                    source_url: e.source_url,
                }),
        );
    }

    #[cfg(feature = "layout-detection")]
    {
        models.extend(
            crate::layout::LayoutModelManager::manifest()
                .into_iter()
                .map(|e| ManifestEntryResponse {
                    relative_path: e.relative_path,
                    sha256: e.sha256,
                    size_bytes: e.size_bytes,
                    source_url: e.source_url,
                }),
        );
    }

    #[cfg(feature = "ner-onnx")]
    {
        models.extend(crate::text::ner::manifest().into_iter().map(|e| ManifestEntryResponse {
            relative_path: e.relative_path,
            sha256: e.sha256,
            size_bytes: e.size_bytes,
            source_url: e.source_url,
        }));
    }

    let total_size_bytes: u64 = models.iter().map(|e| e.size_bytes).sum();
    let model_count = models.len();

    Json(ManifestResponse {
        xberg_version: env!("CARGO_PKG_VERSION").to_string(),
        total_size_bytes,
        model_count,
        models,
    })
}

/// Cache warm endpoint handler.
///
/// POST /cache/warm
///
/// Eagerly downloads required models. Hugging Face artifacts remain in the
/// standard HF cache selected by `HF_HUB_CACHE`, `HF_HOME`, or platform defaults.
/// Optionally downloads embedding models when the `embeddings` feature is enabled.
///
/// # Errors
///
/// Returns `ApiError::Internal` if model downloading fails.
/// Returns `ApiError::Validation` if an unknown embedding preset is requested
/// or a requested model-warming feature is not enabled.
#[utoipa::path(
    post,
    path = "/cache/warm",
    tag = "cache",
    request_body = WarmRequest,
    responses(
        (status = 200, description = "Models warmed", body = WarmResponse),
        (status = 400, description = "Bad request - unknown or empty model name, or requested warmer feature is unavailable", body = crate::api::types::ErrorResponse),
        (status = 415, description = "Unsupported Content-Type", body = crate::api::types::ErrorResponse),
        (status = 422, description = "Unprocessable entity - invalid JSON body", body = crate::api::types::ErrorResponse),
        (status = 500, description = "Internal server error", body = crate::api::types::ErrorResponse),
        (status = 502, description = "Bad gateway - upstream model download failed", body = crate::api::types::ErrorResponse),
    )
)]
#[cfg_attr(feature = "otel", tracing::instrument(name = "api.cache_warm", skip(request)))]
pub(crate) async fn cache_warm_handler(JsonApi(request): JsonApi<WarmRequest>) -> Result<Json<WarmResponse>, ApiError> {
    if let Some(ref name) = request.embedding_model
        && name.trim().is_empty()
    {
        return Err(ApiError::validation(crate::error::XbergError::validation(
            "Field 'embedding_model' must not be empty. Omit the field or provide a valid preset name.",
        )));
    }
    if let Some(ref name) = request.ner_model
        && name.trim().is_empty()
    {
        return Err(ApiError::validation(crate::error::XbergError::validation(
            "Field 'ner_model' must not be empty. Omit the field or provide a valid model name.",
        )));
    }

    let cache_base = resolve_cache_base();

    #[allow(unused_mut)]
    let mut downloaded: Vec<String> = Vec::new();
    #[allow(unused_mut)]
    let mut already_cached: Vec<String> = Vec::new();

    #[cfg(paddle_ocr)]
    {
        let paddle_dir = cache_base.join("paddle-ocr");
        let manager = crate::paddle_ocr::ModelManager::new(paddle_dir);

        manager.ensure_all_models().map_err(ApiError::bad_gateway)?;
        downloaded.push("paddle-ocr v2 (server+mobile det, cls, doc_ori, unified+per-script rec)".to_string());
    }

    #[cfg(feature = "layout-detection")]
    {
        let layout_dir = cache_base.join("layout");
        let manager = crate::layout::LayoutModelManager::new(Some(layout_dir));

        let was_cached = manager.is_rtdetr_cached() && manager.is_tatr_cached();

        if was_cached {
            already_cached.push("layout (rtdetr, tatr)".to_string());
        } else {
            manager.ensure_all_models().map_err(|e| {
                ApiError::bad_gateway(crate::error::XbergError::Other(format!(
                    "Failed to download layout models: {}",
                    e
                )))
            })?;
            downloaded.push("layout (rtdetr, tatr)".to_string());
        }
    }

    #[cfg(feature = "embeddings")]
    {
        let embeddings_dir = cache_base.join("embeddings");
        let presets_to_warm: Vec<crate::EmbeddingPreset> = if request.all_embeddings {
            crate::embeddings::EMBEDDING_PRESETS.clone()
        } else if let Some(ref name) = request.embedding_model {
            match crate::embeddings::get_preset(name) {
                Some(preset) => vec![preset],
                None => {
                    let available: Vec<String> = crate::embeddings::list_presets();
                    return Err(ApiError::validation(crate::error::XbergError::validation(format!(
                        "Unknown embedding preset '{}'. Available: {}",
                        name,
                        available.join(", ")
                    ))));
                }
            }
        } else {
            vec![]
        };

        for preset in &presets_to_warm {
            let label = format!("embedding ({})", preset.name);
            crate::embeddings::warm_model(
                &crate::core::config::EmbeddingModelType::Preset {
                    name: preset.name.clone(),
                },
                Some(embeddings_dir.clone()),
            )
            .map_err(|e| {
                ApiError::bad_gateway(crate::error::XbergError::Other(format!(
                    "Failed to download embedding model '{}': {}",
                    preset.name, e
                )))
            })?;
            downloaded.push(label);
        }
    }

    #[cfg(not(feature = "embeddings"))]
    {
        if request.all_embeddings || request.embedding_model.is_some() {
            return Err(ApiError::validation(crate::error::XbergError::validation(
                "Embedding model warming requires the 'embeddings' feature to be enabled",
            )));
        }
    }

    #[cfg(feature = "ner-onnx")]
    {
        if request.ner || request.all_ner_models || request.ner_model.is_some() {
            let models_to_warm: Vec<String> = if request.all_ner_models {
                crate::text::ner::known_models().iter().map(|s| s.to_string()).collect()
            } else if let Some(ref name) = request.ner_model {
                vec![name.clone()]
            } else {
                vec![crate::text::ner::default_model_name().to_string()]
            };

            for model in &models_to_warm {
                let path = crate::text::ner::download_model(model, None).map_err(|e| {
                    ApiError::bad_gateway(crate::error::XbergError::Other(format!(
                        "Failed to download NER model '{}': {}",
                        model, e
                    )))
                })?;
                downloaded.push(format!(
                    "ner gliner ({model}) -> {} (Hugging Face cache)",
                    path.display()
                ));
            }
        }
    }

    #[cfg(not(feature = "ner-onnx"))]
    {
        if request.ner || request.all_ner_models || request.ner_model.is_some() {
            return Err(ApiError::validation(crate::error::XbergError::MissingDependency(
                "NER model warming requires the 'ner-onnx' feature to be enabled".to_string(),
            )));
        }
    }

    Ok(Json(WarmResponse {
        cache_dir: cache_base.to_string_lossy().to_string(),
        downloaded,
        already_cached,
    }))
}

/// Resolve the cache base directory.
fn resolve_cache_base() -> std::path::PathBuf {
    crate::cache_dir::resolve_cache_base()
}

/// Submit an async extraction job.
///
/// POST /extract-async
///
/// Accepts multipart form data with:
/// - `files`: One or more files to extract
/// - `config` (optional): JSON extraction configuration
///
/// Returns immediately with a job ID. Poll `GET /jobs/{job_id}` for status.
///
/// # Size Limits
///
/// Request body size limits are enforced at the router layer via `DefaultBodyLimit` and `RequestBodyLimitLayer`.
/// Default limits:
/// - Total request body: 100 MB (all files + form data combined)
/// - Individual multipart fields: 100 MB (controlled by Axum's `DefaultBodyLimit`)
///
/// Limits can be configured via environment variables or programmatically when creating the router.
/// If a request exceeds the size limit, it will be rejected with HTTP 413 (Payload Too Large).
#[cfg(feature = "api")]
#[utoipa::path(
    post,
    path = "/extract-async",
    tag = "extraction",
    request_body(content_type = "multipart/form-data"),
    responses(
        (status = 202, description = "Job accepted", body = AsyncJobResponse),
        (status = 400, description = "Bad request", body = crate::api::types::ErrorResponse),
        (status = 413, description = "Payload too large", body = crate::api::types::ErrorResponse),
        (status = 415, description = "Unsupported Content-Type", body = crate::api::types::ErrorResponse),
        // Returned below when MAX_ACTIVE_JOBS is reached. Declared for the same reason as
        // 415: an undeclared status that the handler can actually return is a contract
        // violation, and the API conformance suite fails on it. ~keep
        (status = 429, description = "Too many active jobs", body = crate::api::types::ErrorResponse),
    )
)]
pub(crate) async fn extract_async_handler(
    State(state): State<ApiState>,
    request: UnifiedExtractRequest,
) -> Result<axum::response::Response, ApiError> {
    if request.inputs.is_empty() {
        return Err(ApiError::validation(crate::error::XbergError::validation(
            "No inputs provided",
        )));
    }

    if state.job_store.active_count() >= super::jobs::MAX_ACTIVE_JOBS {
        return Err(ApiError::new(
            axum::http::StatusCode::TOO_MANY_REQUESTS,
            crate::error::XbergError::Other("too many concurrent jobs; try again later".into()),
        ));
    }

    let job_id = state.job_store.create_job();
    let mut effective_config = request.config.unwrap_or_else(|| (*state.default_config).clone());
    apply_multipart_config_fields(&mut effective_config, request.output_format, request.pdf_passwords);
    enforce_and_apply_api_uri_policy(&request.inputs, &mut effective_config, api_allows_local_uri_inputs())?;
    effective_config.cancel_token = state.job_store.cancellation_token(&job_id);
    let inputs = request.inputs;

    let job_store = Arc::clone(&state.job_store);
    let job_id_bg = job_id.clone();

    tokio::spawn(async move {
        let store = job_store;
        let jid = job_id_bg;

        store.set_running(&jid, super::jobs::now_rfc3339());

        let timeout_secs = effective_config.extraction_timeout_secs.unwrap_or(300);
        let timeout_dur = std::time::Duration::from_secs(timeout_secs);

        let extraction_fut = async {
            let results = extract_unified_inputs(inputs, effective_config)
                .await
                .map_err(|e| e.body.message)?;
            serde_json::to_value(&results).map_err(|e| format!("failed to serialize results: {e}"))
        };

        match tokio::time::timeout(timeout_dur, extraction_fut).await {
            Ok(Ok(value)) => store.complete(&jid, value, super::jobs::now_rfc3339()),
            Ok(Err(e)) => store.fail(&jid, e, super::jobs::now_rfc3339()),
            Err(_elapsed) => store.fail(
                &jid,
                format!("extraction timed out after {}s", timeout_secs),
                super::jobs::now_rfc3339(),
            ),
        }
    });

    Ok((
        axum::http::StatusCode::ACCEPTED,
        axum::Json(AsyncJobResponse { job_id }),
    )
        .into_response())
}

/// Poll the status of an async extraction job.
///
/// GET /jobs/{job_id}
///
/// Returns the current `JobStatus`. Once `state == completed` the `result`
/// field is populated; once `state == failed` the `error` field is populated.
/// Jobs expire after 5 minutes and return 404 once evicted.
#[cfg(feature = "api")]
#[utoipa::path(
    get,
    path = "/jobs/{job_id}",
    tag = "extraction",
    params(
        ("job_id" = String, Path, description = "Job ID returned by POST /extract-async"),
    ),
    responses(
        (status = 200, description = "Job status", body = crate::api::types::JobStatus),
        (status = 404, description = "Job not found or expired", body = crate::api::types::ErrorResponse),
    )
)]
pub(crate) async fn job_status_handler(
    State(state): State<ApiState>,
    axum::extract::Path(job_id): axum::extract::Path<String>,
) -> Result<axum::Json<JobStatusResponse>, ApiError> {
    match state.job_store.get(&job_id) {
        Some(status) => Ok(axum::Json(status)),
        None => Err(ApiError {
            status: axum::http::StatusCode::NOT_FOUND,
            body: super::types::ErrorResponse {
                error_type: "NotFoundError".to_string(),
                message: format!("Job '{}' not found or expired", job_id),
                traceback: None,
                status_code: axum::http::StatusCode::NOT_FOUND.as_u16(),
            },
        }),
    }
}

/// Cancel a pending or running async extraction job.
///
/// DELETE /jobs/{job_id}
///
/// A pending job is removed from the queue; a running job's extraction is
/// signalled to stop cooperatively at its next checkpoint. Both transition to
/// `cancelled` and return the updated `JobStatus`. A job that already reached
/// `completed`, `failed`, or `cancelled` cannot be cancelled again and returns
/// 409. Jobs expire after 5 minutes and return 404 once evicted, as with
/// `GET /jobs/{job_id}`.
#[cfg(feature = "api")]
#[utoipa::path(
    delete,
    path = "/jobs/{job_id}",
    tag = "extraction",
    params(
        ("job_id" = String, Path, description = "Job ID returned by POST /extract-async"),
    ),
    responses(
        (status = 200, description = "Job cancelled", body = crate::api::types::JobStatus),
        (status = 404, description = "Job not found or expired", body = crate::api::types::ErrorResponse),
        (status = 409, description = "Job already reached a terminal state", body = crate::api::types::ErrorResponse),
    )
)]
#[cfg_attr(
    feature = "otel",
    tracing::instrument(
        name = "api.cancel_job",
        skip(state),
        fields(job_id = %job_id, outcome = tracing::field::Empty)
    )
)]
pub(crate) async fn cancel_job_handler(
    State(state): State<ApiState>,
    axum::extract::Path(job_id): axum::extract::Path<String>,
) -> Result<axum::Json<JobStatusResponse>, ApiError> {
    let outcome = state.job_store.cancel(&job_id, super::jobs::now_rfc3339());

    #[cfg(feature = "otel")]
    tracing::Span::current().record(
        "outcome",
        match &outcome {
            super::jobs::CancelOutcome::Cancelled(_) => "cancelled",
            super::jobs::CancelOutcome::Conflict(_) => "conflict",
            super::jobs::CancelOutcome::NotFound => "not_found",
        },
    );

    match outcome {
        super::jobs::CancelOutcome::Cancelled(status) => Ok(axum::Json(status)),
        super::jobs::CancelOutcome::Conflict(status) => Err(ApiError {
            status: axum::http::StatusCode::CONFLICT,
            body: super::types::ErrorResponse {
                error_type: "ConflictError".to_string(),
                message: format!(
                    "Job '{}' already reached state '{:?}' and cannot be cancelled",
                    job_id, status.state
                ),
                traceback: None,
                status_code: axum::http::StatusCode::CONFLICT.as_u16(),
            },
        }),
        super::jobs::CancelOutcome::NotFound => Err(ApiError {
            status: axum::http::StatusCode::NOT_FOUND,
            body: super::types::ErrorResponse {
                error_type: "NotFoundError".to_string(),
                message: format!("Job '{}' not found or expired", job_id),
                traceback: None,
                status_code: axum::http::StatusCode::NOT_FOUND.as_u16(),
            },
        }),
    }
}

/// Handler for 404 Not Found errors.
///
/// Returns a JSON error response instead of the default plain text.
pub async fn not_found_handler() -> ApiError {
    ApiError::new(
        axum::http::StatusCode::NOT_FOUND,
        crate::error::XbergError::validation("The requested resource was not found"),
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use axum::{
        Router,
        body::Body,
        http::{Request, StatusCode},
        routing::{get, post},
    };
    use tower::ServiceExt;

    fn test_router() -> Router {
        let extraction_service = crate::service::ExtractionServiceBuilder::new()
            .build()
            .expect("default extraction service configuration should be valid");
        let state = ApiState {
            default_config: std::sync::Arc::new(crate::ExtractionConfig::default()),
            extraction_service: std::sync::Arc::new(std::sync::Mutex::new(extraction_service)),
            #[cfg(feature = "api")]
            job_store: std::sync::Arc::new(crate::api::jobs::JobStore::new()),
            #[cfg(feature = "prometheus")]
            prometheus_registry: crate::telemetry::init_prometheus(),
        };
        #[allow(unused_mut)]
        let mut router = Router::new()
            .route("/version", get(version_handler))
            .route("/detect", post(detect_handler))
            .route("/cache/manifest", get(cache_manifest_handler))
            .route("/cache/warm", post(cache_warm_handler));

        #[cfg(feature = "api")]
        let router = router
            .route("/extract-async", post(extract_async_handler))
            .route("/jobs/{job_id}", get(job_status_handler).delete(cancel_job_handler));

        router.with_state(state)
    }

    /// Build a `multipart/form-data` request carrying a single named text field.
    fn multipart_request_with_field(boundary: &str, field_name: &str, value: &str) -> Request<Body> {
        let body = format!(
            "--{boundary}\r\nContent-Disposition: form-data; name=\"{field_name}\"\r\n\r\n{value}\r\n--{boundary}--\r\n"
        );
        Request::builder()
            .method("POST")
            .uri("/extract")
            .header("content-type", format!("multipart/form-data; boundary={boundary}"))
            .body(Body::from(body))
            .expect("valid multipart request")
    }

    fn multipart_file_request(
        boundary: &str,
        filename: &str,
        content_type: &str,
        data: &[u8],
        config: Option<&str>,
    ) -> Request<Body> {
        let mut body = Vec::new();
        body.extend_from_slice(
            format!(
                "--{boundary}\r\nContent-Disposition: form-data; name=\"files\"; filename=\"{filename}\"\r\nContent-Type: {content_type}\r\n\r\n"
            )
            .as_bytes(),
        );
        body.extend_from_slice(data);
        body.extend_from_slice(b"\r\n");
        if let Some(config) = config {
            body.extend_from_slice(
                format!("--{boundary}\r\nContent-Disposition: form-data; name=\"config\"\r\n\r\n{config}\r\n")
                    .as_bytes(),
            );
        }
        body.extend_from_slice(format!("--{boundary}--\r\n").as_bytes());

        Request::builder()
            .method("POST")
            .uri("/extract")
            .header("content-type", format!("multipart/form-data; boundary={boundary}"))
            .body(Body::from(body))
            .expect("valid multipart request")
    }

    async fn extracted_mime_from_multipart(request: Request<Body>) -> String {
        let parsed = UnifiedExtractRequest::from_request(request, &())
            .await
            .expect("multipart extraction request must parse");
        let config = parsed.config.unwrap_or_default();
        let result = extract_unified_inputs(parsed.inputs, config)
            .await
            .expect("multipart input must extract");
        assert_eq!(result.results.len(), 1);
        result.results[0].mime_type.to_string()
    }

    #[tokio::test]
    async fn should_detect_multipart_json_content_despite_txt_filename_by_default() {
        let request = multipart_file_request(
            "prefercontentboundary",
            "report.txt",
            crate::core::mime::OCTET_STREAM_MIME_TYPE,
            br#"{"kind":"report"}"#,
            None,
        );

        assert_eq!(extracted_mime_from_multipart(request).await, "application/json");
    }

    #[tokio::test]
    async fn should_detect_multipart_json_content_despite_txt_filename_in_content_only_mode() {
        let request = multipart_file_request(
            "contentonlyboundary",
            "report.txt",
            crate::core::mime::OCTET_STREAM_MIME_TYPE,
            br#"{"kind":"report"}"#,
            Some(r#"{"mime_detection_policy":"content_only"}"#),
        );

        assert_eq!(extracted_mime_from_multipart(request).await, "application/json");
    }

    #[tokio::test]
    async fn should_keep_specific_multipart_content_type_authoritative() {
        let request = multipart_file_request(
            "explicitmimeboundary",
            "report.json",
            "text/plain",
            br#"{"kind":"report"}"#,
            Some(r#"{"mime_detection_policy":"content_only"}"#),
        );

        assert_eq!(extracted_mime_from_multipart(request).await, "text/plain");
    }

    #[test]
    fn should_parse_json_multipart_output_format() {
        assert_eq!(
            parse_output_format("json").expect("json is a built-in output format"),
            crate::core::config::OutputFormat::Json
        );
    }

    #[test]
    fn should_parse_doctags_multipart_output_format() {
        assert_eq!(
            parse_output_format("doctags").expect("doctags is a built-in output format"),
            crate::core::config::OutputFormat::DocTags
        );
    }

    #[test]
    fn should_reject_unknown_multipart_output_format() {
        let error =
            parse_output_format("registered-later").expect_err("multipart output formats must be built-in names");

        assert_eq!(error.status, StatusCode::BAD_REQUEST);
        assert_eq!(error.body.status_code, 400);
        assert_eq!(error.body.error_type, "ValidationError");
        assert_eq!(
            error.body.message,
            concat!(
                "Validation error: Invalid output_format: 'registered-later'. Valid values: ",
                "'plain', 'markdown', 'djot', 'html', 'json', 'doctags'"
            )
        );
    }

    /// An unknown multipart field must be rejected, not silently dropped (#248).
    ///
    /// Before the fix the catch-all match arm was `_ => {}`, so a misspelled
    /// field name (`configuration` instead of `config`) was discarded and the
    /// request quietly succeeded against the server defaults — the caller's
    /// settings vanished with no signal at all.
    #[tokio::test]
    async fn should_reject_unknown_multipart_field_naming_the_offending_field() {
        let request = multipart_request_with_field("unknownfieldboundary", "configuration", "{}");

        let error = UnifiedExtractRequest::from_request(request, &())
            .await
            .expect_err("an unknown multipart field must be rejected");

        assert_eq!(error.status, StatusCode::BAD_REQUEST);
        assert_eq!(error.body.status_code, 400);
        assert_eq!(error.body.error_type, "ValidationError");
        assert_eq!(
            error.body.message,
            "Validation error: Unknown multipart field 'configuration'. \
             Accepted fields: file, files, urls, inputs, config, output_format, pdf_password, format"
        );
    }

    /// Every allowlisted multipart field name must still be accepted (#248).
    ///
    /// Guards the rejection above against over-reach — a stricter boundary is
    /// only correct if it does not break the documented field names.
    #[tokio::test]
    async fn should_accept_every_allowlisted_multipart_field_name() {
        for field_name in ACCEPTED_EXTRACT_MULTIPART_FIELDS {
            // Give each field a payload its own parser accepts.
            let value = match field_name {
                "urls" | "inputs" => "[]",
                "config" => "{}",
                "output_format" => "markdown",
                _ => "x",
            };
            let request = multipart_request_with_field("allowlistboundary", field_name, value);

            // Assert on the *name* check specifically: a payload-level complaint
            // would be a different (and legitimate) error, but no allowlisted
            // name may ever be rejected as unknown.
            if let Err(error) = UnifiedExtractRequest::from_request(request, &()).await {
                assert!(
                    !error.body.message.contains("Unknown multipart field"),
                    "allowlisted field '{field_name}' was rejected as unknown: {}",
                    error.body.message
                );
            }
        }
    }

    /// A per-input `config` must reach that input's `ExtractInput::config` (#247).
    ///
    /// The engine merges `ExtractInput::config` over the request config via
    /// `ExtractionConfig::with_file_overrides`, but the HTTP layer never populated
    /// it, so one config was forced onto every input in a batch. The second input
    /// asserts the override stays scoped to the input that declared it.
    #[tokio::test]
    async fn should_thread_per_input_config_override_into_core_input() {
        let body = serde_json::json!({
            "inputs": [
                {"uri": "https://example.com/scanned.pdf", "config": {"force_ocr": true}},
                {"uri": "https://example.com/plain.pdf"}
            ]
        });

        let request = Request::builder()
            .method("POST")
            .uri("/extract")
            .header("content-type", "application/json")
            .body(Body::from(serde_json::to_vec(&body).expect("request body serializes")))
            .expect("valid json request");

        let parsed = UnifiedExtractRequest::from_request(request, &())
            .await
            .expect("per-input config must parse");

        let core_inputs: Vec<ExtractInput> = parsed
            .inputs
            .into_iter()
            .map(ApiExtractInput::into_core_input)
            .collect();

        assert_eq!(core_inputs.len(), 2, "both inputs must survive parsing");
        assert_eq!(
            core_inputs[0].config.as_ref().and_then(|config| config.force_ocr),
            Some(true),
            "the first input's force_ocr override must reach ExtractInput::config"
        );
        assert!(
            core_inputs[1].config.is_none(),
            "an input that declared no config must not inherit its sibling's override"
        );
    }

    #[tokio::test]
    async fn should_reject_request_level_llm_transport_config_without_leaking_value() {
        let secret_url = "http://169.254.169.254/latest/meta-data";
        let body = serde_json::json!({
            "inputs": [{"text": "safe input"}],
            "config": {"ocr": {"vlm_config": {"model": "openai/gpt-4o-mini", "base_url": secret_url}}}
        });
        let request = Request::builder()
            .method("POST")
            .uri("/extract")
            .header("content-type", "application/json")
            .body(Body::from(serde_json::to_vec(&body).expect("request body serializes")))
            .expect("valid request");

        let error = UnifiedExtractRequest::from_request(request, &())
            .await
            .expect_err("caller transport config must be rejected");

        assert_eq!(error.status, StatusCode::BAD_REQUEST);
        assert_eq!(
            error.body.message,
            "Validation error: Caller extraction config may not set ocr.vlm_config.base_url"
        );
        assert!(
            !error.body.message.contains(secret_url),
            "rejection must not include caller-controlled values"
        );
    }

    #[tokio::test]
    async fn should_reject_llm_transport_config_in_per_input_override() {
        let body = serde_json::json!({
            "inputs": [{
                "text": "safe input",
                "config": {"captioning": {"llm": {"model": "openai/gpt-4o-mini", "load_env": false}}}
            }]
        });
        let request = Request::builder()
            .method("POST")
            .uri("/extract")
            .header("content-type", "application/json")
            .body(Body::from(serde_json::to_vec(&body).expect("request body serializes")))
            .expect("valid request");

        let error = UnifiedExtractRequest::from_request(request, &())
            .await
            .expect_err("per-input transport config must be rejected");

        assert_eq!(error.status, StatusCode::BAD_REQUEST);
        assert_eq!(
            error.body.message,
            "Validation error: Caller extraction config may not set captioning.llm.load_env"
        );
    }

    #[test]
    fn should_disable_nested_url_flags_for_remote_inputs_when_local_access_is_disabled() {
        let inputs = vec![ApiExtractInput::Uri {
            uri: "https://example.com/document.pdf".to_string(),
            mime_type: None,
            config: None,
        }];
        let mut config = crate::ExtractionConfig::default();
        config.url.allow_local_file_inputs = true;
        config.url.allow_file_uris = true;

        enforce_and_apply_api_uri_policy(&inputs, &mut config, false).expect("remote URI must remain allowed");

        assert!(!config.url.allow_local_file_inputs);
        assert!(!config.url.allow_file_uris);
    }

    #[test]
    fn should_reject_direct_local_uri_when_local_access_is_disabled() {
        let inputs = vec![ApiExtractInput::Uri {
            uri: "file:///etc/passwd".to_string(),
            mime_type: None,
            config: None,
        }];
        let mut config = crate::ExtractionConfig::default();

        let error =
            enforce_and_apply_api_uri_policy(&inputs, &mut config, false).expect_err("local URI must be rejected");

        assert_eq!(error.status, StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn test_version_handler_returns_200() {
        let app = test_router();
        let response = app
            .oneshot(Request::builder().uri("/version").body(Body::empty()).unwrap())
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);

        let body = axum::body::to_bytes(response.into_body(), usize::MAX).await.unwrap();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert!(json["version"].is_string());
        assert!(!json["version"].as_str().unwrap().is_empty());
    }

    #[tokio::test]
    async fn test_cache_manifest_handler_returns_200() {
        let app = test_router();
        let response = app
            .oneshot(Request::builder().uri("/cache/manifest").body(Body::empty()).unwrap())
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);

        let body = axum::body::to_bytes(response.into_body(), usize::MAX).await.unwrap();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert!(json["xberg_version"].is_string());
        assert!(json["total_size_bytes"].is_number());
        assert!(json["model_count"].is_number());
        assert!(json["models"].is_array());
    }

    #[tokio::test]
    async fn test_detect_handler_no_file_returns_400() {
        let app = test_router();

        let response = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/detect")
                    .header("content-type", "multipart/form-data; boundary=testboundary")
                    .body(Body::from("--testboundary--\r\n"))
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn test_cache_warm_handler_empty_request_is_accepted() {
        // An empty `{}` cache-warm request is VALID — it warms the default model set — so it
        // must be accepted, never rejected as a client error. Whether the live warm actually
        // succeeds is environment-dependent: `cache_warm_handler` calls `ensure_all_models`,
        // which reaches the network. This is a unit test of the request-handling contract,
        // not of download success, so it accepts either outcome of the warm itself:
        //   * 200 OK with a well-formed body when the models are reachable/cached, or
        //   * 502 Bad Gateway when the upstream model download is unavailable (offline CI).
        // Any other status — 400/422 (validation regression), 500 (panic), etc. — is a real
        // handler regression and fails the test. This keeps the test hermetic and
        // deterministic regardless of whether the runner can fetch models.
        let app = test_router();
        let response = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/cache/warm")
                    .header("content-type", "application/json")
                    .body(Body::from("{}"))
                    .unwrap(),
            )
            .await
            .unwrap();

        let status = response.status();
        assert!(
            status == StatusCode::OK || status == StatusCode::BAD_GATEWAY,
            "empty cache-warm request must be accepted (200), or fail only at the upstream \
             model download (502 Bad Gateway); got {status}"
        );

        if status == StatusCode::OK {
            let body = axum::body::to_bytes(response.into_body(), usize::MAX).await.unwrap();
            let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
            assert!(json["cache_dir"].is_string());
            assert!(json["downloaded"].is_array());
            assert!(json["already_cached"].is_array());
        }
    }

    #[tokio::test]
    async fn test_cache_warm_handler_empty_embedding_model_returns_400() {
        let app = test_router();
        let response = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/cache/warm")
                    .header("content-type", "application/json")
                    .body(Body::from(r#"{"embedding_model": ""}"#))
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
        let body = axum::body::to_bytes(response.into_body(), usize::MAX).await.unwrap();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        let error_msg = json["message"].as_str().unwrap_or("");
        assert!(
            error_msg.contains("must not be empty"),
            "Expected empty embedding_model validation error, got: {}",
            error_msg
        );
    }

    #[tokio::test]
    async fn test_cache_warm_handler_whitespace_embedding_model_returns_400() {
        let app = test_router();
        let response = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/cache/warm")
                    .header("content-type", "application/json")
                    .body(Body::from(r#"{"embedding_model": "   "}"#))
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn test_cache_warm_handler_empty_ner_model_returns_400() {
        let app = test_router();
        let response = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/cache/warm")
                    .header("content-type", "application/json")
                    .body(Body::from(r#"{"ner_model": ""}"#))
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
        let body = axum::body::to_bytes(response.into_body(), usize::MAX).await.unwrap();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        let error_msg = json["message"].as_str().unwrap_or("");
        assert!(
            error_msg.contains("ner_model") && error_msg.contains("must not be empty"),
            "Expected empty ner_model validation error, got: {}",
            error_msg
        );
    }

    #[cfg(not(feature = "ner-onnx"))]
    #[tokio::test]
    async fn test_cache_warm_handler_ner_request_without_feature_returns_400() {
        let app = test_router();
        let response = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/cache/warm")
                    .header("content-type", "application/json")
                    .body(Body::from(r#"{"ner": true}"#))
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
        let body = axum::body::to_bytes(response.into_body(), usize::MAX).await.unwrap();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        let error_msg = json["message"].as_str().unwrap_or("");
        assert!(
            error_msg.contains("ner-onnx"),
            "Expected missing ner-onnx validation error, got: {}",
            error_msg
        );
    }

    #[cfg(feature = "api")]
    #[tokio::test]
    async fn test_extract_async_returns_job_id() {
        let app = test_router();
        let boundary = "testboundary123";
        let body = format!(
            "--{boundary}\r\nContent-Disposition: form-data; name=\"files\"; filename=\"test.txt\"\r\nContent-Type: text/plain\r\n\r\nhello world\r\n--{boundary}--\r\n",
            boundary = boundary
        );

        let response = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/extract-async")
                    .header("content-type", format!("multipart/form-data; boundary={}", boundary))
                    .body(Body::from(body))
                    .expect("valid request"),
            )
            .await
            .expect("handler responded");

        assert_eq!(
            response.status(),
            StatusCode::ACCEPTED,
            "expected HTTP 202 Accepted from POST /extract-async"
        );

        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .expect("body bytes readable");
        let resp: AsyncJobResponse = serde_json::from_slice(&bytes).expect("response parses as AsyncJobResponse");
        assert!(!resp.job_id.is_empty(), "job_id must be non-empty");
    }

    #[cfg(feature = "api")]
    #[tokio::test]
    async fn test_job_status_not_found() {
        let app = test_router();

        let response = app
            .oneshot(
                Request::builder()
                    .method("GET")
                    .uri("/jobs/does-not-exist")
                    .body(Body::empty())
                    .expect("valid request"),
            )
            .await
            .expect("handler responded");

        assert_eq!(
            response.status(),
            StatusCode::NOT_FOUND,
            "expected HTTP 404 for unknown job ID"
        );
    }

    #[cfg(feature = "api")]
    #[tokio::test]
    async fn test_cancel_job_not_found() {
        let app = test_router();

        let response = app
            .oneshot(
                Request::builder()
                    .method("DELETE")
                    .uri("/jobs/does-not-exist")
                    .body(Body::empty())
                    .expect("valid request"),
            )
            .await
            .expect("handler responded");

        assert_eq!(
            response.status(),
            StatusCode::NOT_FOUND,
            "expected HTTP 404 for unknown job ID"
        );
    }

    #[cfg(feature = "api")]
    #[tokio::test]
    async fn test_cancel_job_immediately_after_submission() {
        use crate::api::types::{JobState, JobStatus};
        use tower::Service;

        let mut app = test_router();
        let boundary = "cancelboundary000";
        let body = format!(
            "--{boundary}\r\nContent-Disposition: form-data; name=\"files\"; filename=\"test.txt\"\r\nContent-Type: text/plain\r\n\r\nhello world\r\n--{boundary}--\r\n",
            boundary = boundary
        );

        let post_req: Request<Body> = Request::builder()
            .method("POST")
            .uri("/extract-async")
            .header("content-type", format!("multipart/form-data; boundary={}", boundary))
            .body(Body::from(body))
            .expect("valid request");
        let post_response = tower::ServiceExt::<Request<Body>>::ready(&mut app)
            .await
            .expect("service ready")
            .call(post_req)
            .await
            .expect("POST handler responded");
        let post_bytes = axum::body::to_bytes(post_response.into_body(), usize::MAX)
            .await
            .expect("POST body bytes readable");
        let async_resp: AsyncJobResponse =
            serde_json::from_slice(&post_bytes).expect("POST response parses as AsyncJobResponse");
        let job_id = async_resp.job_id;

        let delete_req: Request<Body> = Request::builder()
            .method("DELETE")
            .uri(format!("/jobs/{}", job_id))
            .body(Body::empty())
            .expect("valid request");
        let delete_response = tower::ServiceExt::<Request<Body>>::ready(&mut app)
            .await
            .expect("service ready")
            .call(delete_req)
            .await
            .expect("DELETE handler responded");

        assert_eq!(
            delete_response.status(),
            StatusCode::OK,
            "expected HTTP 200 when cancelling a job that has not yet reached a terminal state"
        );
        let delete_bytes = axum::body::to_bytes(delete_response.into_body(), usize::MAX)
            .await
            .expect("DELETE body bytes readable");
        let status: JobStatus = serde_json::from_slice(&delete_bytes).expect("response is JobStatus");
        assert_eq!(status.job_id, job_id);
        assert_eq!(status.state, JobState::Cancelled);
    }

    #[cfg(feature = "api")]
    #[tokio::test]
    async fn test_cancel_job_conflict_after_completion() {
        use crate::api::types::{JobState, JobStatus};
        use tower::Service;

        let mut app = test_router();
        let boundary = "conflictboundary111";
        let body = format!(
            "--{boundary}\r\nContent-Disposition: form-data; name=\"files\"; filename=\"test.txt\"\r\nContent-Type: text/plain\r\n\r\nhello world\r\n--{boundary}--\r\n",
            boundary = boundary
        );

        let post_req: Request<Body> = Request::builder()
            .method("POST")
            .uri("/extract-async")
            .header("content-type", format!("multipart/form-data; boundary={}", boundary))
            .body(Body::from(body))
            .expect("valid request");
        let post_response = tower::ServiceExt::<Request<Body>>::ready(&mut app)
            .await
            .expect("service ready")
            .call(post_req)
            .await
            .expect("POST handler responded");
        let post_bytes = axum::body::to_bytes(post_response.into_body(), usize::MAX)
            .await
            .expect("POST body bytes readable");
        let async_resp: AsyncJobResponse =
            serde_json::from_slice(&post_bytes).expect("POST response parses as AsyncJobResponse");
        let job_id = async_resp.job_id;

        let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(2);
        loop {
            let poll_req: Request<Body> = Request::builder()
                .method("GET")
                .uri(format!("/jobs/{}", job_id))
                .body(Body::empty())
                .expect("valid request");
            let resp = tower::ServiceExt::<Request<Body>>::ready(&mut app)
                .await
                .expect("service ready")
                .call(poll_req)
                .await
                .expect("GET responded");
            let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
                .await
                .expect("body readable");
            let status: JobStatus = serde_json::from_slice(&bytes).expect("response is JobStatus");
            if matches!(status.state, JobState::Completed | JobState::Failed) {
                break;
            }
            assert!(
                tokio::time::Instant::now() < deadline,
                "job did not reach terminal state within 2s"
            );
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
        }

        let delete_req: Request<Body> = Request::builder()
            .method("DELETE")
            .uri(format!("/jobs/{}", job_id))
            .body(Body::empty())
            .expect("valid request");
        let delete_response = tower::ServiceExt::<Request<Body>>::ready(&mut app)
            .await
            .expect("service ready")
            .call(delete_req)
            .await
            .expect("DELETE handler responded");

        assert_eq!(
            delete_response.status(),
            StatusCode::CONFLICT,
            "expected HTTP 409 when cancelling a job that already completed"
        );
    }

    #[cfg(feature = "api")]
    #[tokio::test]
    async fn test_extract_async_then_poll_job_id() {
        use crate::api::types::{JobState, JobStatus};
        use tower::Service;

        let mut app = test_router();
        let boundary = "pollboundary456";
        let body = format!(
            "--{boundary}\r\nContent-Disposition: form-data; name=\"files\"; filename=\"hello.txt\"\r\nContent-Type: text/plain\r\n\r\nhello world\r\n--{boundary}--\r\n",
            boundary = boundary
        );

        let post_req: Request<Body> = Request::builder()
            .method("POST")
            .uri("/extract-async")
            .header("content-type", format!("multipart/form-data; boundary={}", boundary))
            .body(Body::from(body))
            .expect("valid request");
        let post_response = tower::ServiceExt::<Request<Body>>::ready(&mut app)
            .await
            .expect("service ready")
            .call(post_req)
            .await
            .expect("POST handler responded");

        assert_eq!(
            post_response.status(),
            StatusCode::ACCEPTED,
            "expected HTTP 202 from POST /extract-async"
        );

        let post_bytes = axum::body::to_bytes(post_response.into_body(), usize::MAX)
            .await
            .expect("POST body bytes readable");
        let async_resp: AsyncJobResponse =
            serde_json::from_slice(&post_bytes).expect("POST response parses as AsyncJobResponse");
        let job_id = async_resp.job_id;
        assert!(!job_id.is_empty(), "job_id from POST must be non-empty");

        let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(2);
        let final_status = loop {
            let poll_req: Request<Body> = Request::builder()
                .method("GET")
                .uri(format!("/jobs/{}", job_id))
                .body(Body::empty())
                .expect("valid request");
            let resp = tower::ServiceExt::<Request<Body>>::ready(&mut app)
                .await
                .expect("service ready")
                .call(poll_req)
                .await
                .expect("GET responded");
            assert_eq!(
                resp.status(),
                StatusCode::OK,
                "expected HTTP 200 from GET /jobs/{{job_id}}"
            );
            let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
                .await
                .expect("body readable");
            let status: JobStatus = serde_json::from_slice(&bytes).expect("response is JobStatus");
            if matches!(status.state, JobState::Completed | JobState::Failed) {
                break status;
            }
            assert!(
                tokio::time::Instant::now() < deadline,
                "job did not reach terminal state within 2s"
            );
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
        };

        assert_eq!(
            final_status.job_id, job_id,
            "JobStatus.job_id must match the submitted job_id"
        );
        assert_eq!(
            final_status.state,
            JobState::Completed,
            "job must complete successfully"
        );
        assert!(
            final_status.result.is_some(),
            "completed job must carry an extraction result"
        );
    }

    #[cfg(feature = "api")]
    #[tokio::test]
    async fn test_extract_async_bad_file_fails() {
        use crate::api::types::{JobState, JobStatus};
        use tower::Service;

        let mut app = test_router();
        let boundary = "badboundary789";
        let body = format!(
            "--{boundary}\r\nContent-Disposition: form-data; name=\"files\"; filename=\"bad.xyz\"\r\nContent-Type: application/x-unsupported-format\r\n\r\ngarbage\r\n--{boundary}--\r\n",
            boundary = boundary
        );

        let post_req: Request<Body> = Request::builder()
            .method("POST")
            .uri("/extract-async")
            .header("content-type", format!("multipart/form-data; boundary={}", boundary))
            .body(Body::from(body))
            .expect("valid request");
        let post_response = tower::ServiceExt::<Request<Body>>::ready(&mut app)
            .await
            .expect("service ready")
            .call(post_req)
            .await
            .expect("POST handler responded");

        assert_eq!(post_response.status(), StatusCode::ACCEPTED);

        let post_bytes = axum::body::to_bytes(post_response.into_body(), usize::MAX)
            .await
            .expect("body readable");
        let async_resp: AsyncJobResponse = serde_json::from_slice(&post_bytes).expect("parses as AsyncJobResponse");
        let job_id = async_resp.job_id;

        let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(2);
        let final_status = loop {
            let poll_req: Request<Body> = Request::builder()
                .method("GET")
                .uri(format!("/jobs/{}", job_id))
                .body(Body::empty())
                .expect("valid request");
            let resp = tower::ServiceExt::<Request<Body>>::ready(&mut app)
                .await
                .expect("service ready")
                .call(poll_req)
                .await
                .expect("GET responded");
            assert_eq!(resp.status(), StatusCode::OK);
            let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
                .await
                .expect("body readable");
            let status: JobStatus = serde_json::from_slice(&bytes).expect("response is JobStatus");
            if matches!(status.state, JobState::Completed | JobState::Failed) {
                break status;
            }
            assert!(
                tokio::time::Instant::now() < deadline,
                "job did not reach terminal state within 2s"
            );
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
        };

        assert_eq!(
            final_status.state,
            JobState::Completed,
            "unsupported-format input is reported in the result envelope, not as a job failure"
        );
        let result = final_status
            .result
            .expect("completed job must carry an extraction result");
        let errors = result
            .get("errors")
            .and_then(|value| value.as_array())
            .expect("result envelope must contain an errors array");
        assert!(
            !errors.is_empty(),
            "unsupported-format input must be reported as a per-input error"
        );
    }
}