youtube-legend-cli 0.4.0

Non-interactive Rust CLI that downloads YouTube subtitles through third-party providers, using a native Unix stdin/stdout interface.
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
//! Command-line argument parsing via [`clap`] derive.
//!
//! The single entry point is [`Cli`]. Construct one with `Cli::parse()` at
//! the start of `main`, validate it with [`Cli::validate`], then dispatch
//! the rest of the program.

use crate::error::{AppError, AppResult};
use crate::i18n::{t, Language, Message};
use clap::{ArgAction, Parser, ValueEnum};
use serde::{Deserialize, Serialize};
use std::collections::HashSet;
use std::path::PathBuf;
use std::str::FromStr;
use std::sync::{Mutex, OnceLock, PoisonError};
use std::time::Duration;
use unic_langid::subtags::{Language as LanguageSubtag, Region, Script};
use unic_langid::LanguageIdentifier;

mod config_file;
mod output_args;
mod value;

use config_file::invalid_type;
pub use config_file::load_config;
pub use output_args::{ColorArg, LogFormatArg, LogLevelArg};
pub use value::ConfigValue;

/// Output format for the subtitle body.
///
/// `Txt` strips SRT timestamps and joins cues with blank lines. `Srt`
/// returns the raw subtitle text exactly as the provider delivered it.
/// `Vtt` re-frames that same `SubRip` body as `WebVTT`, which the
/// CHANGELOG promised while the enum still rejected it with exit 2.
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
#[non_exhaustive]
pub enum FormatArg {
    /// Plain text with timestamps removed.
    Txt,
    /// Raw `SubRip` text with timestamps preserved.
    Srt,
    /// `WebVTT`, derived from the same `SubRip` body.
    Vtt,
}

/// Legacy ISO 639-1 codes that `YouTube` still uses for caption tracks,
/// paired with the modern code the rest of the world moved to.
///
/// `YouTube` labels Hebrew tracks `iw`, Indonesian `in`, and Yiddish
/// `ji` — the codes ISO withdrew in 1989. An operator who types
/// `--lang he` must still reach the `iw` track, and a track advertised
/// as `iw` must still be reported back as `he`. Both directions go
/// through this table and nowhere else.
const LEGACY_YOUTUBE_CODES: [(&str, &str); 3] = [("he", "iw"), ("id", "in"), ("yi", "ji")];

/// Modern code for a legacy `YouTube` primary subtag, if any.
#[must_use]
fn modern_from_legacy(primary: &str) -> Option<&'static str> {
    LEGACY_YOUTUBE_CODES
        .iter()
        .find(|(_, legacy)| *legacy == primary)
        .map(|(modern, _)| *modern)
}

/// Legacy `YouTube` code for a modern primary subtag, if any.
#[must_use]
fn legacy_from_modern(primary: &str) -> Option<&'static str> {
    LEGACY_YOUTUBE_CODES
        .iter()
        .find(|(modern, _)| *modern == primary)
        .map(|(_, legacy)| *legacy)
}

/// Set of language tags leaked for the lifetime of the process.
///
/// [`LanguageArg`] is `Copy` and hands out `&'static str`, which the
/// whole command layer relies on. A one-shot CLI parses a handful of
/// distinct tags at most, so leaking each *distinct* tag once is
/// bounded and cheaper than threading a lifetime through every call
/// site. The set is what makes it "once": re-parsing `pt-BR` in a loop
/// returns the same pointer instead of leaking again.
static TAG_INTERNER: OnceLock<Mutex<HashSet<&'static str>>> = OnceLock::new();

/// Return a `&'static str` equal to `tag`, allocating at most once per
/// distinct tag for the lifetime of the process.
fn intern_tag(tag: &str) -> &'static str {
    let set = TAG_INTERNER.get_or_init(|| Mutex::new(HashSet::new()));
    let mut guard = set.lock().unwrap_or_else(PoisonError::into_inner);
    if let Some(existing) = guard.get(tag) {
        return existing;
    }
    let leaked: &'static str = Box::leak(tag.to_string().into_boxed_str());
    guard.insert(leaked);
    leaked
}

/// Preferred subtitle language, as a normalised BCP 47 identifier.
///
/// Unlike the six-variant enum this replaced, the type keeps every
/// subtag the operator supplied: `pt-BR` and `pt-PT` stay distinct, and
/// so do `zh-Hans` and `zh-Hant`. That is the whole point — a provider
/// cannot pick between a Brazilian and a European track if the CLI
/// discards the region before the request is built.
///
/// Accepted input shapes are everything an operating system or an
/// operator is likely to produce: `pt-BR`, `pt_BR.UTF-8`, `EN-us`,
/// `zh-Hans-CN`. Normalisation trims, drops the encoding suffix,
/// unifies `_` with `-`, and canonicalises case — it never truncates at
/// the first hyphen.
///
/// Variants (`pt-BR-x-private`) are dropped: no subtitle provider keys
/// tracks on them, and dropping them keeps the type `Copy`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LanguageArg {
    /// Canonical BCP 47 tag, interned for the process lifetime.
    tag: &'static str,
    /// The same tag with the primary subtag rewritten to the legacy
    /// `YouTube` code when one exists. Equal to `tag` otherwise.
    youtube_tag: &'static str,
    language: LanguageSubtag,
    script: Option<Script>,
    region: Option<Region>,
}

impl LanguageArg {
    /// Parse an ISO 639-1 code or a full BCP 47 locale.
    ///
    /// # Errors
    ///
    /// Returns [`AppError::LanguageParseError`] when the input is empty
    /// or is not a well-formed language tag after normalisation.
    pub fn parse(raw: &str) -> AppResult<Self> {
        let normalised = crate::i18n::normalise_locale_string(raw);
        if normalised.is_empty() {
            return Err(AppError::LanguageParseError(format!(
                "{raw:?}: {}",
                t(Message::LangInvalidTag)
            )));
        }
        let langid = LanguageIdentifier::from_str(&normalised).map_err(|e| {
            AppError::LanguageParseError(format!("{raw}: {} ({e})", t(Message::LangInvalidTag)))
        })?;
        Ok(Self::from_langid(&langid))
    }

    /// Build from an already-parsed identifier, folding legacy
    /// `YouTube` codes onto their modern equivalent.
    fn from_langid(langid: &LanguageIdentifier) -> Self {
        let raw_primary = langid.language.as_str().to_ascii_lowercase();
        let modern_primary = modern_from_legacy(&raw_primary).unwrap_or(raw_primary.as_str());
        // A three-letter-or-shorter ASCII subtag that already parsed as
        // a `LanguageIdentifier` always re-parses, so the fallback is
        // unreachable in practice and never panics.
        let language = LanguageSubtag::from_str(modern_primary).unwrap_or(langid.language);
        let script = langid.script;
        let region = langid.region;

        let canonical = LanguageIdentifier::from_parts(language, script, region, &[]);
        let tag = intern_tag(&canonical.to_string());

        let youtube_tag = match legacy_from_modern(modern_primary) {
            Some(legacy) => {
                let mut rebuilt = String::from(legacy);
                if let Some(s) = script {
                    rebuilt.push('-');
                    rebuilt.push_str(s.as_str());
                }
                if let Some(r) = region {
                    rebuilt.push('-');
                    rebuilt.push_str(r.as_str());
                }
                intern_tag(&rebuilt)
            }
            None => tag,
        };

        Self {
            tag,
            youtube_tag,
            language,
            script,
            region,
        }
    }

    /// English, the built-in default and the negotiation fallback.
    #[must_use]
    pub fn english() -> Self {
        Self::from_langid(&LanguageIdentifier::from_parts(
            LanguageSubtag::from_str("en").unwrap_or_default(),
            None,
            None,
            &[],
        ))
    }

    /// Canonical BCP 47 tag, for example `pt-BR` or `zh-Hant-TW`.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        self.tag
    }

    /// The tag as `YouTube` spells it: identical to [`LanguageArg::as_str`]
    /// except for Hebrew, Indonesian and Yiddish, where the legacy ISO
    /// code is used.
    #[must_use]
    pub fn youtube_code(self) -> &'static str {
        self.youtube_tag
    }

    /// Primary subtag alone (`pt` for `pt-BR`).
    #[must_use]
    pub fn primary(self) -> String {
        self.language.as_str().to_string()
    }

    /// Script subtag, when the operator supplied one.
    #[must_use]
    pub fn script(self) -> Option<Script> {
        self.script
    }

    /// Region subtag, when the operator supplied one.
    #[must_use]
    pub fn region(self) -> Option<Region> {
        self.region
    }

    /// Rebuild the underlying identifier, for locale negotiation.
    #[must_use]
    pub fn to_langid(self) -> LanguageIdentifier {
        LanguageIdentifier::from_parts(self.language, self.script, self.region, &[])
    }
}

impl std::fmt::Display for LanguageArg {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.tag)
    }
}

impl FromStr for LanguageArg {
    type Err = AppError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::parse(s)
    }
}

/// Provider selection strategy for the subtitle-fetch chain.
///
/// `auto` walks the full chain in cost order and is what most callers
/// want. Pinning a single provider is useful when diagnosing which
/// upstream is degraded, because the chain stops masking one failure
/// behind the next provider's success.
///
/// The chain order under `auto` is deliberate. `provider-decopy` leads
/// and `provider-noiz` follows, because both enforce a small daily
/// quota and answer `429` once it is spent, and decopy's is the larger
/// of the two.
///
/// Two browser-driven providers led this chain until 2026-09-04 and
/// were removed that day, measured broken at the source rather than
/// merely degraded. Their variants left the enum with them: a value
/// `clap` accepts and the chain silently ignores is worse than a value
/// `clap` rejects, because the first fails at the end of a run and the
/// second fails at the argument.
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum, Serialize, Deserialize)]
#[non_exhaustive]
pub enum ProviderChoice {
    /// Walk the whole chain in cost order.
    Auto,
    /// Pin the decopy.ai provider. Native track only, no language choice.
    ProviderDecopy,
    /// Pin the noiz.io provider. Subject to a five-per-day quota.
    ProviderNoiz,
}

impl ProviderChoice {
    /// Lowercase kebab-case identifier used in TOML and tracing.
    #[must_use]
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Auto => "auto",
            Self::ProviderDecopy => "provider-decopy",
            Self::ProviderNoiz => "provider-noiz",
        }
    }
}

/// Parsed command-line arguments. See `youtube-legend-cli --help` for the
/// rendered help text and the README for the long-form documentation.
#[doc(alias = "Args")]
#[doc(alias = "arguments")]
#[doc(alias = "parser")]
#[doc(alias = "CLI")]
#[doc(alias = "command-line")]
#[doc(alias = "clap")]
#[doc(alias = "argument parser")]
#[derive(Debug, Parser, Clone)]
#[command(
    name = "youtube-legend-cli",
    version,
    about = "Non-interactive Rust CLI that downloads YouTube subtitles via third-party providers using a native Unix stdin/stdout interface.",
    long_about = None,
    propagate_version = true,
    disable_help_subcommand = true,
    // The positional URL is optional, so a subcommand never has to
    // compete with a required argument. Declaring it keeps `config …`
    // parsing unchanged if a future flag becomes required.
    subcommand_negates_reqs = true,
    after_help = "Examples:\n  youtube-legend-cli https://youtu.be/dQw4w9WgXcQ\n  echo \"https://youtu.be/dQw4w9WgXcQ\" | youtube-legend-cli --format srt\n  cat urls.txt | youtube-legend-cli --batch --json\n  youtube-legend-cli --lang pt --timeout 60 https://youtu.be/dQw4w9WgXcQ",
)]
pub struct Cli {
    /// `YouTube` URL in any of the supported forms (watch, shorts,
    /// embed, youtu.be). Omit when piping a URL through stdin or when
    /// using `--batch`.
    #[arg(
        value_name = "URL",
        help = "YouTube URL (watch, shorts, embed, or youtu.be)"
    )]
    pub url: Option<String>,

    /// Preferred subtitle language. Accepts ISO 639-1 codes or full
    /// BCP 47 locales; script and region are preserved and used to pick
    /// the track.
    #[arg(
        long,
        value_name = "LANG",
        help = "Preferred subtitle language, ISO 639-1 or BCP 47 (en, pt-BR, pt-PT, zh-Hans, zh-Hant)",
        default_value = "en",
        value_parser = parse_language
    )]
    pub lang: LanguageArg,

    /// Interface language for human-facing messages on stderr. When
    /// omitted, the config file decides; failing that, the operating
    /// system locale; failing that, English.
    #[arg(
        long,
        value_name = "LANG",
        help = "Interface language for messages on stderr (see --help for the compiled list)",
        value_parser = parse_ui_language
    )]
    pub ui_lang: Option<Language>,

    // The caveat that used to sit in the doc comment named a provider
    // whose bodies carried no cue framing, and that provider was removed
    // on 2026-09-04. The restriction survives only for a CACHED body
    // written under it, where `srt` and `vtt` are refused with the reason
    // stated; a live fetch has no such limit.
    //
    // This explanation is a PLAIN comment and not a doc comment on
    // purpose. MEASURED here: a multi-paragraph doc comment becomes the
    // long help, which then shadows the `help` string below, and the gate
    // `every_documented_format_is_accepted_and_no_other_is` looks for the
    // literal `Output format:` that only the `help` string carries.
    /// Output format: `txt` strips timestamps; `srt` and `vtt` preserve them.
    #[arg(
        long,
        value_name = "FORMAT",
        help = "Output format: txt (default), srt or vtt",
        default_value = "txt"
    )]
    pub format: FormatArg,

    /// Ceiling for the whole operation, in seconds.
    ///
    /// This is *not* an HTTP request timeout: it wraps the entire
    /// provider chain and every retry inside it. Per-request ceilings
    /// live in the configuration registry under `providers.*`, and the
    /// retry and rate-limit ceilings live under `net.retry.*`.
    ///
    /// The default was 30 s and it was shorter than a single provider
    /// phase, so the operation ceiling fired before any upstream could
    /// answer and the resulting failure was blamed on the provider. A
    /// successful end-to-end run was measured at 101 s, so the default is
    /// now 300 s: high enough that only a genuinely stuck run hits it.
    ///
    /// This paragraph cited `providers.noteey.poll_limit_secs` and a
    /// `browser.*` namespace until 2026-09-04. Neither exists: the two
    /// browser-driven providers were removed and their configuration
    /// went with them, so the text named keys `config list-keys` does
    /// not print. Cite a namespace only after reading that command.
    #[arg(
        long,
        value_name = "SECONDS",
        help = "Whole-operation timeout in seconds (not per HTTP request)",
        default_value_t = 300
    )]
    pub timeout: u64,

    /// Emit tracing events at info level to stderr.
    #[arg(
        long,
        action = ArgAction::SetTrue,
        help = "Emit tracing events to stderr"
    )]
    pub verbose: bool,

    /// Suppress all non-error output on stderr.
    #[arg(
        long,
        action = ArgAction::SetTrue,
        help = "Suppress all stderr output except errors"
    )]
    pub quiet: bool,

    /// Path to a TOML config file. When set, flags in the config are
    /// applied first and CLI flags override the config values.
    #[arg(long, value_name = "PATH", help = "Path to a TOML config file")]
    pub config: Option<PathBuf>,

    /// Tracing log level. Falls back to the `log_level` config key when
    /// unset; default `warn` matches the `tracing-subscriber` baseline.
    ///
    /// `RUST_LOG` was the fallback here until 2026-08-31 and is not any
    /// more: no environment variable governs this any longer.
    #[arg(
        long,
        value_name = "LEVEL",
        help = "Log level: error, warn, info, debug, trace",
        default_value = "warn",
        value_enum
    )]
    pub log_level: LogLevelArg,

    /// Log output format. `json` is suitable for ingestion by log
    /// aggregators; `text` is the human-readable default.
    #[arg(
        long,
        value_name = "FORMAT",
        help = "Log format: text (default) or json",
        default_value = "text",
        value_enum
    )]
    pub log_format: LogFormatArg,

    /// ANSI colour policy. `auto` (the default) decides from TTY
    /// detection; no environment variable is consulted.
    #[arg(
        long,
        value_name = "WHEN",
        help = "Colour output: auto, always, never",
        default_value = "auto",
        value_enum
    )]
    pub color: ColorArg,

    /// Disable progress bars and spinners on stderr.
    #[arg(
        long,
        action = ArgAction::SetTrue,
        help = "Suppress progress bars on stderr"
    )]
    pub no_progress: bool,

    /// Run without making any network requests. Reads are served from
    /// the local cache only; writes still update the cache.
    #[arg(
        long,
        action = ArgAction::SetTrue,
        help = "Skip network I/O and serve reads from cache only"
    )]
    pub dry_run: bool,

    /// Assume "yes" for any interactive confirmation prompt.
    #[arg(
        long,
        action = ArgAction::SetTrue,
        help = "Assume yes for any confirmation prompt"
    )]
    pub yes: bool,

    /// Emit a single JSON object to stdout instead of the raw subtitle.
    #[arg(
        long,
        action = ArgAction::SetTrue,
        help = "Emit structured JSON to stdout"
    )]
    pub json: bool,

    /// Read multiple URLs from stdin, one per line, and emit a
    /// concatenated or JSON-per-line result.
    #[arg(
        long,
        action = ArgAction::SetTrue,
        help = "Read multiple URLs from stdin, one per line"
    )]
    pub batch: bool,

    /// Skip URLs whose output a previous `--batch` run already emitted.
    ///
    /// Without this flag a run starts clean and forgets what any
    /// earlier run finished, which is the behaviour every existing
    /// script already depends on. `requires` is delegated to `clap`
    /// rather than re-stated in `validate`, so the refusal message is
    /// the one `clap` already translates instead of a thirteenth
    /// catalogue entry saying the same thing.
    #[arg(
        long,
        action = ArgAction::SetTrue,
        requires = "batch",
        help = "Skip URLs already completed by a previous --batch run"
    )]
    pub resume: bool,

    /// Refuse every outbound request and serve reads from the local
    /// cache only.
    ///
    /// Distinct from `--dry-run`, which reports what it *would* fetch:
    /// `--offline` still answers from cache, it just never opens a
    /// socket or launches a browser.
    #[arg(
        long,
        action = ArgAction::SetTrue,
        help = "Refuse every outbound request; serve cache only"
    )]
    pub offline: bool,

    // `--asr` stood here and was removed on 2026-09-04, together with
    // the `asr` configuration key and the `asr_preference_inert`
    // warning. It expressed a PREFERENCE between two tracks of one
    // language, and the only provider that ever presented two was
    // removed the same day: the survivors return exactly one track
    // each, so the tie-break has nothing to break. Keeping a flag the
    // binary accepts and can never honour is a promise it does not
    // keep, and the warning it emitted only documented the broken
    // promise instead of withdrawing it.
    /// How many batch items are processed concurrently.
    ///
    /// `0` means "derive it from the host", which is
    /// [`std::thread::available_parallelism`] capped by the
    /// `cli.max_jobs` configuration key. Outside `--batch` the value
    /// is unused: a single URL is one item.
    #[arg(
        long,
        value_name = "N",
        help = "Batch items processed concurrently (0 = derive from the host)",
        default_value_t = 0
    )]
    pub jobs: u64,

    /// Override the User-Agent header used by both providers.
    #[arg(
        long,
        value_name = "STRING",
        help = "Custom User-Agent for HTTP requests"
    )]
    pub user_agent: Option<String>,

    /// Cache TTL in hours. Expired entries are removed on read.
    #[arg(
        long,
        value_name = "HOURS",
        help = "Local cache TTL in hours",
        default_value_t = crate::cache::DEFAULT_TTL_HOURS
    )]
    pub cache_ttl: u64,

    /// Skip cache reads (cache writes still happen).
    #[arg(
        long,
        action = ArgAction::SetTrue,
        help = "Disable reads from the local cache"
    )]
    pub no_cache: bool,

    /// Provider selection.
    ///
    /// `auto` is the default and walks the whole chain in cost order.
    /// Pinning one provider names that provider and nothing else.
    ///
    /// No list of accepted values here on purpose. The comment below
    /// gives the reason, and this doc comment was itself the drift it
    /// warns about: it still said the flag resolved to one provider
    /// long after the enum had grown past it.
    #[arg(
        long,
        value_name = "PROVIDER",
        // Do not enumerate the variants here. `value_enum` already
        // prints all five with their own doc comments right below this
        // line, and a hand-written list is a second copy that drifts:
        // this one still advertised two providers after the enum grew
        // to five.
        help = "Which provider to use; see the values below",
        default_value = "auto",
        value_enum
    )]
    pub provider: Option<ProviderChoice>,

    /// Refuse to read stdin. Fails immediately instead of blocking on a
    /// handle that will never deliver data.
    #[arg(
        long,
        action = ArgAction::SetTrue,
        help = "Refuse stdin; fail fast instead of blocking"
    )]
    pub no_input: bool,

    /// Emit the JSON Schema of every output surface and exit.
    #[arg(
        long,
        action = ArgAction::SetTrue,
        help = "Print the JSON Schema of every output surface and exit"
    )]
    pub print_schema: bool,

    /// Keep only these dotted keys in each emitted element.
    #[arg(
        long,
        visible_alias = "fields",
        value_name = "KEYS",
        value_delimiter = ',',
        help = "Keep only these dotted keys (comma-separated)"
    )]
    pub select: Vec<String>,

    /// Filter emitted elements. Repeatable; expressions conjoin with AND.
    #[arg(
        long,
        value_name = "EXPR",
        help = "Filter elements: key=value, key!=value, key~substring"
    )]
    pub filter: Vec<String>,

    /// Cap the number of elements emitted.
    #[arg(long, value_name = "N", help = "Emit at most N elements")]
    pub limit: Option<usize>,

    /// Sort emitted elements ascending by a dotted key.
    #[arg(long, value_name = "KEY", help = "Sort ascending by a dotted key")]
    pub sort: Option<String>,

    /// Drop later elements repeating a dotted key's value.
    #[arg(
        long,
        value_name = "KEY",
        help = "Drop later elements repeating this key's value"
    )]
    pub dedupe_by: Option<String>,

    /// Replace the payload with `{"count": N}`.
    #[arg(
        long,
        action = ArgAction::SetTrue,
        help = "Replace the payload with a count"
    )]
    pub count_only: bool,

    /// Shorten every string above N characters.
    #[arg(
        long,
        value_name = "N",
        help = "Shorten strings above N characters (never bytes)"
    )]
    pub truncate_content: Option<usize>,

    /// Cap the serialised envelope, dropping whole elements from the end.
    #[arg(
        long,
        value_name = "N",
        help = "Cap the envelope at N bytes by dropping whole elements"
    )]
    pub max_output_bytes: Option<usize>,

    /// Configuration management. Absent for the normal extraction path.
    #[command(subcommand)]
    pub command: Option<Command>,
}

/// Subcommands that manage persisted configuration instead of fetching
/// a subtitle.
#[derive(Debug, Clone, clap::Subcommand)]
#[non_exhaustive]
pub enum Command {
    // This line said "the XDG configuration file" until 2026-09-04, and
    // XDG is the layout of exactly one of the three supported hosts.
    // MEASURED that day: `config path` on macOS returns
    // `~/Library/Application Support/com.youtube-legend-cli.youtube-legend-cli/config.toml`,
    // and setting `XDG_CONFIG_HOME` there changes nothing, because the
    // `directories` crate reads the XDG variables on Linux ONLY. An
    // operator who trusted the word "XDG" would point the variable at a
    // path the binary never reads and conclude the setting was ignored.
    //
    // The explanation lives in a `//` comment and the doc comment stays
    // ONE line on purpose: in `clap` derive a multi-paragraph doc
    // comment becomes `long_help` and SHADOWS `help` in the subcommand
    // list, which is the trap GAP-2026-219 recorded.
    /// Inspect and edit the configuration file.
    Config {
        /// The configuration action to perform.
        #[command(subcommand)]
        action: ConfigAction,
    },
    /// Print the shell completion script for SHELL on stdout.
    Completions {
        /// Target shell.
        shell: clap_complete::Shell,
    },
    /// Print the section 1 manual page on stdout, in roff format.
    Man,
}

/// Actions accepted by the `config` subcommand.
#[derive(Debug, Clone, clap::Subcommand)]
#[non_exhaustive]
pub enum ConfigAction {
    /// Print the absolute path of the configuration file.
    Path,
    /// Print every key currently set, in dotted form.
    Show,
    /// Print the value of one key.
    Get {
        /// Dotted key name.
        key: String,
    },
    /// Set one key, validated against the registry.
    Set {
        /// Dotted key name.
        key: String,
        /// New value. Omit when reading the value from stdin.
        value: Option<String>,
        /// Read the value from stdin instead of argv.
        ///
        /// Mandatory for a key marked secret: argv is visible in the
        /// process table to every user on the host.
        #[arg(long, action = ArgAction::SetTrue)]
        from_stdin: bool,
    },
    /// Remove one key, restoring the compiled default.
    Unset {
        /// Dotted key name.
        key: String,
    },
    /// Print the whole registry: key, type and description.
    ListKeys,
}

impl Cli {
    /// Resolve the timeout as a [`Duration`].
    pub fn timeout_duration(&self) -> Duration {
        Duration::from_secs(self.timeout)
    }

    /// Resolve the cache TTL as a [`Duration`].
    pub fn cache_ttl_duration(&self) -> Duration {
        crate::cache::ttl_from_hours(self.cache_ttl)
    }

    /// User-Agent header value, falling back to the crate default.
    pub fn effective_user_agent(&self) -> String {
        self.user_agent
            .clone()
            .unwrap_or_else(|| crate::net::DEFAULT_USER_AGENT.to_string())
    }

    /// Resolve the effective log level. Honours `--verbose` when the
    /// flag is at its default value.
    ///
    /// `RUST_LOG` was consulted here until 2026-08-31. It is gone: this
    /// product resolves runtime configuration from the command line and
    /// from the XDG file, never from the environment. An inherited
    /// `RUST_LOG` also overrode `--log-level` invisibly. Set the
    /// `log_level` key, or pass `--log-level`.
    pub fn effective_log_level(&self) -> LogLevelArg {
        if self.log_level != LogLevelArg::Warn {
            return self.log_level;
        }
        // GAP-AUD-2026-066: --verbose bumps to info when --log-level
        // was not explicitly set.
        if self.verbose {
            return LogLevelArg::Info;
        }
        self.log_level
    }

    /// Resolve the effective log format. Defaults to `text`.
    pub fn effective_log_format(&self) -> LogFormatArg {
        self.log_format
    }

    /// Resolve the effective colour policy.
    ///
    /// The `color` configuration key and the `--color` flag are the only
    /// governors. `NO_COLOR` and `CLICOLOR_FORCE` were consulted here
    /// until 2026-08-31; both are gone, because an exported value in the
    /// operator's shell silently overrode a policy that `config
    /// list-keys` reports and `config set color` owns.
    pub fn effective_color(&self) -> ColorArg {
        self.color
    }

    /// Exports nothing. Kept as the named step `main` runs between the
    /// config merge and [`crate::logging::init_tracing`].
    ///
    /// Until 2026-08-31 this method wrote `NO_COLOR` or `CLICOLOR_FORCE`
    /// into the process environment so a third-party crate would read
    /// the resolved policy back out. Mutating a process-global to talk
    /// to a library is a channel nothing declares and nothing can
    /// inspect: the value also leaked into every child process this CLI
    /// spawns, including the browser. The colour policy now travels by
    /// value — [`Cli::effective_color`] returns it and `init_tracing`
    /// takes it as an argument.
    ///
    /// The four product variables this method exported before that —
    /// `YT_LOG_LEVEL`, `YT_LOG_FORMAT`, `YT_NO_PROGRESS` and
    /// `YT_DRY_RUN` — were removed earlier, for the same reason.
    pub fn apply_overrides(&self) {}

    /// Build the agent-native reduction options from the parsed flags.
    ///
    /// # Errors
    ///
    /// Returns [`AppError::InvalidUsage`] when a `--filter` expression is
    /// malformed. A bad filter is a usage error, never a silently empty
    /// result set.
    pub fn surface_options(&self) -> AppResult<crate::surface::SurfaceOptions> {
        let mut filters = Vec::with_capacity(self.filter.len());
        for raw in &self.filter {
            filters.push(crate::surface::Filter::parse(raw)?);
        }
        Ok(crate::surface::SurfaceOptions {
            select: self.select.clone(),
            filters,
            limit: self.limit,
            sort: self.sort.clone(),
            dedupe_by: self.dedupe_by.clone(),
            count_only: self.count_only,
            truncate_content: self.truncate_content,
            max_output_bytes: self.max_output_bytes,
        })
    }
}

/// Declare, exactly once, every field that participates in the
/// CLI ↔ config merge.
///
/// Three structures used to repeat the same eighteen field names and had
/// to be edited in lock-step whenever a flag was added: the "was it typed
/// on the command line?" bitmask, the config-file override struct, and
/// the merge itself. A field forgotten in any one of them produced a flag
/// that silently ignored the config file. This macro generates all three
/// from one list, so forgetting a field is no longer possible.
///
/// The groups differ only in how the value is parsed and assigned:
///
/// - `opt_str` — a `String` stored in an `Option<String>` field.
/// - `int` — a TOML integer stored in a plain `u64` field.
/// - `flag` — a TOML boolean stored in a plain `bool` field.
/// - `val` — a [`ConfigValue`] stored in a plain field.
/// - `opt_val` — a [`ConfigValue`] stored in an `Option<_>` field.
macro_rules! config_schema {
    (
        opt_str { $($os:ident),* $(,)? }
        int { $($n:ident),* $(,)? }
        flag { $($bl:ident),* $(,)? }
        val { $($vp:ident : $vpt:ty),* $(,)? }
        opt_val { $($vo:ident : $vot:ty),* $(,)? }
    ) => {
        /// Field-level overrides loaded from a TOML config file.
        ///
        /// Each `Option<T>` is `Some` only when the operator actually set
        /// the key; `None` means "use the built-in default". This shape
        /// lets [`Cli::apply_config_overrides`] tell "set in config"
        /// apart from "not set" without sentinel values.
        #[derive(Debug, Default, Clone)]
        #[non_exhaustive]
        #[allow(missing_docs)]
        pub struct ConfigOverrides {
            $(pub $os: Option<String>,)*
            $(pub $n: Option<u64>,)*
            $(pub $bl: Option<bool>,)*
            $(pub $vp: Option<$vpt>,)*
            $(pub $vo: Option<$vot>,)*
        }

        /// Per-flag "was this set on the command line?" bitmask.
        ///
        /// Populated from `ArgMatches::value_source` so the config-file
        /// merge can tell apart "operator omitted the flag" from
        /// "operator passed the flag with the built-in default value".
        /// The previous sentinel logic compared the parsed field against
        /// its default literal (`if self.timeout == 30`), which silently
        /// let `timeout = 99` from the config override an explicit
        /// `--timeout 30`.
        #[derive(Debug, Clone, Default)]
        #[non_exhaustive]
        #[allow(missing_docs)]
        pub struct CliOverrideFlags {
            $(pub $os: bool,)*
            $(pub $n: bool,)*
            $(pub $bl: bool,)*
            $(pub $vp: bool,)*
            $(pub $vo: bool,)*
        }

        impl CliOverrideFlags {
            /// Read the value source of every merged field.
            #[must_use]
            pub fn from_matches(matches: &clap::ArgMatches) -> Self {
                use clap::parser::ValueSource;
                let src = |id: &str| matches.value_source(id) == Some(ValueSource::CommandLine);
                Self {
                    $($os: src(stringify!($os)),)*
                    $($n: src(stringify!($n)),)*
                    $($bl: src(stringify!($bl)),)*
                    $($vp: src(stringify!($vp)),)*
                    $($vo: src(stringify!($vo)),)*
                }
            }
        }

        /// Every config-file key that mirrors a CLI flag, sorted.
        #[must_use]
        pub fn config_flag_keys() -> Vec<&'static str> {
            let mut keys = vec![
                $(stringify!($os),)*
                $(stringify!($n),)*
                $(stringify!($bl),)*
                $(stringify!($vp),)*
                $(stringify!($vo),)*
            ];
            keys.sort_unstable();
            keys
        }

        /// Absorb one `key = value` pair into `out`.
        ///
        /// Returns `Ok(false)` when the key belongs to no CLI flag, which
        /// lets the caller decide whether it is a tuning namespace or a
        /// typo.
        fn absorb_config_key(
            key: &str,
            value: &toml::Value,
            out: &mut ConfigOverrides,
        ) -> AppResult<bool> {
            match key {
                $(stringify!($os) => {
                    out.$os = Some(
                        value.as_str().ok_or_else(|| invalid_type(key, "string"))?.to_string(),
                    );
                })*
                $(stringify!($n) => {
                    let raw = value.as_integer().ok_or_else(|| invalid_type(key, "integer"))?;
                    out.$n = Some(u64::try_from(raw).map_err(|_| invalid_type(key, "integer"))?);
                })*
                $(stringify!($bl) => {
                    out.$bl = Some(value.as_bool().ok_or_else(|| invalid_type(key, "boolean"))?);
                })*
                $(stringify!($vp) => {
                    let raw = value.as_str().ok_or_else(|| invalid_type(key, "string"))?;
                    out.$vp = Some(<$vpt as ConfigValue>::from_config_str(raw)?);
                })*
                $(stringify!($vo) => {
                    let raw = value.as_str().ok_or_else(|| invalid_type(key, "string"))?;
                    out.$vo = Some(<$vot as ConfigValue>::from_config_str(raw)?);
                })*
                _ => return Ok(false),
            }
            Ok(true)
        }

        impl Cli {
            /// Merge config-file overrides into a freshly-parsed [`Cli`].
            ///
            /// CLI flags always win: a field the operator set on the
            /// command line (recorded in [`CliOverrideFlags`]) is left
            /// alone, and only omitted fields take the config value.
            pub fn apply_config_overrides(
                &mut self,
                cfg: ConfigOverrides,
                flags: &CliOverrideFlags,
            ) {
                $(if !flags.$os {
                    if let Some(v) = cfg.$os { self.$os = Some(v); }
                })*
                $(if !flags.$n {
                    if let Some(v) = cfg.$n { self.$n = v; }
                })*
                $(if !flags.$bl {
                    if let Some(v) = cfg.$bl { self.$bl = v; }
                })*
                $(if !flags.$vp {
                    if let Some(v) = cfg.$vp { self.$vp = v; }
                })*
                $(if !flags.$vo {
                    if let Some(v) = cfg.$vo { self.$vo = Some(v); }
                })*
            }
        }
    };
}

config_schema! {
    opt_str { url, user_agent }
    int { timeout, cache_ttl, jobs }
    flag {
        verbose, quiet, json, batch, no_cache, dry_run, no_progress, yes, no_input,
        offline
    }
    val {
        lang: LanguageArg,
        format: FormatArg,
        log_level: LogLevelArg,
        log_format: LogFormatArg,
        color: ColorArg
    }
    opt_val { ui_lang: Language, provider: ProviderChoice }
}

/// Top-level table names reserved for tuning keys.
///
/// A tuning key is a constant that used to be hard-coded in the source.
/// It lives in the same `config.toml` but under its own namespace.
///
/// A name here must never also exist as a flat key that mirrors a CLI
/// flag. `batch` was both until 0.3.5, and the consequence was silent:
/// the registry declared `batch` as a boolean, so a `[batch]` table was
/// rejected as a malformed boolean before the registry was consulted,
/// and `batch.max_jobs` could not be reached from the file at all. That
/// key now lives under `cli`, and `no_tuning_namespace_shadows_a_flat_key`
/// is what keeps the collision from coming back.
/// `stealth` earns its own namespace rather than folding into an
/// existing one because the seed it carries outranks all of them: it
/// governs the browser fingerprint, the input timings AND the multipart
/// boundary of `provider-decopy`, which opens no browser at all. Filing
/// it under `browser` or `input` would name a scope narrower than the
/// one it actually has.
const TUNING_NAMESPACES: [&str; 8] = [
    "cli",
    "cache",
    "i18n",
    "net",
    "browser",
    "input",
    "providers",
    "stealth",
];

/// Parse the CLI and return both the populated [`Cli`] and a
/// [`CliOverrideFlags`] bitmask describing which flags the user
/// supplied on the command line (vs which the parser filled from
/// the `default_value` directive). Calling this in `main` is
/// strictly equivalent to `Cli::parse()` for the populated `Cli`,
/// but the additional flag tracking is required to make the
/// config↔CLI merge deterministic.
///
/// # Errors
///
/// - Any error `Cli::parse()` would produce: argument parse errors,
///   conflicting flags rejected by `clap`, invalid value parsers.
pub fn parse_with_overrides() -> Result<(Cli, CliOverrideFlags), clap::Error> {
    let cmd = <Cli as clap::CommandFactory>::command();
    // `try_get_matches_from` consumes its argv argument; we pass a
    // fresh iterator each call so the function can be invoked more than
    // once in the same process (e.g. in tests).
    //
    // The fallible form is what makes the declared `clap::Error` return
    // reachable: `get_matches_from` printed the diagnosis itself and
    // ended the process through `std::process::exit`, so the caller
    // never saw the error, never got to emit the `--json` envelope, and
    // every `Drop` on the way out was skipped.
    let matches = cmd.try_get_matches_from(std::env::args_os())?;
    let flags = CliOverrideFlags::from_matches(&matches);
    let cli = <Cli as clap::FromArgMatches>::from_arg_matches(&matches)?;
    Ok((cli, flags))
}

impl Cli {
    /// Reject combinations of flags that would be impossible or surprising
    /// to execute. Returns [`AppError::InvalidUsage`] on the first
    /// impossibility.
    ///
    /// GAP-E2E-015: the previous signature returned `Result<(), String>`
    /// and forced every caller to bridge the `String → AppError` gap.
    /// Returning the typed error directly removes the bridge and
    /// keeps the canonic rule "domain functions return
    /// `Result<T, AppError>`".
    ///
    /// # Errors
    ///
    /// Returns [`AppError::InvalidUsage`] when a flag combination is
    /// impossible:
    ///
    /// - `--batch` combined with a positional URL
    /// - no URL, no stdin pipe, and no `--batch`
    pub fn validate(&self) -> AppResult<()> {
        if self.batch && self.url.is_some() {
            return Err(usage(Message::UsageBatchWithUrl));
        }
        if self.url.is_none() && is_stdin_tty_or_blocked() && !self.batch {
            return Err(usage(Message::UsageNoUrl));
        }
        if self.url.as_ref().is_some_and(|u| u.len() > max_url_chars()) {
            return Err(usage(Message::UsageUrlTooLong));
        }
        if self.no_input && self.url.is_none() {
            // Fail closed: `--no-input` refuses stdin, so an absent
            // positional URL leaves no target at all. Executing anyway
            // would mean guessing.
            return Err(AppError::InvalidUsage(
                "--no-input requires the url as a positional argument".to_string(),
            ));
        }
        // A malformed `--filter` must be a usage error at validation
        // time, not an empty result set at emission time.
        let surface = self.surface_options()?;
        if surface.is_active() && !self.json {
            // The reduction knobs act on the JSON envelope. Without
            // `--json` there is no envelope to reduce, and silently
            // ignoring the flags would let a caller believe a cut
            // happened when none did.
            return Err(AppError::InvalidUsage(
                "the agent-native reduction flags require --json".to_string(),
            ));
        }
        if self.quiet && self.verbose {
            return Err(usage(Message::UsageQuietWithVerbose));
        }
        if self.timeout == 0 {
            return Err(usage(Message::UsageTimeoutZero));
        }
        if self.cache_ttl == 0 {
            return Err(usage(Message::UsageCacheTtlZero));
        }
        if self.dry_run && self.batch {
            return Err(usage(Message::UsageDryRunWithBatch));
        }
        Ok(())
    }

    /// Interface locale requested on the command line or in the config
    /// file, if any. `None` means "let [`crate::i18n`] fall back to the
    /// system locale".
    #[must_use]
    pub fn effective_ui_language(&self) -> Option<Language> {
        self.ui_lang
    }
}

/// Compiled fallback for the longest positional URL the CLI accepts.
/// Beyond this the input is almost certainly not a URL, and every
/// provider would reject it.
///
/// Overridable at run time through the `cli.max_url_chars`
/// configuration key; see [`max_url_chars`] for the resolution.
const DEFAULT_MAX_URL_CHARS: usize = 2048;

/// Longest positional URL the CLI accepts.
///
/// Reads the `cli.max_url_chars` configuration key when the operator set
/// it, and falls back to the compiled default otherwise. A key that
/// was never set never invents a value the source did not already have.
#[must_use]
pub fn max_url_chars() -> usize {
    crate::config::tuning_u64("cli.max_url_chars")
        .and_then(|v| usize::try_from(v).ok())
        .filter(|v| *v > 0)
        .unwrap_or(DEFAULT_MAX_URL_CHARS)
}

/// Wrap a catalogue message as an [`AppError::InvalidUsage`].
///
/// The message is rendered here, at construction time, because the
/// variant carries a `String` payload rather than a catalogue key.
fn usage(msg: Message) -> AppError {
    AppError::InvalidUsage(t(msg).to_string())
}

/// `clap` value parser for `--lang`. Bridges
/// [`LanguageArg::parse`] to the `String` error `clap` expects.
fn parse_language(raw: &str) -> Result<LanguageArg, String> {
    LanguageArg::parse(raw).map_err(|e| e.to_string())
}

/// `clap` value parser for `--ui-lang`.
///
/// Rejects any locale this build does not carry, rather than silently
/// falling back: an operator who asks for an interface language must
/// learn that the binary was compiled without it.
fn parse_ui_language(raw: &str) -> Result<Language, String> {
    Language::from_tag(raw).ok_or_else(|| {
        format!(
            "{raw}: {} ({})",
            t(Message::LangUnsupportedUi),
            Language::compiled_tags()
        )
    })
}

fn is_stdin_tty_or_blocked() -> bool {
    use std::io::IsTerminal;
    std::io::stdin().is_terminal()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cli::{Cli, FormatArg, LanguageArg};
    use crate::cli::{ColorArg, LogFormatArg, LogLevelArg};
    use crate::error::AppError;
    use clap::Parser;

    /// A tuning namespace that is also a flat key is unreachable, and
    /// unreachable in silence.
    ///
    /// TOML cannot hold `batch = true` and `[batch]` at once, so the
    /// registry's declared type for the flat key decides how the parser
    /// reads the table — and it read it as a malformed boolean, failing
    /// before the registry was ever consulted for the leaf. The operator
    /// saw a type error about a key they had not written.
    ///
    /// This is a naming invariant, not a parsing one, so it is checked
    /// here rather than defended at parse time: the fix is to name the
    /// namespace differently, never to teach the parser a special case.
    #[test]
    fn no_tuning_namespace_shadows_a_flat_key() {
        for namespace in TUNING_NAMESPACES {
            assert!(
                crate::config::spec(namespace).is_none(),
                "`{namespace}` is both a tuning namespace and a flat registry key; \
                 every `{namespace}.*` key is unreachable from config.toml"
            );
        }
    }

    /// Every registry key must live under a declared tuning namespace or
    /// be a flat key. A leaf whose root is neither is rejected at load
    /// time by `validate_tuning_keys`, which would make it impossible to
    /// set — the same silence, arriving by the opposite route.
    #[test]
    fn every_dotted_registry_key_has_a_declared_namespace() {
        for entry in crate::config::KEYS {
            let Some((root, _)) = entry.key.split_once('.') else {
                continue;
            };
            assert!(
                TUNING_NAMESPACES.contains(&root),
                "`{}` has root `{root}`, which is not a tuning namespace",
                entry.key
            );
        }
    }

    /// Test-only helper: drive `parse_with_overrides` from a
    /// controllable argv slice instead of `std::env::args_os`.
    /// Returns `(Cli, CliOverrideFlags)` for assertion.
    fn parse_with_overrides_from<const N: usize>(args: [&str; N]) -> (Cli, CliOverrideFlags) {
        let cmd = <Cli as clap::CommandFactory>::command();
        let matches = cmd.get_matches_from(args);
        let flags = CliOverrideFlags::from_matches(&matches);
        let cli =
            <Cli as clap::FromArgMatches>::from_arg_matches(&matches).expect("test argv is valid");
        (cli, flags)
    }

    fn make_cli(url: Option<&str>, batch: bool) -> Cli {
        let mut args = vec!["youtube-legend-cli".to_string()];
        if let Some(u) = url {
            args.push(u.to_string());
        }
        if batch {
            args.push("--batch".to_string());
        }
        Cli::parse_from(args)
    }

    #[test]
    fn validate_accepts_url_only() {
        let cli = make_cli(Some("https://youtu.be/dQw4w9WgXcQ"), false);
        assert!(cli.validate().is_ok());
    }

    #[test]
    fn clap_rejects_invalid_language_via_try_parse_from() {
        // GAP-AUD-002: a rejected `--lang` exits with code 2 via
        // clap::Error::exit() before reaching AppError. try_parse_from
        // returns Err so we can assert the type without spawning a
        // process. The exit code 2 is produced by clap::Error::exit()
        // in src/main.rs.
        //
        // The rejected value is now a *malformed* tag rather than an
        // unregistered one: since the parser became BCP 47 aware, an
        // unregistered-but-well-formed subtag like `xx` is accepted and
        // simply fails to match any track later on.
        use clap::Parser;
        let result = Cli::try_parse_from([
            "youtube-legend-cli",
            "--lang",
            "not a language tag",
            "https://youtu.be/dQw4w9WgXcQ",
        ]);
        assert!(
            result.is_err(),
            "clap must reject a malformed --lang before reaching AppError"
        );
        let err = result.unwrap_err();
        // clap v4 reports rejected enum values as `ValueValidation`
        // (a sub-kind of argument validation), not the legacy
        // `InvalidValue`. Either way, the kind is a parse-time error
        // — never reaching `AppError::exit_code()` — and the process
        // exits with code 2 via `clap::Error::exit()`.
        assert!(matches!(
            err.kind(),
            clap::error::ErrorKind::ValueValidation | clap::error::ErrorKind::InvalidValue
        ));
    }

    #[test]
    fn validate_accepts_batch_with_stdin() {
        let cli = make_cli(None, true);
        assert!(cli.validate().is_ok());
    }

    #[test]
    fn validate_rejects_url_and_batch_together() {
        let cli = make_cli(Some("https://youtu.be/dQw4w9WgXcQ"), true);
        assert_usage(&cli.validate().unwrap_err(), Message::UsageBatchWithUrl);
    }

    #[test]
    fn validate_rejects_url_too_long() {
        let long = "a".repeat(max_url_chars() + 1);
        let cli = make_cli(Some(&long), false);
        assert_usage(&cli.validate().unwrap_err(), Message::UsageUrlTooLong);
    }

    /// Assert that `err` is an `InvalidUsage` carrying exactly `msg`.
    ///
    /// The comparison goes through the catalogue rather than a literal,
    /// so the assertion checks *which message* validate chose and stays
    /// silent about the locale rendering it.
    fn assert_usage(err: &AppError, msg: Message) {
        match err {
            AppError::InvalidUsage(payload) => assert_eq!(payload, t(msg)),
            other => panic!("expected InvalidUsage, got {other:?}"),
        }
    }

    #[test]
    fn validate_rejects_quiet_with_verbose() {
        let cli = Cli::parse_from([
            "youtube-legend-cli",
            "https://youtu.be/dQw4w9WgXcQ",
            "--quiet",
            "--verbose",
        ]);
        let err = cli.validate().unwrap_err();
        assert!(matches!(err, AppError::InvalidUsage(_)));
        assert!(err.to_string().contains("--quiet"));
    }

    #[test]
    fn validate_rejects_zero_timeout() {
        let cli = Cli::parse_from([
            "youtube-legend-cli",
            "https://youtu.be/dQw4w9WgXcQ",
            "--timeout",
            "0",
        ]);
        let err = cli.validate().unwrap_err();
        assert!(matches!(err, AppError::InvalidUsage(_)));
        assert!(err.to_string().contains("--timeout"));
    }

    #[test]
    fn validate_rejects_zero_cache_ttl() {
        let cli = Cli::parse_from([
            "youtube-legend-cli",
            "https://youtu.be/dQw4w9WgXcQ",
            "--cache-ttl",
            "0",
        ]);
        let err = cli.validate().unwrap_err();
        assert!(matches!(err, AppError::InvalidUsage(_)));
        assert!(err.to_string().contains("--cache-ttl"));
    }

    #[test]
    fn validate_accepts_stdin_pipe_path_semantically() {
        let cli = make_cli(None, false);
        let res = cli.validate();
        let is_tty = is_stdin_tty_or_blocked();
        if is_tty {
            assert!(matches!(res, Err(AppError::InvalidUsage(_))));
        } else {
            assert!(res.is_ok());
        }
    }

    #[test]
    fn parse_language_normalises_without_truncating() {
        assert_eq!(lang_tag("pt-BR"), "pt-BR");
        assert_eq!(lang_tag("pt_BR.UTF-8"), "pt-BR");
        assert_eq!(lang_tag("EN-us"), "en-US");
        assert_eq!(lang_tag("es-AR"), "es-AR");
        assert_eq!(lang_tag("zh-Hans-CN"), "zh-Hans-CN");
        assert_eq!(lang_tag("zh-hant-tw"), "zh-Hant-TW");
    }

    /// The regression this type exists for: the old parser collapsed
    /// everything after the first hyphen, so these four tags were one.
    #[test]
    fn parse_language_keeps_region_and_script_distinct() {
        assert_ne!(lang_tag("pt-BR"), lang_tag("pt-PT"));
        assert_ne!(lang_tag("zh-Hans"), lang_tag("zh-Hant"));
    }

    #[test]
    fn parse_language_maps_youtube_legacy_codes() {
        // YouTube still spells Hebrew `iw`, Indonesian `in` and
        // Yiddish `ji`. Input in either spelling normalises to the
        // modern code, and the legacy code is available for the wire.
        for (modern, legacy) in [("he", "iw"), ("id", "in"), ("yi", "ji")] {
            let from_modern = LanguageArg::parse(modern).expect("modern code parses");
            let from_legacy = LanguageArg::parse(legacy).expect("legacy code parses");
            assert_eq!(from_modern.as_str(), modern);
            assert_eq!(from_legacy.as_str(), modern);
            assert_eq!(from_modern.youtube_code(), legacy);
            assert_eq!(from_legacy.youtube_code(), legacy);
        }
    }

    #[test]
    fn youtube_legacy_mapping_preserves_region() {
        let tag = LanguageArg::parse("he-IL").expect("he-IL parses");
        assert_eq!(tag.as_str(), "he-IL");
        assert_eq!(tag.youtube_code(), "iw-IL");
    }

    #[test]
    fn youtube_code_equals_tag_for_non_legacy_languages() {
        let tag = LanguageArg::parse("pt-BR").expect("pt-BR parses");
        assert_eq!(tag.youtube_code(), tag.as_str());
    }

    #[test]
    fn parse_language_rejects_malformed_tag() {
        let err = LanguageArg::parse("not a tag").unwrap_err();
        assert!(
            matches!(err, AppError::LanguageParseError(_)),
            "expected LanguageParseError, got {err:?}"
        );
        assert!(LanguageArg::parse("").is_err());
        assert!(LanguageArg::parse("   ").is_err());
    }

    #[test]
    fn interning_returns_the_same_pointer_for_equal_tags() {
        let a = LanguageArg::parse("pt-BR").expect("parses");
        let b = LanguageArg::parse("pt_BR.UTF-8").expect("parses");
        assert!(std::ptr::eq(a.as_str(), b.as_str()));
    }

    #[test]
    fn lang_flag_accepts_bcp47_from_argv() {
        let cli = Cli::parse_from([
            "youtube-legend-cli",
            "https://youtu.be/dQw4w9WgXcQ",
            "--lang",
            "pt-BR",
        ]);
        assert_eq!(cli.lang.as_str(), "pt-BR");
    }

    #[test]
    fn lang_flag_defaults_to_english() {
        let cli = Cli::parse_from(["youtube-legend-cli", "https://youtu.be/dQw4w9WgXcQ"]);
        assert_eq!(cli.lang.as_str(), "en");
        assert_eq!(cli.lang, LanguageArg::english());
    }

    #[test]
    fn language_arg_exposes_its_subtags() {
        let tag = LanguageArg::parse("zh-Hant-TW").expect("parses");
        assert_eq!(tag.primary(), "zh");
        assert_eq!(tag.script().map(|s| s.to_string()).as_deref(), Some("Hant"));
        assert_eq!(tag.region().map(|r| r.to_string()).as_deref(), Some("TW"));
        assert_eq!(tag.to_langid().to_string(), "zh-Hant-TW");
    }

    #[test]
    fn ui_lang_flag_accepts_compiled_locale() {
        let cli = Cli::parse_from([
            "youtube-legend-cli",
            "https://youtu.be/dQw4w9WgXcQ",
            "--ui-lang",
            "pt-BR",
        ]);
        assert_eq!(cli.ui_lang, Some(Language::PtBr));
        assert_eq!(cli.effective_ui_language(), Some(Language::PtBr));
    }

    #[test]
    fn ui_lang_flag_rejects_locale_absent_from_this_build() {
        let result = Cli::try_parse_from([
            "youtube-legend-cli",
            "https://youtu.be/dQw4w9WgXcQ",
            "--ui-lang",
            "xx",
        ]);
        assert!(result.is_err(), "clap must reject an uncompiled ui locale");
    }

    #[test]
    fn ui_lang_defaults_to_none_so_the_system_locale_decides() {
        let cli = Cli::parse_from(["youtube-legend-cli", "https://youtu.be/dQw4w9WgXcQ"]);
        assert_eq!(cli.effective_ui_language(), None);
    }

    #[test]
    fn format_arg_maps_to_extensions() {
        assert_eq!(format_fmt(FormatArg::Txt), "txt");
        assert_eq!(format_fmt(FormatArg::Srt), "srt");
        assert_eq!(format_fmt(FormatArg::Vtt), "vtt");
    }

    /// The `--format` surface has one spelling per variant, and the
    /// config file must accept exactly the spellings the command line
    /// does. `vtt` was documented and refused for a whole release
    /// because nothing compared the two lists.
    #[test]
    fn every_format_variant_is_reachable_from_argv_and_from_config() {
        use clap::ValueEnum;
        for variant in FormatArg::value_variants() {
            let spelling = variant
                .to_possible_value()
                .expect("every variant is selectable")
                .get_name()
                .to_string();
            let cli = Cli::parse_from([
                "youtube-legend-cli",
                "https://youtu.be/dQw4w9WgXcQ",
                "--format",
                &spelling,
            ]);
            assert_eq!(cli.format, *variant, "argv rejected `{spelling}`");
            assert_eq!(
                FormatArg::from_config_str(&spelling).expect("config accepts it"),
                *variant,
                "the config file rejected `{spelling}`"
            );
            assert_eq!(format_fmt(*variant), spelling);
        }
    }

    /// Parse `raw` and return its canonical tag. Panics on a bad tag,
    /// which is exactly what a failing test should do.
    fn lang_tag(raw: &str) -> &'static str {
        LanguageArg::parse(raw)
            .unwrap_or_else(|e| panic!("`{raw}` must parse: {e}"))
            .as_str()
    }

    #[test]
    fn cli_accepts_all_global_flags() {
        let cli = Cli::parse_from([
            "youtube-legend-cli",
            "https://youtu.be/dQw4w9WgXcQ",
            "--config",
            "/tmp/cfg.toml",
            "--log-level",
            "debug",
            "--log-format",
            "json",
            "--color",
            "never",
            "--no-progress",
            "--dry-run",
            "--yes",
        ]);
        assert_eq!(cli.log_level, LogLevelArg::Debug);
        assert_eq!(cli.log_format, LogFormatArg::Json);
        assert_eq!(cli.color, ColorArg::Never);
        assert!(cli.no_progress);
        assert!(cli.dry_run);
        assert!(cli.yes);
        assert_eq!(cli.config, Some(std::path::PathBuf::from("/tmp/cfg.toml")));
    }

    #[test]
    fn log_level_enum_maps_to_tracing() {
        assert_eq!(LogLevelArg::Error.as_str(), "error");
        assert_eq!(LogLevelArg::Warn.as_str(), "warn");
        assert_eq!(LogLevelArg::Info.as_str(), "info");
        assert_eq!(LogLevelArg::Debug.as_str(), "debug");
        assert_eq!(LogLevelArg::Trace.as_str(), "trace");
    }

    #[test]
    fn color_defaults_to_auto_and_ignores_the_environment() {
        let cli = Cli::parse_from(["youtube-legend-cli", "https://youtu.be/dQw4w9WgXcQ"]);
        assert_eq!(cli.color, ColorArg::Auto);
        // Auto stays Auto: no environment variable can move it any
        // more, so the resolved policy equals the parsed flag.
        assert_eq!(cli.effective_color(), ColorArg::Auto);
    }

    #[test]
    fn dry_run_rejects_batch() {
        let cli = Cli::parse_from(["youtube-legend-cli", "--dry-run", "--batch"]);
        let err = cli.validate().unwrap_err();
        assert!(matches!(err, AppError::InvalidUsage(_)));
        assert!(err.to_string().contains("--dry-run"));
        assert!(err.to_string().contains("--batch"));
    }

    #[test]
    fn apply_overrides_exports_no_env_var_at_all() {
        // `apply_overrides` exports nothing. The four product variables
        // went first; `NO_COLOR` and `CLICOLOR_FORCE` followed on
        // 2026-08-31, when the colour policy started travelling by
        // value instead of through the process environment.
        let prev_no_color = std::env::var("NO_COLOR").ok();
        let prev_force = std::env::var("CLICOLOR_FORCE").ok();
        for key in [
            "YT_LOG_LEVEL",
            "YT_LOG_FORMAT",
            "YT_DRY_RUN",
            "YT_NO_PROGRESS",
            "NO_COLOR",
            "CLICOLOR_FORCE",
        ] {
            std::env::remove_var(key);
        }

        let cli = Cli::parse_from([
            "youtube-legend-cli",
            "https://youtu.be/dQw4w9WgXcQ",
            "--log-level",
            "trace",
            "--log-format",
            "json",
            "--color",
            "never",
            "--no-progress",
            "--dry-run",
        ]);
        cli.apply_overrides();

        for key in [
            "YT_LOG_LEVEL",
            "YT_LOG_FORMAT",
            "YT_DRY_RUN",
            "YT_NO_PROGRESS",
            "NO_COLOR",
            "CLICOLOR_FORCE",
        ] {
            assert!(
                std::env::var(key).is_err(),
                "{key} must not be exported by this product"
            );
        }
        // `--color never` is still the resolved policy; it simply
        // reaches its consumers as a value now.
        assert_eq!(cli.effective_color(), ColorArg::Never);

        restore("NO_COLOR", prev_no_color);
        restore("CLICOLOR_FORCE", prev_force);
    }

    fn restore(key: &str, prev: Option<String>) {
        match prev {
            Some(v) => std::env::set_var(key, v),
            None => std::env::remove_var(key),
        }
    }

    #[test]
    fn load_config_reads_valid_toml() {
        let dir = std::env::temp_dir();
        let path = dir.join("yt_legend_config_test_valid.toml");
        std::fs::write(
            &path,
            r#"
url = "https://youtu.be/dQw4w9WgXcQ"
lang = "pt"
timeout = 12
cache_ttl = 6
verbose = true
json = false
dry_run = true
log_level = "debug"
log_format = "json"
color = "never"
"#,
        )
        .expect("write tmp config");
        let cfg = load_config(&path).expect("load config");
        assert_eq!(cfg.url.as_deref(), Some("https://youtu.be/dQw4w9WgXcQ"));
        assert_eq!(cfg.lang.map(LanguageArg::as_str), Some("pt"));
        assert_eq!(cfg.timeout, Some(12));
        assert_eq!(cfg.cache_ttl, Some(6));
        assert_eq!(cfg.verbose, Some(true));
        assert_eq!(cfg.dry_run, Some(true));
        assert!(matches!(cfg.log_level, Some(LogLevelArg::Debug)));
        assert!(matches!(cfg.log_format, Some(LogFormatArg::Json)));
        assert!(matches!(cfg.color, Some(ColorArg::Never)));
        std::fs::remove_file(&path).ok();
    }

    #[test]
    fn load_config_rejects_invalid_toml() {
        let dir = std::env::temp_dir();
        let path = dir.join("yt_legend_config_test_bad.toml");
        std::fs::write(&path, "this is not = toml [[[").expect("write tmp");
        let err = load_config(&path).unwrap_err();
        assert!(matches!(err, AppError::Config(_)));
        assert_eq!(err.exit_code(), 78);
        let msg = err.to_string();
        assert!(msg.contains(&path.display().to_string()), "actual: {msg}");
        std::fs::remove_file(&path).ok();
    }

    #[test]
    fn load_config_rejects_unknown_key() {
        let dir = std::env::temp_dir();
        let path = dir.join("yt_legend_config_test_unknown.toml");
        std::fs::write(&path, "definitely_not_a_flag = 1\n").expect("write tmp");
        let err = load_config(&path).unwrap_err();
        assert!(matches!(err, AppError::Config(_)));
        assert_eq!(err.exit_code(), 78);
        let msg = err.to_string();
        assert!(msg.contains("`definitely_not_a_flag`"), "actual: {msg}");
        std::fs::remove_file(&path).ok();
    }

    #[test]
    fn load_config_rejects_unknown_key_inside_tuning_namespace() {
        // The silent-drop regression: `net` is a tuning namespace, so
        // the whole subtree used to be waved through unread.
        let path = std::env::temp_dir().join("yt_legend_config_test_tuning_unknown.toml");
        std::fs::write(&path, "[net]\nfoo = 1\n").expect("write tmp");
        let err = load_config(&path).unwrap_err();
        assert!(matches!(err, AppError::Config(_)));
        assert_eq!(err.exit_code(), 78);
        let msg = err.to_string();
        assert!(msg.contains("`net.foo`"), "actual: {msg}");
        std::fs::remove_file(&path).ok();
    }

    #[test]
    fn load_config_accepts_known_tuning_keys() {
        let path = std::env::temp_dir().join("yt_legend_config_test_tuning_known.toml");
        std::fs::write(
            &path,
            r#"
[net.retry]
max_attempts = 5

[cache]
qualifier = "com"

[cli]
worker_threads_max = 8

[i18n]
max_untranslated_messages = 3
"#,
        )
        .expect("write tmp");
        load_config(&path).expect("registered tuning keys must load");
        std::fs::remove_file(&path).ok();
    }

    /// Rejecting every tuning key would satisfy the failure case on its
    /// own, so this is the half that proves the registry is honoured:
    /// every dotted key it declares must still load.
    #[test]
    fn load_config_accepts_every_registered_tuning_key() {
        let mut text = String::new();
        let mut written = 0_usize;
        for spec in crate::config::KEYS {
            // A flat key mirrors a CLI flag and is typed by
            // `absorb_config_key`, not by the registry. `batch` is both a
            // flag and a namespace, so a `[batch]` table is refused as a
            // wrong-typed boolean before the registry is ever consulted.
            if !spec.key.contains('.') || spec.key.starts_with("batch.") {
                continue;
            }
            text.push_str(&format!("{} = \"placeholder\"\n", spec.key));
            written += 1;
        }
        assert!(written > 50, "the registry looks empty: {written} keys");
        let path = std::env::temp_dir().join("yt_legend_config_test_all_tuning.toml");
        std::fs::write(&path, &text).expect("write tmp");
        load_config(&path).expect("every registered tuning key must load");
        std::fs::remove_file(&path).ok();
    }

    #[test]
    fn load_config_rejects_missing_file() {
        let path = std::path::Path::new("/nonexistent/path/yt_legend.toml");
        let err = load_config(path).unwrap_err();
        assert!(matches!(err, AppError::Config(_)));
        assert_eq!(err.exit_code(), 78);
    }

    #[test]
    fn apply_config_overrides_cli_wins() {
        let (mut cli, flags) = parse_with_overrides_from([
            "youtube-legend-cli",
            "https://youtu.be/from_cli",
            "--lang",
            "es",
        ]);
        let cfg = ConfigOverrides {
            url: Some("https://youtu.be/from_config".to_string()),
            lang: Some(LanguageArg::parse("pt-BR").expect("pt-BR parses")),
            timeout: Some(99),
            ..Default::default()
        };
        cli.apply_config_overrides(cfg, &flags);
        // CLI wins on url (positional, not defaultable) and lang
        // (operator passed `--lang es` so `flags.lang` is true).
        assert_eq!(cli.url.as_deref(), Some("https://youtu.be/from_cli"));
        assert_eq!(cli.lang.as_str(), "es");
        // Config fills in defaults (timeout was omitted on CLI,
        // `flags.timeout` is false, so the override applies).
        assert_eq!(cli.timeout, 99);
    }

    #[test]
    fn apply_config_overrides_config_fills_defaults() {
        let (mut cli, flags) = parse_with_overrides_from(["youtube-legend-cli"]);
        let cfg = ConfigOverrides {
            timeout: Some(45),
            cache_ttl: Some(2),
            log_level: Some(LogLevelArg::Trace),
            color: Some(ColorArg::Always),
            ..Default::default()
        };
        cli.apply_config_overrides(cfg, &flags);
        assert_eq!(cli.timeout, 45);
        assert_eq!(cli.cache_ttl, 2);
        assert!(matches!(cli.log_level, LogLevelArg::Trace));
        assert!(matches!(cli.color, ColorArg::Always));
    }

    /// GAP-E2E-016 regression: when the operator types a flag
    /// explicitly with the same value as the built-in default
    /// (`--timeout 30` for example), the previous sentinel logic
    /// `if self.timeout == 30` would mis-classify that field as
    /// "operator omitted" and let the config override win. The
    /// `CliOverrideFlags` bitmask avoids the ambiguity.
    #[test]
    fn apply_config_overrides_explicit_default_does_not_get_overridden() {
        let (mut cli, flags) = parse_with_overrides_from(["youtube-legend-cli", "--timeout", "30"]);
        let cfg = ConfigOverrides {
            timeout: Some(99),
            ..Default::default()
        };
        cli.apply_config_overrides(cfg, &flags);
        assert!(
            flags.timeout,
            "flags.timeout must report explicit CLI usage"
        );
        // The explicit `--timeout 30` MUST survive the merge even
        // though its value matches the built-in default.
        assert_eq!(
            cli.timeout, 30,
            "explicit CLI default value must NOT be overridden by config"
        );
    }

    fn format_fmt(f: FormatArg) -> &'static str {
        match f {
            FormatArg::Txt => "txt",
            FormatArg::Srt => "srt",
            FormatArg::Vtt => "vtt",
        }
    }

    #[test]
    fn provider_choice_parses_all_variants() {
        use crate::cli::ProviderChoice;
        let cases = [
            ("auto", ProviderChoice::Auto),
            ("provider-decopy", ProviderChoice::ProviderDecopy),
            ("provider-noiz", ProviderChoice::ProviderNoiz),
        ];
        for (flag, expected) in cases {
            let cli = Cli::parse_from([
                "youtube-legend-cli",
                "https://youtu.be/dQw4w9WgXcQ",
                "--provider",
                flag,
            ]);
            assert_eq!(cli.provider, Some(expected), "failed for {flag}");
        }
    }

    /// A value the command line accepts must be a value the config file
    /// accepts, and the reverse.
    ///
    /// MEASURED on 2026-09-04: `from_config_str` listed `auto` and ONE
    /// provider, so pinning any other one through the configuration file
    /// was refused while the identical value on the command line went
    /// through. Two entry points to the same setting had drifted apart
    /// and nothing compared them.
    ///
    /// The set is DERIVED from `ValueEnum` rather than written out here.
    /// A hand-written list is a third copy of the same fact, and a third
    /// copy drifts exactly like the second one did — this test would
    /// then pass while agreeing with nobody.
    #[test]
    fn every_provider_the_command_line_accepts_the_config_file_accepts_too() {
        use crate::cli::ConfigValue;
        use clap::ValueEnum;

        for variant in ProviderChoice::value_variants() {
            let wire = variant.as_str();
            let parsed = ProviderChoice::from_config_str(wire).unwrap_or_else(|e| {
                panic!(
                    "`--provider {wire}` parses on the command line but the config file \
                     refuses it: {e}"
                )
            });
            assert_eq!(
                parsed, *variant,
                "`{wire}` round-trips to a different variant through the config file"
            );
        }
    }
}