convert-rs 2.0.0

Extensible file conversion library with graph routing and optional native tools
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
//! Adapter registry, route execution, and per-step output validation.
//!
//! Every step receives a private output directory, and every artifact an adapter
//! returns is checked: regular file, inside its step directory, declared
//! format matches the step target, and total bytes respect the budget. A step
//! that fails validation abandons the route and the engine tries the next.
//! The workspace is a file ownership boundary, not an execution sandbox.

use std::collections::{BTreeMap, BTreeSet};
use std::io::Read;
use std::path::{Path, PathBuf};
use std::sync::Arc;

use tempfile::TempDir;

use crate::{
    Adapter, Artifact, BackendStatus, ContentKind, ContentProfile, ConversionKind, Error, Format,
    Graph, Limits, Plan, Policy, Result, StepRequest,
};

use crate::builtin::{BuiltinAdapter, detect};

#[cfg(feature = "archives")]
use crate::archives::ArchivesAdapter;
#[cfg(feature = "media")]
use crate::media::MediaAdapter;

/// Per-conversion identification and route-selection choices.
///
/// Defaults use file identification and normal planning without a backend filter
/// or quality params. Resource budgets are configured separately through
/// [`Converter::limits`]. All fields are public; construct with
/// `ConversionOptions { field: value, ..ConversionOptions::default() }`.
#[derive(Clone, Debug, Default)]
pub struct ConversionOptions {
    /// Override format identification for every input (a format ID or extension).
    ///
    /// Skips content identification, including its empty-file rejection. Staging
    /// still requires regular files within the per-file input budget. This is a
    /// caller assertion, not a content validation request.
    pub from: Option<String>,
    /// Require every executed step to use this backend.
    ///
    /// Normal planning first finds a bounded set of routes, then filters it; a
    /// matching route outside that set is not searched for. Identity plans have
    /// no steps and pass any backend filter. Forced plans are checked step by step.
    pub backend: Option<String>,
    /// Skip route search and attempt only this caller-supplied plan.
    ///
    /// Prefer a plan obtained from [`Converter::plan`]. Steps must have concrete
    /// format IDs. Execution checks kind gates, the `external` flag against
    /// [`Policy::allow_external`], backend filtering, format continuity, and
    /// returned artifacts. It does not verify edge membership in the graph,
    /// recompute cost, enforce search budgets or decode-only gates, or apply
    /// [`Policy::allow_external_packaging`]. Metadata is trusted: forced plans
    /// are not a safe boundary for untrusted callers.
    pub forced_plan: Option<Plan>,
    /// Quality knobs forwarded verbatim to every executed step.
    ///
    /// The reserved key `quality` carries a 0-100 integer string; the engine
    /// validates that range and adapters map it onto their closest encoder
    /// control (JPEG/WebP quality, ffmpeg `-q`, imageMagick `-quality`).
    /// Unknown keys are ignored by adapters, so passing knobs for a backend
    /// that is not selected is harmless. Params never select paths or tools:
    /// values are opaque strings and are never interpolated into argv as
    /// executable or filesystem locations.
    pub params: BTreeMap<String, String>,
    /// Re-sniff every step's artifacts by content magic before accepting them.
    ///
    /// When enabled, the engine reads the first bytes of each returned file and
    /// compares the detected format with the step target. A contradiction fails
    /// the route and the engine falls back to the next plan. Bytes with no known
    /// signature are accepted, because absence of evidence is not evidence of
    /// a mismatch. Disabled by default because detection only covers formats
    /// with registered signatures.
    pub verify: bool,
    /// Request a genuine re-encode when source and target formats match.
    ///
    /// By default a same-format request stages a byte-for-byte copy with an
    /// empty plan. When set, planning searches for nonempty routes that return
    /// to the requested format (image recompression, codec change inside a
    /// container) and the identity copy is not offered. If no re-encode route
    /// exists with the registered adapters, conversion fails with an explanatory
    /// [`Error::Invalid`] rather than silently copying.
    pub reencode: bool,
    /// Content properties every executed step must declare it preserves.
    ///
    /// Names are adapter vocabulary (`pixels`, `alpha`, `metadata`, `structure`,
    /// ...), matched case-insensitively against [`crate::Conversion::retained`] during
    /// planning and enforced again for forced plans at execution. An empty list
    /// (the default) adds no requirement. The zero-step identity copy satisfies
    /// any retention request because it preserves bytes.
    pub preserve: Vec<String>,
    /// Ask adapters to inspect this input's content before planning.
    ///
    /// When set (and no [`Self::from`] override is given), [`Converter::convert`]
    /// profiles the first identified input through [`Converter::profile`] and
    /// searches with [`Graph::routes_with_profile`](convert_rs_core::Graph::routes_with_profile),
    /// so edges with [`crate::Conversion::requires`] content are gated on the
    /// observed streams. With an override, format identification (and any
    /// inspection) is the caller's job and no profile is taken. The converter's
    /// [`Policy::inspect_content`] sets the same behavior for every request;
    /// this field overrides it per call.
    pub inspect_content: bool,
}

impl ConversionOptions {
    /// Validate caller-supplied params, returning a descriptive error.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Invalid`] when `quality` is present but not an integer
    /// within 0-100, or when `reencode` is combined with a forced plan.
    fn validate(&self) -> Result<()> {
        if let Some(quality) = self.params.get("quality") {
            let value: u8 = quality
                .trim()
                .parse()
                .map_err(|_| Error::Invalid(format!("quality must be 0-100, got {quality}")))?;
            if value > 100 {
                return Err(Error::Invalid(format!(
                    "quality must be 0-100, got {value}"
                )));
            }
        }
        if self.reencode && self.forced_plan.is_some() {
            return Err(Error::Invalid(
                "reencode replaces route search and cannot combine with a forced plan".into(),
            ));
        }
        if self.inspect_content && self.forced_plan.is_some() {
            return Err(Error::Invalid(
                "inspect_content drives route search and cannot combine with a forced plan".into(),
            ));
        }
        Ok(())
    }

    /// Enforce requested retention claims on a caller-supplied forced plan.
    ///
    /// Search applies [`Policy::retain`] pruning, but forced plans bypass search,
    /// so every nonempty step must declare it preserves at least the properties
    /// named in [`Self::preserve`] (matched case-insensitively). Plans with no
    /// steps are identity copies and always satisfy the request.
    fn check_forced_retention(&self, plan: &Plan) -> Result<()> {
        for step in &plan.steps {
            for wanted in &self.preserve {
                let wanted = wanted.trim().to_ascii_lowercase();
                if wanted.is_empty() {
                    continue;
                }
                if !step.retained.iter().any(|held| held == &wanted) {
                    return Err(Error::Security(format!(
                        "step {} via {} does not declare it preserves {wanted}",
                        step.operation, step.backend
                    )));
                }
            }
        }
        Ok(())
    }

    /// Enforce the caller's content policy on a caller-supplied forced plan.
    ///
    /// Mirrors the planner's [`Policy::require`] gate: each required kind must
    /// appear in the observed profile (when one exists), in the final step's
    /// [`crate::Conversion::produces`] claim, or in the target format's declared
    /// payloads when [`Policy::require_content`] is off.
    fn check_forced_content(
        &self,
        plan: &Plan,
        target: &Format,
        profile: Option<&ContentProfile>,
        require: &[ContentKind],
        require_content: bool,
    ) -> Result<()> {
        for wanted in require {
            let delivered = profile
                .filter(|found| found.format == target.id)
                .is_some_and(|found| found.declares(wanted))
                || plan
                    .produced()
                    .iter()
                    .any(|produced| wanted.matches(produced))
                || (!require_content
                    && target
                        .payloads
                        .iter()
                        .any(|declared| wanted.matches(declared)));
            if !delivered {
                return Err(Error::Security(format!(
                    "forced plan does not deliver required content {wanted} in {target}",
                    target = target.id
                )));
            }
        }
        Ok(())
    }
}

/// One attempted route during a single [`Converter::convert`] call.
///
/// The report's `attempts` list records every route try in order, including the
/// successful one, so callers can explain to users why a preferred route was
/// skipped instead of silently falling back.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct RouteAttempt {
    /// Zero-based position of this attempt in the fallback order.
    pub index: usize,
    /// Human-readable rendering of the route, e.g. `txt→json via builtin`.
    pub route: String,
    /// Adapter-declared plan that was executed (or attempted).
    pub plan: Plan,
    /// Rendered failure for rejected routes; `None` for the accepted route.
    pub error: Option<String>,
}

impl RouteAttempt {
    /// Construct an attempt record.
    #[must_use]
    pub fn new(index: usize, route: String, plan: Plan, error: Option<String>) -> Self {
        Self {
            index,
            route,
            plan,
            error,
        }
    }
}

/// An informational warning derived from an executed step's declared kind.
///
/// The engine emits one warning for each non-lossless step of the successful
/// route, including packaging and extraction. It does not measure actual loss
/// or collect every adapter diagnostic. Failed attempts' warnings are discarded.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Warning {
    /// Zero-based index into the successful report's plan, not an artifact index.
    pub step: usize,
    /// Adapter that executed the step.
    pub backend: String,
    /// Adapter operation ID.
    pub operation: String,
    /// Adapter-declared semantic classification of the step.
    pub kind: ConversionKind,
    /// Explanation suitable for logs or a user interface.
    pub message: String,
}

/// A resolved conversion: the accepted route, its warnings, and the artifacts.
///
/// Artifacts live in a private directory owned by this report. Dropping the
/// report deletes them, so copy final files out before the report is dropped.
/// Moving or cloning artifact paths does not transfer workspace ownership.
/// Use [`Self::write_all_to`] to persist artifacts, or [`Self::directory`] to
/// access the workspace directly.
#[derive(Debug)]
#[non_exhaustive]
pub struct ConversionReport {
    workspace: TempDir,
    /// Route selected and executed by the converter, or the supplied forced plan.
    pub plan: Plan,
    /// Final artifacts, in adapter output order, or input order for identity copies.
    ///
    /// Format labels were checked against the target, not independently decoded,
    /// unless [`ConversionOptions::verify`] was enabled for this conversion.
    pub artifacts: Vec<Artifact>,
    /// One warning per non-lossless step in this report's plan.
    ///
    /// An empty list is not a guarantee of complete quality or metadata preservation.
    pub warnings: Vec<Warning>,
    /// Cost-ordered notes for every non-lossless step that actually ran,
    /// carrying the adapter-declared fidelity note when the step supplied one.
    ///
    /// This is the quality/cost view a UI should render next to warnings:
    /// what each lossy step discards, straight from the adapter, rather than
    /// the engine's generic sentence.
    pub costs: Vec<StepCost>,
    /// Structured log of every route attempted while producing this report.
    ///
    /// Every attempt is included, including earlier fallbacks that failed and
    /// the accepted route (the final entry). Empty only when conversion itself
    /// failed before planning, because a failed [`Converter::convert`] returns
    /// [`Error::RoutesFailed`] only as a rendered string.
    pub attempts: Vec<RouteAttempt>,
    /// Requested [`ConversionOptions::params`] keys no executed step declared support for.
    ///
    /// Adapters ignore unknown keys by contract, so a typo would otherwise
    /// silently change nothing. After each successful route the engine unions
    /// [`crate::Adapter::param_keys`] over its steps and reports the difference.
    /// A nonempty list is informational: the conversion succeeded, but those
    /// knobs had no effect.
    pub ignored_params: Vec<String>,
}

/// How reachable a requested target format is from a probed source format.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum CapabilityReason {
    /// A route exists under the current policy and adapter availability.
    Planned {
        /// Cost of the cheapest found route.
        cost: u64,
    },
    /// A route exists but the policy gate (lossy, bridges, external, ...) blocks it.
    PolicyBlocked,
    /// The only routes need backends that are not registered or report unavailable.
    BackendUnavailable {
        /// Backend names that exist but are unusable on this host.
        backends: Vec<String>,
    },
    /// No graph route exists with the registered adapters under any gate setting.
    NoRoute,
}

/// One target format's reachability from a source format.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TargetCapability {
    /// Resolved target format ID.
    pub format: String,
    /// Why or whether conversion to this format is currently possible.
    pub reason: CapabilityReason,
}

/// Identification plus per-format deep-decode results for one input file.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct InputReport {
    /// Identification found for the file.
    pub identification: Identification,
    /// Path checked.
    pub path: PathBuf,
    /// Formats whose registered adapters confirmed the file decodes.
    ///
    /// Populated by [`Converter::probe`] only for formats adapters answered
    /// about; absence means no adapter gave an opinion, which is not rejection.
    pub decodable_as: Vec<String>,
}

/// Where a [`Converter::profile`] profile came from.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ProfileSource {
    /// An available adapter described the file's streams.
    Observed,
    /// No claiming adapter answered; planning falls back to declared payloads.
    NoOpinion,
    /// An adapter's inspection exceeded [`Limits::timeout`] and nobody answered.
    Timeout,
}

/// Identification plus an optional content profile for one input file.
///
/// Returned by [`Converter::profile`]. `profile` is `Some` only when an
/// adapter actually described the file: an observed profile with no streams is
/// real evidence (the file carries nothing describable), while `None` means no
/// adapter answered and the graph's declared [`Format::payloads`] stand in.
/// [`Self::identification`] is the [`Converter::identify`] result the profile
/// was taken for.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct ProfileReport {
    /// Format identification for the file.
    pub identification: Identification,
    /// Adapter-observed profile, or `None` when nothing answered.
    pub profile: Option<ContentProfile>,
    /// Which kind of outcome produced [`Self::profile`].
    pub source: ProfileSource,
}

/// A note explaining what an executed step costs or discards.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct StepCost {
    /// Zero-based step index in the executed plan.
    pub step: usize,
    /// Adapter that ran the step.
    pub backend: String,
    /// Adapter operation ID.
    pub operation: String,
    /// Adapter-declared semantic classification.
    pub kind: ConversionKind,
    /// The step's declared cost contribution.
    pub cost: u32,
    /// Adapter-supplied fidelity sentence, falling back to an engine default.
    pub note: String,
}

impl StepCost {
    /// Build a cost note for one executed step.
    #[must_use]
    pub fn new(
        step: usize,
        backend: &str,
        operation: &str,
        kind: ConversionKind,
        cost: u32,
        note: Option<&str>,
    ) -> Self {
        Self {
            step,
            backend: backend.to_owned(),
            operation: operation.to_owned(),
            kind,
            cost,
            note: note
                .unwrap_or("no fidelity note declared by this adapter")
                .to_owned(),
        }
    }
}

impl ConversionReport {
    /// The workspace directory holding this report's artifacts.
    ///
    /// It also contains staged inputs and intermediate outputs. The returned
    /// path is valid only while this report's temporary directory exists; this
    /// method does not persist or transfer ownership of that directory.
    #[must_use]
    pub fn directory(&self) -> &Path {
        self.workspace.path()
    }

    /// Copy the final artifacts into `dir`, creating it when missing.
    ///
    /// Files are named from [`Self::suggested_names`] and never overwritten: an
    /// existing destination gains a `-<n>` suffix, matching the collision naming
    /// inside the batch itself. Each file is written through a temporary path
    /// and renamed, so a failed copy leaves no partial output. Returns the
    /// written paths in artifact order. The report keeps ownership of the
    /// workspace; dropping the report does not remove these copies. Calling
    /// this method twice persists a second, rename-deduplicated set.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Io`] for filesystem failures.
    pub fn write_all_to(&self, dir: &Path) -> Result<Vec<PathBuf>> {
        std::fs::create_dir_all(dir)?;
        let mut written = Vec::with_capacity(self.artifacts.len());
        for name in self.suggested_names() {
            let destination = unique_destination(dir, &name);
            let artifact = &self.artifacts[written.len()];
            let temporary = dir.join(format!(".convert-rs-{}.tmp", uuid_like(written.len())));
            let result = (|| -> Result<()> {
                std::fs::copy(&artifact.path, &temporary)?;
                std::fs::rename(&temporary, &destination)?;
                Ok(())
            })();
            if result.is_err() {
                let _ = std::fs::remove_file(&temporary);
            }
            result?;
            written.push(destination);
        }
        Ok(written)
    }

    /// Stable artifact file names, `converted-<index>.<target>`.
    ///
    /// The report does not retain input paths, so batch output directories get
    /// positional names; rename after writing if the original basename matters.
    /// Artifacts that carry an [`Artifact::logical_name`] instead suggest a
    /// sanitized form of it, preserving the member names extraction produced.
    #[must_use]
    pub fn suggested_names(&self) -> Vec<String> {
        self.artifacts
            .iter()
            .enumerate()
            .map(|(index, artifact)| match &artifact.logical_name {
                Some(name) => sanitize_suggested_name(name),
                None => {
                    let extension = artifact
                        .format
                        .chars()
                        .filter(|c| c.is_ascii_lowercase() || c.is_ascii_digit())
                        .collect::<String>();
                    let extension = if extension.is_empty() {
                        "bin"
                    } else {
                        &extension
                    };
                    format!("converted-{index}.{extension}")
                }
            })
            .collect()
    }
}

/// Choose a destination path that exists nowhere yet, appending `-<n>` on a clash.
fn unique_destination(dir: &Path, name: &str) -> PathBuf {
    let candidate = dir.join(name);
    if !candidate.exists() {
        return candidate;
    }
    let (stem, extension) = name.rsplit_once('.').unwrap_or((name, ""));
    (1u32..)
        .map(|index| {
            if extension.is_empty() {
                dir.join(format!("{stem}-{index}"))
            } else {
                dir.join(format!("{stem}-{index}.{extension}"))
            }
        })
        .find(|renamed| !renamed.exists())
        .unwrap_or(candidate)
}

/// A short, deterministic pseudo-unique token for temp file names.
fn uuid_like(seed: usize) -> String {
    use std::hash::{Hash, Hasher};
    let mut hasher = std::collections::hash_map::DefaultHasher::new();
    (std::process::id(), seed, std::time::SystemTime::now()).hash(&mut hasher);
    format!("{:016x}", hasher.finish())
}

/// Reduce a logical name to one safe file-name component for persistence.
fn sanitize_suggested_name(name: &str) -> String {
    let basename = name.rsplit(['/', '\\']).next().unwrap_or(name);
    let cleaned: String = basename
        .chars()
        .take(128)
        .map(|c| {
            if c.is_control() || matches!(c, ':' | '<' | '>' | '"' | '|' | '?' | '*' | '\0') {
                '_'
            } else {
                c
            }
        })
        .collect();
    let trimmed = cleaned.trim_matches(['.', ' ']);
    if trimmed.is_empty() {
        "file".to_owned()
    } else {
        trimmed.to_owned()
    }
}

/// A resolved input format with the evidence used to determine it.
///
/// Identification is a heuristic label, not proof that a decoder accepts the file.
/// [`Converter::identify`] never returns [`IdentificationMethod::Override`]; that
/// variant represents a source override applied internally during conversion.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Identification {
    /// Resolved format ID.
    pub format: String,
    /// Evidence used to identify the input.
    pub method: IdentificationMethod,
}

impl Identification {
    /// Construct an identification record.
    #[must_use]
    pub fn new(format: impl Into<String>, method: IdentificationMethod) -> Self {
        Self {
            format: format.into(),
            method,
        }
    }
}

/// Evidence source used by [`Converter::identify`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum IdentificationMethod {
    /// Caller supplied the format override.
    Override,
    /// A single filename suffix matched a registered ID or extension alias.
    Extension,
    /// Up to the first 1,024 bytes matched a known signature for a registered format.
    Magic,
    /// No known signature or extension matched; the input is treated as binary.
    Unknown,
}

/// Adapter registry, routing configuration, and file conversion entry point.
///
/// [`Self::new`] and [`Default`] register compiled-in pure-Rust adapters with
/// default [`Policy`] and [`Limits`]. Native tools require explicit discovery
/// (with the `external` feature) and policy opt-in. Execution requires a Tokio
/// runtime; registration, lookup, and planning do not.
///
/// Plans describe format-level operations, not codec selection. A route can
/// fail because of input contents or adapter limitations despite valid metadata.
pub struct Converter {
    graph: Graph,
    adapters: BTreeMap<String, Arc<dyn Adapter>>,
    order: Vec<String>,
    policy: Policy,
    limits: Limits,
}

impl std::fmt::Debug for Converter {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("Converter")
            .field("adapters", &self.order)
            .field("formats", &self.graph.formats().count())
            .finish()
    }
}

impl Default for Converter {
    fn default() -> Self {
        Self::new()
    }
}

impl Converter {
    /// Construct a converter with every compiled-in pure-Rust adapter.
    ///
    /// Always includes byte/text operations. Optional `data`, `media`, and
    /// `archives` features add their operations. Does not probe native tools.
    #[must_use]
    pub fn new() -> Self {
        let mut converter = Self {
            graph: Graph::new(),
            adapters: BTreeMap::new(),
            order: Vec::new(),
            policy: Policy::default(),
            limits: Limits::default(),
        };
        let _ = converter.register(Arc::new(BuiltinAdapter));
        #[cfg(feature = "media")]
        {
            let _ = converter.register(Arc::new(MediaAdapter));
        }
        #[cfg(feature = "archives")]
        {
            let _ = converter.register(Arc::new(ArchivesAdapter));
        }
        converter
    }

    /// Construct a converter and register native-tool adapters whose probes succeed.
    ///
    /// Available only with the `external` feature. Starts from [`Self::new`];
    /// unavailable tools are omitted rather than returned as errors. Probes do
    /// not establish that every advertised format or codec works for a file.
    /// Native tools are invoked per operation, not kept running by discovery.
    ///
    /// The default policy still disallows external routes. Set
    /// [`Policy::allow_external`] to use them. The library does not sandbox native
    /// tools; use operating-system isolation for hostile inputs.
    #[cfg(feature = "external")]
    pub async fn discover() -> Self {
        let mut converter = Self::new();
        let adapters = crate::external::discover().await;
        for adapter in adapters {
            if adapter.status().available {
                let _ = converter.register(adapter);
            }
        }
        converter
    }

    /// Add an adapter. Registration by name is idempotent; re-registering the
    /// same name replaces the previous adapter and rebuilds the graph.
    ///
    /// Formats from all adapters are registered before edges, allowing references
    /// to other adapters' formats. No availability probe is required. Metadata
    /// must remain stable across calls. Failed registration leaves the current
    /// registry and graph unchanged.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Invalid`] for an empty name, a name longer than 64 bytes,
    /// no format declarations, more than 8,192 formats, or more than 1,000,000
    /// conversions from the incoming adapter. Returns [`Error::Plan`] if the
    /// rebuilt graph rejects format or edge metadata. Backend names in edges
    /// are not checked against the adapter's registration name.
    pub fn register(&mut self, adapter: Arc<dyn Adapter>) -> Result<()> {
        let name = adapter.name().to_owned();
        if name.is_empty() || name.len() > 64 {
            return Err(Error::Invalid("invalid adapter name".into()));
        }
        let formats = adapter.formats();
        let conversions = adapter.conversions();
        if formats.is_empty() || formats.len() > 8192 || conversions.len() > 1_000_000 {
            return Err(Error::Invalid("adapter registration rejected".into()));
        }
        // Rebuild from every registered adapter so a replacement never leaves
        // edges whose backend no longer exists, and so a rejected registration
        // cannot leave a converter with an emptied registry.
        let mut previous = self.adapters.clone();
        let mut ordered = self.order.clone();
        ordered.retain(|existing| existing != &name);
        ordered.push(name.clone());
        previous.insert(name.clone(), Arc::clone(&adapter));
        let mut graph = Graph::new();
        for key in &ordered {
            for format in previous[key].formats() {
                graph.add_format(format).map_err(Error::Plan)?;
            }
        }
        for key in &ordered {
            for conversion in previous[key].conversions() {
                graph.add_conversion(conversion).map_err(Error::Plan)?;
            }
        }
        self.graph = graph;
        self.adapters = previous;
        self.order = ordered;
        Ok(())
    }

    #[must_use]
    /// Replace resource limits using builder-style ownership.
    ///
    /// Does not validate the values. See [`Limits`] for adapter-dependent checks
    /// and the distinction between budgets and hard resource isolation.
    pub fn limits(mut self, limits: Limits) -> Self {
        self.limits = limits;
        self
    }

    #[must_use]
    /// Replace the routing and execution policy using builder-style ownership.
    ///
    /// The policy is not validated here; invalid search settings fail at planning.
    pub fn with_policy(mut self, policy: Policy) -> Self {
        self.policy = policy;
        self
    }

    /// Replace the routing policy at runtime.
    ///
    /// Affects later conversions, including kind checks on forced plans. It does
    /// not alter previously returned plans or validate the new policy immediately.
    pub fn set_policy(&mut self, policy: Policy) {
        self.policy = policy;
    }

    #[must_use]
    /// Return the immutable route graph used by this converter.
    ///
    /// Use [`Self::register`] to contribute formats and conversions.
    pub fn graph(&self) -> &Graph {
        &self.graph
    }

    #[must_use]
    /// Return the current routing policy.
    pub fn policy(&self) -> &Policy {
        &self.policy
    }

    #[must_use]
    /// Clone all registered formats in ascending format-ID order.
    ///
    /// Includes custom registrations, not just compiled-in or discovered adapters.
    /// Presence does not imply a permitted route or a working encoder.
    pub fn formats(&self) -> Vec<Format> {
        self.graph.formats().cloned().collect()
    }

    /// Return registered adapters' status reports in ascending backend-name order.
    ///
    /// Calls [`Adapter::status`], which may return cached probe results. Tools
    /// omitted during discovery are not listed; status does not re-plan routes.
    #[must_use]
    pub fn backends(&self) -> Vec<BackendStatus> {
        self.adapters
            .values()
            .map(|adapter| adapter.status())
            .collect()
    }

    #[must_use]
    /// Resolve a format ID or extension alias without inspecting a file.
    ///
    /// Trims whitespace, folds ASCII case, and accepts leading dots. IDs take
    /// precedence over aliases; ambiguous aliases choose the smallest format ID.
    /// Returns `None` for unknown values. Does not parse paths or MIME types.
    pub fn resolve(&self, value: &str) -> Option<&Format> {
        self.graph.resolve(value)
    }

    /// Identify one nonempty regular input file by extension, then signature.
    ///
    /// Multi-dot names strip every alphanumeric suffix (`archive.tar.gz` looks
    /// up `tar.gz`, then `gz`). A recognized suffix wins without opening or
    /// validating the contents. Otherwise, up to 1,024 bytes are read for
    /// magic detection. Unknown content becomes `bin`; built-in conversion
    /// from `bin` to text requires reinterpretation opt-in, but identity does not.
    ///
    /// Zero-byte files are rejected unless [`Policy::allow_empty_inputs`] is
    /// enabled; with the policy open, empty inputs identify as `bin`.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Invalid`] when metadata cannot be inspected or a needed
    /// header read fails. Returns [`Error::Security`] for nonregular paths
    /// (including symlinks) and for empty files under the default policy.
    /// Input byte budgets are checked later during staging, not by this method.
    pub fn identify(&self, path: &Path) -> Result<Identification> {
        let metadata = std::fs::symlink_metadata(path)
            .map_err(|_| Error::Invalid(format!("cannot inspect {}", path.display())))?;
        if !metadata.file_type().is_file() {
            return Err(Error::Security("input is not a regular file".into()));
        }
        if metadata.len() == 0 {
            if !self.policy.allow_empty_inputs {
                return Err(Error::Security("input is empty".into()));
            }
            return Ok(Identification {
                format: "bin".into(),
                method: IdentificationMethod::Unknown,
            });
        }
        if let Some(id) = extensions_of(path)
            .iter()
            .find_map(|value| self.graph.resolve(value))
        {
            return Ok(Identification {
                format: id.id.clone(),
                method: IdentificationMethod::Extension,
            });
        }
        let mut header = [0u8; 1024];
        let mut file =
            std::fs::File::open(path).map_err(|_| Error::Invalid("input is unreadable".into()))?;
        let count = file
            .read(&mut header)
            .map_err(|_| Error::Invalid("input is unreadable".into()))?;
        if let Some(id) = detect(&header[..count]).and_then(|name| self.graph.resolve(name)) {
            return Ok(Identification {
                format: id.id.clone(),
                method: IdentificationMethod::Magic,
            });
        }
        Ok(Identification {
            format: "bin".into(),
            method: IdentificationMethod::Unknown,
        })
    }

    /// Identify a file, then ask available decoders what it really holds.
    ///
    /// Runs [`Self::identify`] first, then calls [`Adapter::accepts_input`] on
    /// every format declared by an available adapter. Formats an adapter confirms
    /// are listed in [`InputReport::decodable_as`]; formats nobody answered
    /// about are absent, which is not a rejection. The full byte budget applies
    /// per answer, so probing a large adversarial file costs at most one decode
    /// per declared format.
    ///
    /// # Errors
    ///
    /// As [`Self::identify`].
    pub fn probe(&self, path: &Path) -> Result<InputReport> {
        let identification = self.identify(path)?;
        let mut decodable = BTreeSet::new();
        for adapter in self.adapters.values() {
            if !adapter.status().available {
                continue;
            }
            for format in adapter.formats() {
                if decodable.contains(&format.id) {
                    continue;
                }
                if adapter.accepts_input(path, &format.id, &self.limits) == Some(true) {
                    decodable.insert(format.id);
                }
            }
        }
        Ok(InputReport {
            identification,
            path: path.to_path_buf(),
            decodable_as: decodable.into_iter().collect(),
        })
    }

    /// Identify a file, then ask one available adapter to describe its streams.
    ///
    /// [`Policy::inspect_content`] is a directive for engines like this one:
    /// when it is set, [`Self::convert`] profiles the first identified input
    /// before planning and routes through
    /// [`Graph::routes_with_profile`](convert_rs_core::Graph::routes_with_profile).
    /// This method performs that profiling step and describes the outcome.
    ///
    /// Runs [`Self::identify`], then asks available adapters that declare the
    /// identified format, in registration order, for [`Adapter::inspect`]. The
    /// first adapter answering `Ok(Some(profile))` whose `profile.format`
    /// matches the identification wins. Adapters that decline (`Ok(None)`),
    /// fail (`Err`), or claim a different format express no opinion; the engine
    /// asks the next one. An inspection exceeding [`Limits::timeout`] is
    /// abandoned and recorded.
    ///
    /// When nobody answered, [`ProfileReport::profile`] is `None`: planning
    /// falls back to declared [`Format::payloads`] unless
    /// [`Policy::require_content`] demands observed evidence.
    ///
    /// # Errors
    ///
    /// As [`Self::identify`]. Adapter failures and timeouts are reported
    /// through [`ProfileReport::source`], never as an error.
    pub async fn profile(&self, path: &Path) -> Result<ProfileReport> {
        let identification = self.identify(path)?;
        let (profile, timed_out) = self.inspect(path, &identification.format).await;
        Ok(ProfileReport {
            source: match (&profile, timed_out) {
                (Some(_), _) => ProfileSource::Observed,
                (None, true) => ProfileSource::Timeout,
                (None, false) => ProfileSource::NoOpinion,
            },
            identification,
            profile,
        })
    }

    /// Ask declaring available adapters for a profile of `path` as `format`.
    ///
    /// Shared by [`Self::profile`] and [`Self::convert`]. Returns the first
    /// well-formed observed profile plus whether any inspection timed out.
    async fn inspect(&self, path: &Path, format: &str) -> (Option<ContentProfile>, bool) {
        let mut timed_out = false;
        for adapter in self.adapters.values() {
            if !adapter.status().available {
                continue;
            }
            if !adapter
                .formats()
                .into_iter()
                .any(|declared| declared.id == format)
            {
                continue;
            }
            let job = adapter.inspect(path, format, &self.limits);
            match tokio::time::timeout(self.limits.timeout, job).await {
                Ok(Some(Ok(mut profile))) if profile.format == format => {
                    profile.deduplicate();
                    return (Some(profile), false);
                }
                Ok(_) => continue,
                Err(_elapsed) => timed_out = true,
            }
        }
        (None, timed_out)
    }

    /// Classify how reachable each target format is from a source format.
    ///
    /// A target is [`CapabilityReason::Planned`] when the current policy and
    /// registered adapters route to it. Otherwise the method re-searches with
    /// every gate open, once restricted to available backends and once without:
    /// a route that only the open search finds is [`CapabilityReason::PolicyBlocked`],
    /// one that needs a registered-but-unavailable or missing backend is
    /// [`CapabilityReason::BackendUnavailable`], and a format nothing routes to
    /// is [`CapabilityReason::NoRoute`]. Planning only; no files are read.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Invalid`] for an unknown source or target format name.
    pub fn capabilities(&self, source: &str, targets: &[String]) -> Result<Vec<TargetCapability>> {
        let source = self
            .graph
            .resolve(source)
            .ok_or_else(|| Error::Invalid(format!("unknown source format: {source}")))?
            .id
            .clone();
        let available: Vec<String> = self
            .adapters
            .values()
            .filter(|adapter| adapter.status().available)
            .map(|adapter| adapter.name().to_owned())
            .collect();
        let unrestricted = Policy {
            allow_bridges: true,
            allow_lossy: true,
            allow_reinterpret: true,
            allow_packaging: true,
            allow_external: true,
            allow_external_packaging: true,
            allow_decode_only: true,
            reencode_same_format: true,
            allow_creative: true,
            ..self.policy.clone()
        };
        let mut reports = Vec::with_capacity(targets.len());
        for target in targets {
            let target = self
                .graph
                .resolve(target)
                .ok_or_else(|| Error::Invalid(format!("unknown target format: {target}")))?
                .id
                .clone();
            reports.push(TargetCapability {
                reason: self.classify(&source, &target, &available, &unrestricted),
                format: target,
            });
        }
        Ok(reports)
    }

    fn classify(
        &self,
        source: &str,
        target: &str,
        available: &[String],
        unrestricted: &Policy,
    ) -> CapabilityReason {
        if let Ok(plans) = self.graph.routes(source, target, &self.policy)
            && let Some(cheapest) = plans.iter().map(|plan| plan.cost).min()
        {
            return CapabilityReason::Planned { cost: cheapest };
        }
        let permissive_available = Policy {
            backends: available.to_vec(),
            ..unrestricted.clone()
        };
        if matches!(
            self.graph.routes(source, target, &permissive_available),
            Ok(plans) if !plans.is_empty()
        ) {
            return CapabilityReason::PolicyBlocked;
        }
        match self.graph.routes(source, target, unrestricted) {
            Ok(plans)
                if plans.iter().any(|plan| {
                    plan.steps
                        .iter()
                        .all(|step| available.iter().any(|backend| backend == &step.backend))
                }) =>
            {
                CapabilityReason::PolicyBlocked
            }
            Ok(plans) => {
                let mut missing: Vec<String> = plans
                    .iter()
                    .flat_map(|plan| plan.steps.iter())
                    .map(|step| step.backend.clone())
                    .filter(|backend| !available.contains(backend))
                    .collect();
                missing.sort();
                missing.dedup();
                CapabilityReason::BackendUnavailable { backends: missing }
            }
            _ => CapabilityReason::NoRoute,
        }
    }

    /// Enumerate policy-filtered routes between two formats.
    ///
    /// Uses the supplied policy, not necessarily [`Self::policy`]. Does not inspect
    /// files or filter by backend availability. See [`Graph::routes`] for ordering,
    /// bounded search, and partial-result behavior.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use convert_rs::{ConversionKind, Converter, Policy};
    /// let converter = Converter::new();
    /// let plans = converter.plan("txt", "bin", converter.policy())?;
    /// assert_eq!(plans[0].steps[0].kind, ConversionKind::Lossless);
    /// assert!(converter.plan("bin", "txt", converter.policy()).is_err());
    /// let policy = Policy { allow_reinterpret: true, ..Policy::default() };
    /// let plans = converter.plan("bin", "txt", &policy)?;
    /// assert_eq!(plans[0].steps[0].operation, "decode-text");
    /// # Ok::<(), convert_rs::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`Error::Plan`] for unknown formats, invalid search settings, no
    /// route, or an exhausted search budget before any route is found.
    pub fn plan(&self, from: &str, to: &str, policy: &Policy) -> Result<Vec<Plan>> {
        Ok(self.graph.routes(from, to, policy)?)
    }

    /// Convert files through the first successful route in the planned set.
    ///
    /// All inputs must resolve to one format. Routes are attempted in cost
    /// order, and every attempt re-stages fresh copies of inputs that adapters
    /// must not mutate. Search is bounded, so not every graph route is attempted.
    /// Backend filtering occurs after this bounded search. A forced plan bypasses
    /// search and is attempted once; see [`ConversionOptions::forced_plan`].
    ///
    /// With normal planning, same-format requests produce staged copies with an
    /// empty plan and no warnings. They do not validate content, re-encode, or
    /// choose codecs. File extensions and overrides are declarations, not decoder validation.
    /// Successful outputs remain temporary until copied out of the report.
    ///
    /// # Execute a reviewed plan
    ///
    /// ```rust
    /// use convert_rs::{ConversionKind, ConversionOptions, Converter, Policy};
    /// # #[tokio::main(flavor = "current_thread")]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let policy = Policy { allow_reinterpret: true, ..Policy::default() };
    /// let converter = Converter::new().with_policy(policy);
    /// let plans = converter.plan("bin", "txt", converter.policy())?;
    /// let chosen = plans.into_iter().next().ok_or("no plan")?;
    /// assert_eq!(chosen.steps[0].kind, ConversionKind::Reinterpret);
    /// let options = ConversionOptions {
    ///     from: Some("bin".into()),
    ///     backend: Some("builtin".into()),
    ///     forced_plan: Some(chosen),
    ///     ..ConversionOptions::default()
    /// };
    /// let inputs = tempfile::tempdir()?;
    /// let source = inputs.path().join("payload");
    /// std::fs::write(&source, "valid UTF-8")?;
    /// let report = converter.convert(&[source], "txt", &options).await?;
    /// assert_eq!(std::fs::read_to_string(&report.artifacts[0].path)?, "valid UTF-8");
    /// assert_eq!(report.warnings[0].kind, ConversionKind::Reinterpret);
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`Error::Invalid`] for empty input lists, unknown overrides or
    /// targets, mixed identified formats, or no route remaining after backend
    /// filtering; [`Error::Limit`] for too many inputs; and identification or
    /// planning errors before execution. Staging, adapter, execution-policy,
    /// and output-validation failures are accumulated into [`Error::RoutesFailed`]
    /// if all attempted routes fail. A successful fallback omits earlier errors.
    pub async fn convert(
        &self,
        paths: &[PathBuf],
        to: &str,
        options: &ConversionOptions,
    ) -> Result<ConversionReport> {
        options.validate()?;
        if paths.is_empty() {
            return Err(Error::Invalid("no input files given".into()));
        }
        if paths.len() > self.limits.max_artifacts {
            return Err(Error::Limit("input file count".into()));
        }
        let target = self
            .graph
            .resolve(to)
            .ok_or_else(|| Error::Invalid(format!("unknown target format: {to}")))?
            .id
            .clone();

        let identification = match &options.from {
            Some(value) => {
                let format = self
                    .graph
                    .resolve(value)
                    .ok_or_else(|| Error::Invalid(format!("unknown source format: {value}")))?
                    .id
                    .clone();
                Identification {
                    format,
                    method: IdentificationMethod::Override,
                }
            }
            None => self.identify(&paths[0])?,
        };
        if options.from.is_none() {
            for path in &paths[1..] {
                let other = self.identify(path)?;
                if other.format != identification.format {
                    return Err(Error::Invalid(format!(
                        "inputs have different formats: {} and {}",
                        identification.format, other.format
                    )));
                }
            }
        }
        let source = identification.format;

        let inspect = options.inspect_content || self.policy.inspect_content;
        let profile = if inspect && options.from.is_none() && options.forced_plan.is_none() {
            self.inspect(&paths[0], &source).await.0
        } else {
            None
        };

        let plans = match &options.forced_plan {
            Some(plan) => vec![plan.clone()],
            None => {
                if source == target && options.reencode {
                    let reencode_policy = Policy {
                        reencode_same_format: true,
                        backends: options.backend.iter().cloned().collect(),
                        retain: normalized_retain(&options.preserve),
                        ..self.policy.clone()
                    };
                    match self.graph.routes_with_profile(
                        &source,
                        &target,
                        &reencode_policy,
                        profile.as_ref(),
                    ) {
                        Ok(plans) => plans,
                        Err(convert_rs_core::PlanError::NoRoute { .. }) => {
                            return Err(Error::Invalid(format!(
                                "no same-format re-encode route exists for {source}; \
                                 the copy path would ignore the reencode request"
                            )));
                        }
                        Err(error) => return Err(error.into()),
                    }
                } else {
                    let mut policy = self.policy.clone();
                    if let Some(backend) = &options.backend {
                        policy.backends = vec![backend.clone()];
                    }
                    if !options.preserve.is_empty() {
                        policy.retain = normalized_retain(&options.preserve);
                    }
                    let search =
                        self.graph
                            .routes_with_profile(&source, &target, &policy, profile.as_ref());
                    match (search, options.backend.as_ref()) {
                        (Ok(plans), _) => plans,
                        (Err(convert_rs_core::PlanError::NoRoute { .. }), Some(backend)) => {
                            return Err(Error::Invalid(format!(
                                "no route from {source} to {target} uses only backend {backend}"
                            )));
                        }
                        (Err(error), _) => return Err(error.into()),
                    }
                }
            }
        };

        let mut attempts: Vec<RouteAttempt> = Vec::new();
        let mut failures = Vec::new();
        let target_format = self.graph.format(&target);
        for plan in plans {
            let forced = options.forced_plan.as_ref().is_some();
            let rejected = options
                .check_forced_retention(&plan)
                .and_then(|()| {
                    if forced {
                        match target_format {
                            Some(format) => options.check_forced_content(
                                &plan,
                                format,
                                profile.as_ref(),
                                &self.policy.require,
                                self.policy.require_content,
                            ),
                            None => Ok(()),
                        }
                    } else {
                        Ok(())
                    }
                })
                .err();
            if let Some(error) = rejected {
                let index = attempts.len();
                attempts.push(RouteAttempt::new(
                    index,
                    render_route(&plan),
                    plan.clone(),
                    Some(error.to_string()),
                ));
                failures.push(format!("{}: {error}", attempts[index].route));
                continue;
            }
            let index = attempts.len();
            let rendered = render_route(&plan);
            let attempt = self.execute(&plan, &source, &target, paths, options).await;
            match attempt {
                Ok(mut report) => {
                    let accepted = RouteAttempt::new(index, rendered, plan.clone(), None);
                    report.attempts = attempts;
                    report.attempts.push(accepted);
                    return Ok(report);
                }
                Err(error) => {
                    attempts.push(RouteAttempt::new(
                        index,
                        rendered,
                        plan.clone(),
                        Some(error.to_string()),
                    ));
                    failures.push(format!("{}: {error}", attempts[index].route));
                }
            }
        }
        Err(Error::RoutesFailed(failures.join("; ")))
    }

    /// Convert one in-memory buffer, returning its converted bytes.
    ///
    /// Writes the input to a staged temporary file, runs
    /// [`Self::convert`] with these options, verifies that exactly one
    /// artifact was produced, and reads it back. The report is dropped
    /// afterwards, so nothing to clean up. Requires a Tokio runtime; use
    /// [`Self::convert_blocking`] from synchronous code.
    ///
    /// # Errors
    ///
    /// Identifies the buffer by content (extension-based lookup cannot apply);
    /// returns [`Error::Conversion`] when a multi-output route (for example
    /// archive extraction) is selected, plus any error from [`Self::convert`].
    pub async fn convert_bytes(
        &self,
        input: &[u8],
        from: &str,
        to: &str,
        options: &ConversionOptions,
    ) -> Result<Vec<u8>> {
        let source_format = self
            .graph
            .resolve(from)
            .ok_or_else(|| Error::Invalid(format!("unknown source format: {from}")))?
            .id
            .clone();
        let workspace = TempDir::new()?;
        let staged_path = workspace.path().join("input");
        std::fs::write(&staged_path, input)?;
        let options = ConversionOptions {
            from: Some(source_format),
            ..options.clone()
        };
        let report = self
            .convert(std::slice::from_ref(&staged_path), to, &options)
            .await?;
        let [artifact] = report.artifacts.as_slice() else {
            return Err(Error::Conversion(format!(
                "route produced {} artifacts; convert_bytes needs exactly one",
                report.artifacts.len()
            )));
        };
        Ok(std::fs::read(&artifact.path)?)
    }

    /// Synchronous [`Self::convert_bytes`] for callers without a Tokio runtime.
    ///
    /// Builds a single-threaded runtime internally and blocks the current
    /// thread; calling it from an existing async context deadlocks.
    ///
    /// # Errors
    ///
    /// As [`Self::convert`], plus [`Error::Invalid`] if the runtime cannot be
    /// constructed (for example nested inside another Tokio runtime).
    pub fn convert_blocking(
        &self,
        input: &[u8],
        from: &str,
        to: &str,
        options: &ConversionOptions,
    ) -> Result<Vec<u8>> {
        let runtime = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .map_err(|error| Error::Invalid(format!("cannot build a blocking runtime: {error}")))?;
        runtime.block_on(self.convert_bytes(input, from, to, options))
    }

    async fn execute(
        &self,
        plan: &Plan,
        source: &str,
        target: &str,
        paths: &[PathBuf],
        options: &ConversionOptions,
    ) -> Result<ConversionReport> {
        let pinned = &options.backend;
        let workspace = TempDir::new()?;
        let mut artifacts = Vec::with_capacity(paths.len());
        for (index, path) in paths.iter().enumerate() {
            artifacts.push(stage_input(
                path,
                workspace.path(),
                index,
                source,
                &self.limits,
            )?);
        }

        let mut warnings = Vec::new();
        let mut costs = Vec::new();
        let mut spent_total = 0u64;
        for (index, step) in plan.steps.iter().enumerate() {
            if !self.policy.allows(step.kind) {
                return Err(Error::Security(format!(
                    "{:?} steps are disabled",
                    step.kind
                )));
            }
            if step.external && !self.policy.allow_external {
                return Err(Error::Security(format!(
                    "{} uses a native external tool; enable Policy::allow_external",
                    step.backend
                )));
            }
            if pinned
                .as_ref()
                .is_some_and(|backend| &step.backend != backend)
            {
                return Err(Error::Invalid("plan uses a disallowed backend".into()));
            }
            if artifacts
                .iter()
                .any(|artifact| artifact.format != step.from)
            {
                return Err(Error::Conversion(format!(
                    "step {index} expected {} inputs",
                    step.from
                )));
            }
            let adapter = self.adapters.get(&step.backend).ok_or_else(|| {
                Error::Conversion(format!("backend {} is not registered", step.backend))
            })?;
            let step_dir = workspace.path().join(step_dir_name(index)?);
            tokio::fs::create_dir_all(&step_dir).await?;
            let request = StepRequest::new(
                artifacts.clone(),
                step_dir.clone(),
                step.from.clone(),
                step.to.clone(),
                step.operation.clone(),
                self.limits.clone(),
            )
            .with_params(&options.params)
            .with_spent_output_bytes(spent_total);
            match adapter.convert(&request).await {
                Ok(produced) => {
                    let (validated, produced_bytes) = validate_artifacts(
                        produced,
                        &step_dir,
                        step,
                        &self.limits,
                        &self.graph,
                        options,
                        &self.adapters,
                    )?;
                    artifacts = validated;
                    spent_total = spent_total.saturating_add(produced_bytes);
                    if self.limits.max_total_output_bytes > 0
                        && spent_total > self.limits.max_total_output_bytes
                    {
                        return Err(Error::Limit(
                            "combined step outputs exceed the total byte budget".into(),
                        ));
                    }
                }
                Err(error) => {
                    let _ = tokio::fs::remove_dir_all(&step_dir).await;
                    return Err(error);
                }
            }
            if let Some(warning) = warning_for(index, step) {
                warnings.push(warning);
            }
            if step.kind != ConversionKind::Lossless {
                costs.push(StepCost::new(
                    index,
                    &step.backend,
                    &step.operation,
                    step.kind,
                    step.cost,
                    step.note.as_deref(),
                ));
            }
        }
        if artifacts.iter().any(|artifact| artifact.format != *target) {
            return Err(Error::Conversion(
                "final artifacts do not match the target".into(),
            ));
        }
        if options.verify && plan.steps.is_empty() {
            let identity = crate::Conversion::new(
                source,
                target,
                "engine",
                "identity",
                crate::ConversionKind::Lossless,
                0,
            );
            for artifact in &artifacts {
                verify_artifact_bytes(
                    &artifact.path,
                    &identity,
                    &self.graph,
                    &self.adapters,
                    &self.limits,
                )?;
            }
        }
        let ignored_params = ignored_param_keys(plan, options, &self.adapters);
        Ok(ConversionReport {
            workspace,
            plan: plan.clone(),
            artifacts,
            warnings,
            costs,
            attempts: Vec::new(),
            ignored_params,
        })
    }
}

/// Requested param keys that no executed step's adapter declared support for.
fn ignored_param_keys(
    plan: &Plan,
    options: &ConversionOptions,
    adapters: &BTreeMap<String, Arc<dyn crate::Adapter>>,
) -> Vec<String> {
    if options.params.is_empty() {
        return Vec::new();
    }
    let mut supported: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
    for step in &plan.steps {
        if let Some(adapter) = adapters.get(&step.backend) {
            supported.extend(
                adapter
                    .param_keys(&step.operation)
                    .iter()
                    .map(|key| key.trim().to_ascii_lowercase()),
            );
        }
    }
    options
        .params
        .keys()
        .filter(|key| !supported.contains(&key.trim().to_ascii_lowercase()))
        .cloned()
        .collect()
}

fn step_dir_name(index: usize) -> Result<String> {
    Ok(format!("step-{index:04}"))
}

/// Lowercase and trim requested retention property names, dropping blanks.
fn normalized_retain(values: &[String]) -> Vec<String> {
    let mut normalized: Vec<String> = values
        .iter()
        .map(|value| value.trim().to_ascii_lowercase())
        .filter(|value| !value.is_empty())
        .collect();
    normalized.sort();
    normalized.dedup();
    normalized
}

/// Render a plan's route as a single line, e.g. `identity` or `a→b via x | b→c via y`.
fn render_route(plan: &Plan) -> String {
    if plan.steps.is_empty() {
        "identity".to_owned()
    } else {
        plan.steps
            .iter()
            .map(|step| format!("{}→{} via {}", step.from, step.to, step.backend))
            .collect::<Vec<_>>()
            .join(" | ")
    }
}

fn warning_for(index: usize, step: &crate::Conversion) -> Option<Warning> {
    let generic = match step.kind {
        ConversionKind::Lossless => return None,
        ConversionKind::Lossy => format!(
            "{} re-encoded through {}; expect quality or metadata loss",
            step.to, step.operation
        ),
        ConversionKind::Reencode => format!(
            "{} re-encoded in place through {}; expect quality or metadata loss",
            step.to, step.operation
        ),
        ConversionKind::Bridge => format!(
            "{} bridged through {}; the result expresses {} differently",
            step.from, step.operation, step.to
        ),
        ConversionKind::Reinterpret => format!(
            "bytes were reinterpreted as {} by {}",
            step.to, step.backend
        ),
        ConversionKind::Package => "files were packaged; contents were not converted".into(),
        ConversionKind::Extract => "archive members were extracted as separate files".into(),
    };
    let message = match &step.note {
        Some(note) => format!("{generic}: {note}"),
        None => generic,
    };
    Some(Warning {
        step: index,
        backend: step.backend.clone(),
        operation: step.operation.clone(),
        kind: step.kind,
        message,
    })
}

/// Candidate suffix lookups for a file name, longest first.
///
/// `archive.tar.gz` yields `["tar.gz", "gz"]`; `note.txt` yields `["txt"]`.
/// Each candidate is matched only when a registered extension equals it, so
/// unknown suffixes fall through to signature detection.
fn extensions_of(path: &Path) -> Vec<String> {
    let Some(name) = path.file_name().and_then(|name| name.to_str()) else {
        return Vec::new();
    };
    let Some(dotted) = name.split_once('.').map(|(_, rest)| rest) else {
        return Vec::new();
    };
    let mut candidates = Vec::new();
    let mut rest = dotted;
    while let Some(index) = rest.rfind('.') {
        candidates.push(rest.to_ascii_lowercase());
        rest = &rest[index + 1..];
    }
    if !rest.is_empty() {
        candidates.push(rest.to_ascii_lowercase());
    }
    candidates
}

fn stage_input(
    path: &Path,
    dir: &Path,
    index: usize,
    format: &str,
    limits: &Limits,
) -> Result<Artifact> {
    let metadata = std::fs::symlink_metadata(path)?;
    if !metadata.file_type().is_file() {
        return Err(Error::Security("input is not a regular file".into()));
    }
    if metadata.len() > limits.max_input_bytes {
        return Err(Error::Limit("input bytes exceed budget".into()));
    }
    let destination = dir.join(format!("input-{index}"));
    std::fs::copy(path, &destination)?;
    let staged = std::fs::symlink_metadata(&destination)?;
    if !staged.file_type().is_file() || staged.len() != metadata.len() {
        return Err(Error::Security("staged input changed during copy".into()));
    }
    Ok(Artifact::new(destination, format.to_owned()))
}

/// Ensure an adapter produced only bounded regular files inside its own step
/// directory and that no intermediate directory contains path-traversal names.
///
/// Returns the validated artifacts and their total byte count so the caller can
/// track the cumulative [`Limits::max_total_output_bytes`] budget.
fn validate_artifacts(
    produced: Vec<Artifact>,
    step_dir: &Path,
    step: &crate::Conversion,
    limits: &Limits,
    graph: &Graph,
    options: &ConversionOptions,
    adapters: &BTreeMap<String, Arc<dyn Adapter>>,
) -> Result<(Vec<Artifact>, u64)> {
    if produced.len() > limits.max_artifacts {
        return Err(Error::Limit("adapter produced too many artifacts".into()));
    }
    let root = step_dir
        .canonicalize()
        .map_err(|_| Error::Security("step directory disappeared".into()))?;
    let mut artifacts = Vec::with_capacity(produced.len());
    let mut total = 0u64;
    for artifact in produced {
        if artifact.format != step.to {
            return Err(Error::Conversion(format!(
                "{} returned a {} artifact for a {} step",
                step.backend, artifact.format, step.to
            )));
        }
        let metadata = std::fs::symlink_metadata(&artifact.path)
            .map_err(|_| Error::Security("adapter artifact does not exist".into()))?;
        if !metadata.file_type().is_file() {
            return Err(Error::Security(
                "adapter returned a non-regular file".into(),
            ));
        }
        let canonical = artifact.path.canonicalize().map_err(|_| {
            Error::Security("adapter returned a path that cannot be resolved".into())
        })?;
        if !canonical.starts_with(&root) {
            return Err(Error::Security(
                "adapter wrote outside its step directory".into(),
            ));
        }
        if options.verify {
            verify_artifact_bytes(&canonical, step, graph, adapters, limits)?;
        }
        total = total
            .checked_add(metadata.len())
            .ok_or_else(|| Error::Limit("artifact byte overflow".into()))?;
        if total > limits.max_output_bytes {
            return Err(Error::Limit("artifact bytes exceed budget".into()));
        }
        let mut validated = Artifact::new(canonical, artifact.format);
        validated.logical_name = artifact.logical_name;
        artifacts.push(validated);
    }
    Ok((artifacts, total))
}

/// Re-sniff an artifact's first bytes and ask available decoders to confirm them.
///
/// Detection covers registered magic signatures; when no signature matches the
/// content, verification defers to the adapters. A signature that resolves to
/// a different registered format is a contradiction and fails the route. After
/// the signature check passes, available adapters that can judge the declared
/// format through [`crate::Adapter::accepts_input`] get a say: `Some(false)`
/// rejects the artifact, and `None` (the default) expresses no opinion.
fn verify_artifact_bytes(
    path: &Path,
    step: &crate::Conversion,
    graph: &Graph,
    adapters: &BTreeMap<String, Arc<dyn Adapter>>,
    limits: &Limits,
) -> Result<()> {
    // bin holds arbitrary bytes and identity relabels are caller assertions;
    // a signature hit on either target is expected, not a contradiction.
    if step.to != "bin"
        && step.from != step.to
        && let Some(contradiction) = sniff_contradiction(path, step, graph)?
    {
        return Err(contradiction);
    }
    for adapter in adapters.values() {
        if adapter.name() == step.backend || !adapter.status().available {
            continue;
        }
        if adapter.accepts_input(path, &step.to, limits) == Some(false) {
            return Err(Error::Conversion(format!(
                "verification failed: {} cannot decode what {} wrote as {}",
                adapter.name(),
                step.backend,
                step.to
            )));
        }
    }
    Ok(())
}

/// Return the error describing a signature contradiction, or `None` when the
/// bytes agree with (or say nothing about) the declared target format.
fn sniff_contradiction(
    path: &Path,
    step: &crate::Conversion,
    graph: &Graph,
) -> Result<Option<Error>> {
    let mut header = [0u8; 1024];
    let mut file = std::fs::File::open(path)
        .map_err(|_| Error::Security("artifact became unreadable during verification".into()))?;
    let count = file.read(&mut header).map_err(|_| {
        Error::Security(format!(
            "artifact {} cannot be re-read for verification",
            path.display()
        ))
    })?;
    if count == 0 {
        return Ok(None);
    }
    let Some(name) = detect(&header[..count]) else {
        return Ok(None);
    };
    let Some(resolved) = graph.resolve(name) else {
        return Ok(None);
    };
    // A compound container is allowed to sniff as its inner format: a valid
    // `tar.gz` file begins with the gzip signature, so `tar.gz` accepts a `gz`
    // detection. Anything else that contradicts the declared format fails.
    if resolved.id == step.to || step.to.ends_with(&format!(".{}", resolved.id)) {
        return Ok(None);
    }
    Ok(Some(Error::Conversion(format!(
        "verification failed: {} wrote a {} file while the step claims {}",
        step.backend, resolved.id, step.to
    ))))
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;

    fn graph_backend_converter() -> Converter {
        Converter::new()
    }

    #[test]
    fn registration_is_idempotent_by_name() {
        let converter = graph_backend_converter();
        assert_eq!(
            converter
                .order
                .iter()
                .filter(|name| name.as_str() == "builtin")
                .count(),
            1
        );
    }

    #[test]
    #[cfg(feature = "media")]
    fn extension_detection_wins_and_magic_is_fallback() {
        let converter = graph_backend_converter();
        let dir = TempDir::new().unwrap();
        std::fs::write(dir.path().join("note.txt"), b"plain text").unwrap();
        assert_eq!(
            converter
                .identify(&dir.path().join("note.txt"))
                .unwrap()
                .method,
            IdentificationMethod::Extension
        );
        std::fs::write(dir.path().join("payload.dat"), b"\x89PNG\r\n\x1a\nxx").unwrap();
        let found = converter.identify(&dir.path().join("payload.dat")).unwrap();
        assert_eq!(found.format, "png");
        assert_eq!(found.method, IdentificationMethod::Magic);
        std::fs::write(dir.path().join("random"), [1, 2, 3, 250, 7]).unwrap();
        let found = converter.identify(&dir.path().join("random")).unwrap();
        assert_eq!(found.format, "bin");
        assert_eq!(found.method, IdentificationMethod::Unknown);
    }

    #[test]
    fn identify_rejects_nonregular_and_empty() {
        let converter = graph_backend_converter();
        let dir = TempDir::new().unwrap();
        std::fs::create_dir(dir.path().join("adir")).unwrap();
        assert!(matches!(
            converter.identify(&dir.path().join("adir")),
            Err(Error::Security(_))
        ));
        std::fs::write(dir.path().join("empty.txt"), b"").unwrap();
        assert!(matches!(
            converter.identify(&dir.path().join("empty.txt")),
            Err(Error::Security(_))
        ));
    }

    #[tokio::test]
    async fn unknown_files_require_reinterpretation_opt_in() {
        let converter = graph_backend_converter();
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("mystery");
        std::fs::write(&path, [7u8; 40]).unwrap();
        let default = converter
            .convert(
                std::slice::from_ref(&path),
                "txt",
                &ConversionOptions::default(),
            )
            .await;
        assert!(matches!(default, Err(Error::Plan(_))), "{default:?}");
        let policy = Policy {
            allow_reinterpret: true,
            ..Policy::default()
        };
        let report = Converter::default()
            .with_policy(policy)
            .convert(&[path], "txt", &ConversionOptions::default())
            .await
            .unwrap();
        assert_eq!(report.plan.steps.len(), 1);
        assert!(
            report
                .warnings
                .iter()
                .any(|warning| warning.kind == ConversionKind::Reinterpret)
        );
    }

    #[tokio::test]
    async fn same_format_requests_stage_a_copy() {
        let converter = graph_backend_converter();
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("data.txt");
        std::fs::write(&path, b"unchanged").unwrap();
        let report = converter
            .convert(&[path], "txt", &ConversionOptions::default())
            .await
            .unwrap();
        assert!(report.plan.steps.is_empty());
        assert_eq!(
            std::fs::read_to_string(&report.artifacts[0].path).unwrap(),
            "unchanged"
        );
    }

    #[tokio::test]
    async fn mixed_format_inputs_are_rejected() {
        let converter = graph_backend_converter();
        let dir = TempDir::new().unwrap();
        std::fs::write(dir.path().join("a.txt"), b"a").unwrap();
        std::fs::write(dir.path().join("b.gz"), b"\x1f\x8brest").unwrap();
        let error = converter
            .convert(
                &[dir.path().join("a.txt"), dir.path().join("b.gz")],
                "tar",
                &ConversionOptions::default(),
            )
            .await
            .err();
        assert!(matches!(error, Some(Error::Invalid(_))));
    }

    #[test]
    fn validating_artifacts_rejects_escapes_and_mismatch() {
        let dir = TempDir::new().unwrap();
        let step_dir = dir.path().join("step");
        std::fs::create_dir(&step_dir).unwrap();
        let step = crate::Conversion::new(
            "a",
            "png",
            "backend",
            "convert",
            ConversionKind::Lossless,
            1,
        );
        let limits = Limits::default();

        let graph = Graph::new();
        let defaults = ConversionOptions::default();
        std::fs::write(dir.path().join("escape.png"), b"x").unwrap();
        let escape = Artifact::new(dir.path().join("escape.png"), "png");
        assert!(matches!(
            validate_artifacts(
                vec![escape],
                &step_dir,
                &step,
                &limits,
                &graph,
                &defaults,
                &BTreeMap::new()
            ),
            Err(Error::Security(_))
        ));

        let directory = Artifact::new(step_dir.clone(), "png");
        assert!(matches!(
            validate_artifacts(
                vec![directory],
                &step_dir,
                &step,
                &limits,
                &graph,
                &defaults,
                &BTreeMap::new(),
            ),
            Err(Error::Security(_))
        ));

        let wrong = Artifact::new(step_dir.join("wrong.jpg"), "jpeg".to_owned());
        std::fs::write(&wrong.path, b"x").unwrap();
        assert!(matches!(
            validate_artifacts(
                vec![wrong],
                &step_dir,
                &step,
                &limits,
                &graph,
                &defaults,
                &BTreeMap::new()
            ),
            Err(Error::Conversion(_))
        ));

        std::fs::write(step_dir.join("real.png"), b"x").unwrap();
        let good = Artifact::new(step_dir.join("real.png"), "png");
        assert_eq!(
            validate_artifacts(
                vec![good],
                &step_dir,
                &step,
                &limits,
                &graph,
                &defaults,
                &BTreeMap::new()
            )
            .unwrap()
            .0
            .len(),
            1
        );
    }

    #[test]
    fn stage_input_rejects_nonregular_and_oversize() {
        let limits = Limits {
            max_input_bytes: 4,
            ..Limits::default()
        };
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("in");
        std::fs::write(&path, b"payload").unwrap();
        assert!(matches!(
            stage_input(&path, dir.path(), 0, "bin", &limits),
            Err(Error::Limit(_))
        ));
        std::fs::create_dir(dir.path().join("adir")).unwrap();
        assert!(matches!(
            stage_input(
                &dir.path().join("adir"),
                dir.path(),
                1,
                "bin",
                &Limits::default()
            ),
            Err(Error::Security(_))
        ));
    }

    #[tokio::test]
    async fn backend_constraint_selects_or_rejects_routes() {
        let converter = graph_backend_converter();
        let dir = TempDir::new().unwrap();
        std::fs::write(dir.path().join("data.txt"), b"[1, 2, 3]").unwrap();
        let options = ConversionOptions {
            from: Some("txt".into()),
            backend: Some("builtin".into()),
            ..ConversionOptions::default()
        };
        let report = converter
            .convert(&[dir.path().join("data.txt")], "csv", &options)
            .await
            .err();
        assert!(report.is_some(),);
    }

    #[test]
    #[cfg(feature = "media")]
    fn graph_routes_honor_policy() {
        let converter = graph_backend_converter();
        let strict = converter
            .plan("bin", "png", &Policy::default())
            .unwrap_err();
        assert!(matches!(
            strict,
            Error::Plan(convert_rs_core::PlanError::NoRoute { .. })
        ));
    }
}