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
//! Persisted configuration: XDG discovery, the key registry, and the
//! read/write store behind the `config` subcommand.
//!
//! # Why a registry
//!
//! Every tunable this binary owns is declared exactly once, in
//! [`crate::config::KEYS`].
//! `config list-keys` renders that list, `config set` validates against
//! it, and `config get` reads through it. A key that is not in the
//! registry is rejected, so a typo surfaces immediately instead of
//! silently doing nothing.
//!
//! # No product environment variables
//!
//! This crate reads no environment variable at all. Configuration
//! arrives from the command line, then from the XDG file, then from the
//! compiled default — in that order. `NO_COLOR`, `CLICOLOR_FORCE` and
//! `RUST_LOG` were honoured as ecosystem conventions until 2026-08-31;
//! all three are gone, because an exported value follows every
//! invocation in the shell and never appears in `config list-keys`.
//!
//! # File location
//!
//! - Linux: `$XDG_CONFIG_HOME/youtube-legend-cli/config.toml`
//! - macOS: `~/Library/Application Support/youtube-legend-cli/config.toml`
//! - Windows: `%APPDATA%\youtube-legend-cli\config.toml`
//!
//! The path is resolved by the `directories` crate and can be printed
//! with `youtube-legend-cli config path`.

use crate::error::{AppError, AppResult};
use crate::i18n::{t, Message};
use directories::ProjectDirs;
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::sync::OnceLock;

/// Organisation segment handed to `directories`.
const PROJECT_ORG: &str = "youtube-legend-cli";
/// Application segment handed to `directories`.
const PROJECT_APP: &str = "youtube-legend-cli";
/// Qualifier segment handed to `directories`.
const PROJECT_QUALIFIER: &str = "com";
/// File name of the persisted configuration.
const CONFIG_FILE_NAME: &str = "config.toml";

/// Value type a registry key accepts.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum KeyKind {
    /// A TOML string.
    Str,
    /// A TOML integer, stored and read as `u64`.
    Int,
    /// A TOML boolean.
    Bool,
    /// A TOML array of strings.
    StrList,
}

impl KeyKind {
    /// Lowercase name used by `config list-keys`.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Str => "string",
            Self::Int => "integer",
            Self::Bool => "boolean",
            Self::StrList => "string-list",
        }
    }
}

/// One entry of the configuration registry.
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
pub struct KeySpec {
    /// Dotted key name, for example `net.waf.max_consecutive_failures`.
    pub key: &'static str,
    /// Value type the key accepts.
    pub kind: KeyKind,
    /// One-line description rendered by `config list-keys`.
    pub doc: &'static str,
    /// `true` when the value is a credential.
    ///
    /// A secret key is refused on the command line: `config set` demands
    /// `--from-stdin` for it, because argv is visible in the process
    /// table to every user on the host.
    pub secret: bool,
}

/// Declare a non-secret registry entry.
macro_rules! key {
    ($name:literal, $kind:ident, $doc:literal) => {
        KeySpec {
            key: $name,
            kind: KeyKind::$kind,
            doc: $doc,
            secret: false,
        }
    };
}

/// Every configuration key this binary recognises.
///
/// The first block mirrors the long-form CLI flags. The remaining blocks
/// are tuning constants lifted out of the source: each one used to be a
/// hard-coded literal.
pub const KEYS: &[KeySpec] = &[
    // --- keys that mirror a CLI flag -------------------------------
    key!("url", Str, "Default YouTube URL when none is supplied"),
    key!("lang", Str, "Preferred subtitle language (BCP 47)"),
    key!("ui_lang", Str, "Interface language for stderr messages"),
    key!("format", Str, "Output format: txt, srt or vtt"),
    // NOT an HTTP request timeout, and the wording matters because this
    // description is what `config list-keys` publishes to an automated
    // caller. It is the ceiling for the WHOLE operation: it wraps the
    // provider chain and every retry inside it. The flag's own help was
    // corrected on 2026-08-31 and this copy was missed, so the two
    // halves of one surface contradicted each other.
    //
    // This comment also listed "the browser launch" until 2026-09-04.
    // The two browser-driven providers were removed on that date and
    // nothing launches a browser any more, so the ceiling wraps HTTP
    // and retries and nothing else.
    key!(
        "timeout",
        Int,
        "Whole-operation timeout in seconds (not per HTTP request)"
    ),
    key!("cache_ttl", Int, "Local cache TTL in hours"),
    key!("user_agent", Str, "User-Agent header for HTTP requests"),
    key!("verbose", Bool, "Emit tracing events to stderr"),
    key!("quiet", Bool, "Suppress stderr output except errors"),
    key!("json", Bool, "Emit the structured JSON envelope"),
    key!("batch", Bool, "Read multiple URLs from stdin"),
    key!("no_cache", Bool, "Disable reads from the local cache"),
    key!("dry_run", Bool, "Skip network I/O entirely"),
    key!("no_progress", Bool, "Suppress progress bars on stderr"),
    key!("yes", Bool, "Assume yes for any confirmation prompt"),
    key!("no_input", Bool, "Refuse to read stdin"),
    key!(
        "log_level",
        Str,
        "Log level: error, warn, info, debug, trace"
    ),
    key!("log_format", Str, "Log format: text or json"),
    key!("color", Str, "Colour output: auto, always, never"),
    key!(
        "provider",
        Str,
        "Provider selection: auto or a pinned provider"
    ),
    key!(
        "offline",
        Bool,
        "Refuse every outbound request; serve cache only"
    ),
    key!("jobs", Int, "Batch items processed concurrently"),
    // --- cli -------------------------------------------------------
    key!("cli.max_url_chars", Int, "Longest positional URL accepted"),
    key!(
        "cli.worker_threads_min",
        Int,
        "Lower bound of the tokio worker-thread count derived from available parallelism"
    ),
    key!(
        "cli.worker_threads_max",
        Int,
        "Upper bound of the tokio worker-thread count derived from available parallelism"
    ),
    // `batch.max_jobs` until 0.3.5. The registry already declared a flat
    // `batch` key of type boolean, mirroring the `--batch` flag, so a
    // `[batch]` table in `config.toml` was rejected as a malformed
    // boolean before the registry was ever consulted: the ceiling was
    // unreachable from the file, and only the compiled default applied.
    // Renaming breaks no one precisely because the old name never worked.
    key!(
        "cli.max_jobs",
        Int,
        "Ceiling applied to --jobs regardless of what is requested"
    ),
    // --- i18n ------------------------------------------------------
    key!(
        "i18n.windows_console_code_page",
        Int,
        "Console code page forced on Windows"
    ),
    key!(
        "i18n.max_untranslated_messages",
        Int,
        "Ceiling on untranslated catalogue entries"
    ),
    // --- cache -----------------------------------------------------
    key!(
        "cache.qualifier",
        Str,
        "Qualifier segment of the platform cache directory"
    ),
    // --- net -------------------------------------------------------
    key!(
        "net.watch_probe_timeout_secs",
        Int,
        "Timeout for the watch-page probe that names the real cause after the chain fails"
    ),
    key!(
        "net.verify_delivered_language",
        Bool,
        "Confirm on the watch page that the delivered track is the language that was asked for"
    ),
    key!(
        "net.health.failure_budget",
        Int,
        "Consecutive failures before a provider is called broken"
    ),
    key!(
        "net.health.persistence_window_secs",
        Int,
        "Seconds a failure run must span before it counts as persistent"
    ),
    key!(
        "net.per_host_concurrency",
        Int,
        "Concurrent in-flight requests allowed against one upstream host"
    ),
    key!(
        "net.throttle_interval_ms",
        Int,
        "Minimum interval between two provider calls, in milliseconds"
    ),
    key!(
        "net.max_body_bytes",
        Int,
        "Ceiling on a subtitle payload accepted by the parser, in bytes"
    ),
    // --- net.retry -------------------------------------------------
    key!(
        "net.retry.max_attempts",
        Int,
        "How many times a provider call is attempted before the error is returned"
    ),
    key!(
        "net.retry.backoff_base_ms",
        Int,
        "First back-off delay; each further attempt doubles it"
    ),
    key!(
        "net.retry.backoff_max_ms",
        Int,
        "Ceiling applied to the doubling back-off delay"
    ),
    key!(
        "net.retry.rate_limit_default_secs",
        Int,
        "Wait applied on HTTP 429 when the upstream sends no Retry-After"
    ),
    key!(
        "net.retry.rate_limit_cap_secs",
        Int,
        "Ceiling applied to an upstream Retry-After value"
    ),
    // --- net.robots ------------------------------------------------
    key!(
        "net.robots.honor",
        Bool,
        "Obey robots.txt before scraping (off by default: this CLI acts on behalf of a user request, not as a crawler)"
    ),
    key!(
        "net.robots.fetch_timeout_secs",
        Int,
        "Seconds allowed for the robots.txt fetch itself, when honoring is on"
    ),
    // --- net.observe -----------------------------------------------
    key!(
        "net.observe.redacted_headers",
        StrList,
        "Header names redacted before a capture is written"
    ),
    key!(
        "net.observe.redacted_header_substrings",
        StrList,
        "Header-name substrings that trigger redaction"
    ),
    key!(
        "net.observe.binary_media_prefixes",
        StrList,
        "Content-Type prefixes treated as binary media"
    ),
    key!(
        "net.observe.top_hosts_limit",
        Int,
        "How many hosts the traffic summary reports"
    ),
    // --- net.intercept ---------------------------------------------
    key!(
        "net.intercept.blocked_hosts",
        StrList,
        "Hosts refused outright by the interceptor"
    ),
    key!(
        "net.intercept.url_patterns",
        StrList,
        "URL patterns matched by the interceptor"
    ),
    key!(
        "net.intercept.stub_status",
        Int,
        "HTTP status returned for a stubbed request"
    ),
    key!(
        "net.intercept.block_media",
        Bool,
        "Refuse image, font and media subresources"
    ),
    key!(
        "net.intercept.stub_trackers",
        Bool,
        "Answer tracker requests with a stub instead of the network"
    ),
    // --- net.endpoints ---------------------------------------------
    key!(
        "net.endpoints.decopy.host",
        Str,
        "Host of the decopy provider API"
    ),
    key!(
        "net.endpoints.decopy.base",
        Str,
        "Scheme and authority of the decopy provider API"
    ),
    key!(
        "net.endpoints.decopy.create_job_path",
        Str,
        "Path of the decopy create-job endpoint"
    ),
    key!(
        "net.endpoints.decopy.product_code",
        Str,
        "Product code the decopy API requires"
    ),
    key!("net.endpoints.noiz.host", Str, "Host of the noiz provider API"),
    key!(
        "net.endpoints.noiz.base",
        Str,
        "Scheme and authority of the noiz provider API"
    ),
    key!(
        "net.endpoints.noiz.subtitles_path",
        Str,
        "Path of the noiz subtitles endpoint"
    ),
    // --- net.session -----------------------------------------------
    key!("net.session.cookie_file", Str, "Path of the cookie jar"),
    key!(
        "net.session.cookie_file_mode",
        Int,
        "Unix permission bits of the cookie jar"
    ),
    key!(
        "net.session.chrome_full_version",
        Str,
        "Chrome full version advertised in client hints"
    ),
    key!(
        "net.session.header_order",
        StrList,
        "Order request headers are emitted in"
    ),
    key!(
        "net.session.accept_navigation",
        Str,
        "Accept header for navigation requests"
    ),
    key!(
        "net.session.accept_encoding",
        Str,
        "Accept-Encoding header value"
    ),
    key!(
        "net.session.accept_language",
        Str,
        "Accept-Language header value"
    ),
    // --- net.waf ---------------------------------------------------
    key!(
        "net.waf.max_consecutive_failures",
        Int,
        "Failures tolerated before the circuit opens"
    ),
    key!(
        "net.waf.header_signatures",
        StrList,
        "Exact header names that identify a WAF"
    ),
    key!(
        "net.waf.header_prefix_signatures",
        StrList,
        "Header-name prefixes that identify a WAF"
    ),
    key!(
        "net.waf.cookie_signatures",
        StrList,
        "Exact cookie names that identify a WAF"
    ),
    key!(
        "net.waf.cookie_prefix_signatures",
        StrList,
        "Cookie-name prefixes that identify a WAF"
    ),
    key!(
        "net.waf.challenge_cookies",
        StrList,
        "Cookies that mark an interactive challenge"
    ),
    // --- input -----------------------------------------------------
    key!(
        "input.max_stdin_bytes",
        Int,
        "Ceiling on a single stdin read, in bytes"
    ),
    key!(
        "input.move_steps_min",
        Int,
        "Minimum synthesised pointer steps per move"
    ),
    key!(
        "input.move_steps_max",
        Int,
        "Maximum synthesised pointer steps per move"
    ),
    key!("input.move_gap_min_ms", Int, "Minimum gap between steps"),
    key!("input.move_gap_max_ms", Int, "Maximum gap between steps"),
    key!(
        "input.bezier_deviation_px",
        Int,
        "Curve deviation of a synthesised pointer path"
    ),
    key!("input.click_jitter_min_px", Int, "Minimum click jitter"),
    key!("input.click_jitter_max_px", Int, "Maximum click jitter"),
    key!(
        "input.click_settle_min_ms",
        Int,
        "Minimum post-click settle"
    ),
    key!(
        "input.click_settle_max_ms",
        Int,
        "Maximum post-click settle"
    ),
    key!("input.type_delay_min_ms", Int, "Minimum inter-key delay"),
    key!("input.type_delay_max_ms", Int, "Maximum inter-key delay"),
    key!("input.scroll_chunk_min_px", Int, "Minimum scroll chunk"),
    key!("input.scroll_chunk_max_px", Int, "Maximum scroll chunk"),
    key!(
        "input.scroll_pause_min_ms",
        Int,
        "Minimum pause between chunks"
    ),
    key!(
        "input.scroll_pause_max_ms",
        Int,
        "Maximum pause between chunks"
    ),
    key!("input.scroll_total_px", Int, "Total distance scrolled"),
    // Shape of the delays, not their centre. The pairs above give the
    // mean; these give the second moment, which is what a detector
    // actually measures. Sigma is in thousandths because the registry
    // carries integers.
    key!(
        "input.delay_sigma_milli",
        Int,
        "Log-space standard deviation of the delays, in thousandths"
    ),
    key!(
        "input.long_pause_permille",
        Int,
        "Chance per thousand that a word boundary earns a long pause"
    ),
    key!(
        "input.long_pause_min_ms",
        Int,
        "Minimum long pause at a word boundary"
    ),
    key!(
        "input.long_pause_max_ms",
        Int,
        "Maximum long pause at a word boundary"
    ),
    // --- stealth ---------------------------------------------------
    // Absent by design: the seed then comes from the system, because a
    // seed decides *which* noise there is and never *whether* there is
    // noise. Setting it makes one invocation reproducible, which is the
    // point when measuring the distribution that was actually emitted.
    key!(
        "stealth.seed",
        Int,
        "Fixed root seed for this invocation; unset draws from the system"
    ),
    // --- providers.decopy ------------------------------------------
    key!(
        "providers.decopy.request_timeout_secs",
        Int,
        "Per-request timeout"
    ),
    key!(
        "providers.decopy.max_body_bytes",
        Int,
        "Largest response body accepted"
    ),
    key!(
        "providers.decopy.serial_hex_len",
        Int,
        "Length in hex characters of the request serial"
    ),
    // --- providers.noiz --------------------------------------------
    key!(
        "providers.noiz.request_timeout_secs",
        Int,
        "Per-request timeout"
    ),
    key!(
        "providers.noiz.max_body_bytes",
        Int,
        "Largest response body accepted"
    ),
    // --- providers.cue ---------------------------------------------
    key!(
        "providers.cue.min_cue_millis",
        Int,
        "Shortest cue duration kept when normalising timings"
    ),
];

/// Look a key up in the registry.
#[must_use]
pub fn spec(key: &str) -> Option<&'static KeySpec> {
    KEYS.iter().find(|s| s.key == key)
}

/// The one [`ProjectDirs`] this product uses.
///
/// Every directory the CLI touches — configuration, cache, session data
/// — must be derived from this single call. Four sites used to build
/// their own, with three different argument triples, and on Linux they
/// happened to collapse because the XDG rules ignore the qualifier and
/// the organisation. On macOS and Windows they do not: there the triple
/// becomes part of the path, so the cookie jar landed in one directory
/// while the configuration that governs it landed in another.
///
/// A bug that is invisible on the platform you develop on is the exact
/// shape this function exists to prevent, which is why the constants
/// below are private and this is the only way to reach them.
#[must_use]
pub fn project_dirs() -> Option<ProjectDirs> {
    ProjectDirs::from(PROJECT_QUALIFIER, PROJECT_ORG, PROJECT_APP)
}

/// Directory holding the persisted configuration.
///
/// # Errors
///
/// Returns [`AppError::Internal`] when the platform exposes no home
/// directory, which is the only condition under which `directories`
/// fails.
pub fn config_dir() -> AppResult<PathBuf> {
    project_dirs()
        .map(|d| d.config_dir().to_path_buf())
        .ok_or_else(|| AppError::Internal(t(Message::ConfigDirUnavailable).to_string()))
}

/// Directory holding state that must survive between invocations.
///
/// State is what the CLI wants to remember across runs without it being
/// configuration the operator edits or a cache it may delete at will:
/// which upstream has been failing, how far a `--batch` got before it
/// died.
///
/// # The platform trap this function exists to absorb
///
/// `ProjectDirs::state_dir` returns `Option`, and it is `None` on macOS
/// and on Windows — measured in `directories-6.0.0/src/lib.rs:271-275`,
/// where the table carries an em dash for both. Calling it directly and
/// giving up on `None` would make every feature built on state silently
/// not exist on two of this project's three platform families, with
/// exit 0 and no message. `data_local_dir` is the fallback because it
/// is the per-machine, non-roaming directory on exactly the platforms
/// that lack a state directory, which is the same intent under a
/// different name.
///
/// # Errors
///
/// Returns [`AppError::Internal`] when the platform exposes no home
/// directory, which is the only condition under which `directories`
/// fails.
pub fn state_dir() -> AppResult<PathBuf> {
    project_dirs()
        .map(|d| {
            d.state_dir()
                .unwrap_or_else(|| d.data_local_dir())
                .to_path_buf()
        })
        .ok_or_else(|| AppError::Internal(t(Message::ConfigDirUnavailable).to_string()))
}

/// Absolute path of `config.toml`.
///
/// # Errors
///
/// Propagates the failure of [`config_dir`].
pub fn config_file_path() -> AppResult<PathBuf> {
    Ok(config_dir()?.join(CONFIG_FILE_NAME))
}

/// Path of the auto-discovered config file, when the file exists.
///
/// Returns `None` both when the platform exposes no config directory and
/// when the file is simply absent — neither is an error, because running
/// without a config file is the normal case.
#[must_use]
pub fn discover() -> Option<PathBuf> {
    let path = config_file_path().ok()?;
    path.is_file().then_some(path)
}

/// A loaded configuration file, addressable by dotted key.
#[derive(Debug, Clone)]
pub struct ConfigStore {
    path: PathBuf,
    table: toml::Table,
}

impl ConfigStore {
    /// Load the XDG config file, or start from an empty table when it
    /// does not exist yet.
    ///
    /// # Errors
    ///
    /// - [`AppError::Internal`] when the config directory cannot be
    ///   resolved.
    /// - [`AppError::Config`] when the file exists but is unreadable or
    ///   is not valid TOML.
    pub fn load() -> AppResult<Self> {
        let path = config_file_path()?;
        Self::load_from(&path)
    }

    /// Load a specific file, or start empty when it does not exist.
    ///
    /// # Errors
    ///
    /// Returns [`AppError::Config`] when the file exists but cannot be
    /// read or parsed.
    pub fn load_from(path: &Path) -> AppResult<Self> {
        let table = if path.is_file() {
            let text = std::fs::read_to_string(path).map_err(|e| {
                AppError::Config(format!(
                    "{} {}: {e}",
                    t(Message::ConfigCouldNotRead),
                    path.display()
                ))
            })?;
            text.parse::<toml::Table>().map_err(|e| {
                AppError::Config(format!(
                    "{} {}: {e}",
                    path.display(),
                    t(Message::ConfigNotValidToml)
                ))
            })?
        } else {
            toml::Table::new()
        };
        Ok(Self {
            path: path.to_path_buf(),
            table,
        })
    }

    /// Path this store reads from and writes to.
    #[must_use]
    pub fn path(&self) -> &Path {
        &self.path
    }

    /// The raw table, for callers that merge it into the CLI.
    #[must_use]
    pub fn table(&self) -> &toml::Table {
        &self.table
    }

    /// Every set key, flattened to its dotted form, in sorted order.
    #[must_use]
    pub fn flattened(&self) -> BTreeMap<String, String> {
        let mut out = BTreeMap::new();
        flatten_into(&self.table, String::new(), &mut out);
        out
    }

    /// Read one dotted key.
    #[must_use]
    pub fn get(&self, key: &str) -> Option<&toml::Value> {
        let mut cursor: Option<&toml::Value> = None;
        for (idx, segment) in key.split('.').enumerate() {
            cursor = if idx == 0 {
                self.table.get(segment)
            } else {
                cursor?.as_table()?.get(segment)
            };
            cursor?;
        }
        cursor
    }

    /// Write one dotted key, parsing `raw` according to the registry.
    ///
    /// # Errors
    ///
    /// - [`AppError::InvalidUsage`] when the key is not in the registry
    ///   or `raw` does not parse as the declared type.
    pub fn set(&mut self, key: &str, raw: &str) -> AppResult<()> {
        let spec = spec(key).ok_or_else(|| unknown_key(key))?;
        let value = parse_value(spec, raw)?;
        let mut segments: Vec<&str> = key.split('.').collect();
        // `split` on a non-empty string always yields at least one item,
        // so the pop cannot fail; the fallback keeps the code total.
        let leaf = segments.pop().unwrap_or(key);
        let mut cursor = &mut self.table;
        for segment in segments {
            let entry = cursor
                .entry(segment.to_string())
                .or_insert_with(|| toml::Value::Table(toml::Table::new()));
            if !entry.is_table() {
                *entry = toml::Value::Table(toml::Table::new());
            }
            match entry.as_table_mut() {
                Some(t) => cursor = t,
                // Unreachable: `entry` was just forced to be a table.
                None => return Err(unknown_key(key)),
            }
        }
        cursor.insert(leaf.to_string(), value);
        Ok(())
    }

    /// Remove one dotted key, restoring the compiled default.
    ///
    /// Removing a key that was never set succeeds, so a script never has
    /// to know the previous state.
    ///
    /// # Errors
    ///
    /// Returns [`AppError::InvalidUsage`] when the key is not in the
    /// registry.
    pub fn unset(&mut self, key: &str) -> AppResult<()> {
        if spec(key).is_none() {
            return Err(unknown_key(key));
        }
        let mut segments: Vec<&str> = key.split('.').collect();
        let leaf = segments.pop().unwrap_or(key);
        let mut cursor = &mut self.table;
        for segment in segments {
            match cursor.get_mut(segment).and_then(toml::Value::as_table_mut) {
                Some(t) => cursor = t,
                None => return Ok(()),
            }
        }
        cursor.remove(leaf);
        Ok(())
    }

    /// Persist the table, creating the parent directory if needed.
    ///
    /// On Unix the file is created with mode `0600`: the registry can
    /// carry credentials, and a credential must not be world-readable.
    ///
    /// # Errors
    ///
    /// - [`AppError::Io`] when the directory or the file cannot be
    ///   written.
    /// - [`AppError::Config`] when the table cannot be serialised.
    pub fn save(&self) -> AppResult<()> {
        if let Some(parent) = self.path.parent() {
            std::fs::create_dir_all(parent).map_err(|e| {
                AppError::Io(std::io::Error::other(format!(
                    "creating {}: {e}",
                    parent.display()
                )))
            })?;
        }
        let text = toml::to_string_pretty(&self.table)
            .map_err(|e| AppError::Config(format!("could not serialise config: {e}")))?;
        std::fs::write(&self.path, text.as_bytes()).map_err(|e| {
            AppError::Io(std::io::Error::other(format!(
                "writing {}: {e}",
                self.path.display()
            )))
        })?;
        restrict_permissions(&self.path)
    }
}

/// Tighten the config file to owner-only access.
#[cfg(unix)]
fn restrict_permissions(path: &Path) -> AppResult<()> {
    use std::os::unix::fs::PermissionsExt;
    std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)).map_err(|e| {
        AppError::Io(std::io::Error::other(format!(
            "restricting permissions on {}: {e}",
            path.display()
        )))
    })
}

/// Windows and other platforms inherit the directory ACL; there is no
/// portable mode bit to set.
#[cfg(not(unix))]
fn restrict_permissions(_path: &Path) -> AppResult<()> {
    Ok(())
}

/// Build the [`AppError`] for a key absent from the registry.
///
/// This is the single wording for the condition: the store and the
/// `config` subcommand both route through it, so the sentence exists
/// once and is translated once.
#[must_use]
pub fn unknown_key(key: &str) -> AppError {
    AppError::InvalidUsage(format!(
        "{} `{key}`; {}",
        t(Message::ConfigUnknownKey),
        t(Message::ConfigUnknownKeyHint)
    ))
}

/// Parse `raw` into the TOML value the spec declares.
fn parse_value(spec: &KeySpec, raw: &str) -> AppResult<toml::Value> {
    match spec.kind {
        KeyKind::Str => Ok(toml::Value::String(raw.to_string())),
        KeyKind::Int => raw
            .trim()
            .parse::<i64>()
            .map(toml::Value::Integer)
            .map_err(|e| {
                AppError::InvalidUsage(format!(
                    "`{}` {}: {e}",
                    spec.key,
                    t(Message::ConfigExpectsInteger)
                ))
            }),
        KeyKind::Bool => match raw.trim() {
            "true" | "1" | "yes" => Ok(toml::Value::Boolean(true)),
            "false" | "0" | "no" => Ok(toml::Value::Boolean(false)),
            other => Err(AppError::InvalidUsage(format!(
                "`{}` {} `{other}`",
                spec.key,
                t(Message::ConfigExpectsBoolean)
            ))),
        },
        KeyKind::StrList => Ok(toml::Value::Array(
            raw.split(',')
                .map(str::trim)
                .filter(|s| !s.is_empty())
                .map(|s| toml::Value::String(s.to_string()))
                .collect(),
        )),
    }
}

/// Flatten a TOML table into dotted `key = rendered value` pairs.
fn flatten_into(table: &toml::Table, prefix: String, out: &mut BTreeMap<String, String>) {
    for (key, value) in table {
        let dotted = if prefix.is_empty() {
            key.clone()
        } else {
            format!("{prefix}.{key}")
        };
        match value {
            toml::Value::Table(inner) => flatten_into(inner, dotted, out),
            other => {
                out.insert(dotted, render_toml(other));
            }
        }
    }
}

/// Render a scalar TOML value for `config show` / `config get`.
fn render_toml(value: &toml::Value) -> String {
    match value {
        toml::Value::String(s) => s.clone(),
        toml::Value::Array(items) => items.iter().map(render_toml).collect::<Vec<_>>().join(","),
        other => other.to_string(),
    }
}

/// Process-wide tuning table, installed once by `main` after the config
/// file is loaded.
static TUNING: OnceLock<toml::Table> = OnceLock::new();

/// Publish the loaded table so tuning accessors can read it.
///
/// Calling this more than once is a no-op: the first table wins, which
/// keeps a one-shot binary deterministic.
pub fn install_tuning(table: toml::Table) {
    let _ = TUNING.set(table);
}

/// Read a tuning key as an unsigned integer.
///
/// `None` means "the operator did not configure this", and the call site
/// must keep using its compiled default. That is deliberate: a tuning
/// key never invents a value the source did not already have.
#[must_use]
pub fn tuning_u64(key: &str) -> Option<u64> {
    lookup_tuning(key)?.as_integer()?.try_into().ok()
}

/// Read a tuning key as a boolean.
#[must_use]
pub fn tuning_bool(key: &str) -> Option<bool> {
    lookup_tuning(key)?.as_bool()
}

/// Read a tuning key as a string.
#[must_use]
pub fn tuning_string(key: &str) -> Option<String> {
    Some(lookup_tuning(key)?.as_str()?.to_string())
}

/// Read a tuning key as a list of strings.
#[must_use]
pub fn tuning_str_list(key: &str) -> Option<Vec<String>> {
    let array = lookup_tuning(key)?.as_array()?;
    Some(
        array
            .iter()
            .filter_map(|v| v.as_str().map(str::to_string))
            .collect(),
    )
}

/// Resolve an integer tuning key, refusing values outside `min..=max`.
///
/// A persisted value outside the range is discarded and `default` is
/// returned, with one warning on stderr. That is deliberate: these keys
/// govern timeouts, body ceilings and concurrency budgets, and a value
/// such as a zero timeout would wedge the process with no diagnostic.
///
/// # Panics
///
/// Never. An absent, mistyped or out-of-range value all resolve to
/// `default`.
#[must_use]
pub fn tuning_u64_in_range(key: &str, default: u64, min: u64, max: u64) -> u64 {
    match tuning_u64(key) {
        Some(value) if value >= min && value <= max => value,
        Some(value) => {
            tracing::warn!(
                key,
                value,
                min,
                max,
                default,
                "configured value is out of range; keeping the compiled default"
            );
            default
        }
        None => default,
    }
}

/// [`tuning_u64_in_range`] for a key consumed as a `usize`.
#[must_use]
pub fn tuning_usize_in_range(key: &str, default: usize, min: usize, max: usize) -> usize {
    let resolved = tuning_u64_in_range(key, default as u64, min as u64, max as u64);
    usize::try_from(resolved).unwrap_or(default)
}

/// [`tuning_u64_in_range`] for a key consumed as a `u32`.
#[must_use]
pub fn tuning_u32_in_range(key: &str, default: u32, min: u32, max: u32) -> u32 {
    let resolved = tuning_u64_in_range(key, u64::from(default), u64::from(min), u64::from(max));
    u32::try_from(resolved).unwrap_or(default)
}

/// Resolve a boolean tuning key, falling back to `default`.
#[must_use]
pub fn tuning_bool_or(key: &str, default: bool) -> bool {
    tuning_bool(key).unwrap_or(default)
}

/// Resolve a string tuning key, refusing an empty value.
///
/// An empty string is never a meaningful header value, selector or
/// geometry, so it is treated the same way as an out-of-range integer.
#[must_use]
pub fn tuning_string_or(key: &str, default: &str) -> String {
    match tuning_string(key) {
        Some(value) if !value.trim().is_empty() => value,
        Some(_) => {
            tracing::warn!(
                key,
                "configured value is empty; keeping the compiled default"
            );
            default.to_string()
        }
        None => default.to_string(),
    }
}

/// Resolve a string-list tuning key, refusing an empty list.
///
/// An operator who genuinely wants "no entries" has a dedicated boolean
/// for it wherever that is meaningful; an empty list here is far more
/// often a mistyped `config set`.
#[must_use]
pub fn tuning_str_list_or(key: &str, default: &[&str]) -> Vec<String> {
    match tuning_str_list(key) {
        Some(list) if !list.is_empty() => list,
        Some(_) => {
            tracing::warn!(
                key,
                "configured list is empty; keeping the compiled default"
            );
            default.iter().map(|s| (*s).to_string()).collect()
        }
        None => default.iter().map(|s| (*s).to_string()).collect(),
    }
}

/// Resolve a string-list tuning key whose entries are `left=right`
/// pairs, refusing an empty list.
///
/// Entries without a `=` are skipped with a warning rather than
/// aborting the run: one malformed pair must not cost the operator the
/// whole table.
#[must_use]
pub fn tuning_pairs_or(key: &str, default: &[(&str, &str)]) -> Vec<(String, String)> {
    let compiled = || -> Vec<(String, String)> {
        default
            .iter()
            .map(|(l, r)| ((*l).to_string(), (*r).to_string()))
            .collect()
    };
    let Some(list) = tuning_str_list(key) else {
        return compiled();
    };
    let mut out = Vec::with_capacity(list.len());
    for entry in &list {
        match entry.split_once('=') {
            Some((left, right)) if !left.trim().is_empty() && !right.trim().is_empty() => {
                out.push((left.trim().to_string(), right.trim().to_string()));
            }
            _ => tracing::warn!(key, entry, "ignoring an entry that is not `left=right`"),
        }
    }
    if out.is_empty() {
        tracing::warn!(
            key,
            "configured list yielded no usable pair; keeping the compiled default"
        );
        return compiled();
    }
    out
}

/// Effective values of the flags that also exist as tuning keys.
///
/// A tuning accessor is reachable from code that never sees the parsed
/// [`crate::cli::Cli`] — a provider, for instance. This table carries
/// the already-merged value of those few flags so such code observes
/// the documented precedence: command line, then XDG file, then the
/// compiled default.
static FLAG_OVERRIDES: OnceLock<toml::Table> = OnceLock::new();

/// Publish the effective value of the flags that shadow a tuning key.
///
/// Called once, from the command dispatcher, after the CLI and the
/// config file have been merged. Later calls are no-ops, which keeps a
/// one-shot binary deterministic.
pub fn install_flag_overrides(table: toml::Table) {
    let _ = FLAG_OVERRIDES.set(table);
}

/// Walk the installed tables by dotted key, flags first.
fn lookup_tuning(key: &str) -> Option<&'static toml::Value> {
    if let Some(value) = FLAG_OVERRIDES.get().and_then(|t| walk(t, key)) {
        return Some(value);
    }
    walk(TUNING.get()?, key)
}

/// Walk one table by dotted key.
fn walk(table: &'static toml::Table, key: &str) -> Option<&'static toml::Value> {
    let mut cursor: Option<&toml::Value> = None;
    for (idx, segment) in key.split('.').enumerate() {
        cursor = if idx == 0 {
            table.get(segment)
        } else {
            cursor?.as_table()?.get(segment)
        };
        cursor?;
    }
    cursor
}

#[cfg(test)]
mod tests {
    use super::*;

    fn tmp_path(name: &str) -> PathBuf {
        std::env::temp_dir().join(format!("ylc_config_test_{name}.toml"))
    }

    #[test]
    fn registry_has_no_duplicate_keys() {
        let mut seen: Vec<&str> = KEYS.iter().map(|s| s.key).collect();
        let total = seen.len();
        seen.sort_unstable();
        seen.dedup();
        assert_eq!(seen.len(), total, "the registry must not repeat a key");
    }

    /// Looks up one key's published description, or fails naming it.
    fn doc_for(key: &str) -> &'static str {
        KEYS.iter()
            .find(|spec| spec.key == key)
            .unwrap_or_else(|| panic!("the registry must carry a `{key}` key"))
            .doc
    }

    /// The `format` key's published description must name every
    /// spelling the parser actually accepts.
    ///
    /// This is a gate and not a spelling check: the expected set is
    /// DERIVED from `FormatArg` through `ValueEnum`, so adding a fourth
    /// output format fails here until the description that
    /// `config list-keys` publishes has been taught about it.
    ///
    /// It was written after the description read `Output format: txt or
    /// srt` for a parser that had accepted `vtt` since the day the
    /// CHANGELOG promised it. A description copied by hand drifts from
    /// the enum it describes, and `config list-keys` is the surface an
    /// automated caller reads.
    #[test]
    fn the_format_key_description_names_every_accepted_spelling() {
        use clap::ValueEnum;

        let doc = doc_for("format");
        let mut checked = 0_usize;
        for variant in crate::cli::FormatArg::value_variants() {
            let spelling = variant
                .to_possible_value()
                .expect("no FormatArg variant is skipped")
                .get_name()
                .to_string();
            assert!(
                doc.contains(&spelling),
                "`config list-keys` describes `format` as {doc:?}, which never \
                 mentions the accepted spelling {spelling:?}"
            );
            checked += 1;
        }

        // A control: an empty variant list would pass the loop above
        // without comparing anything.
        assert!(
            checked >= 2,
            "only {checked} spelling(s) were compared, so this test proved nothing"
        );
    }

    /// The `timeout` key and the `--timeout` flag describe ONE surface,
    /// so they must say the same sentence.
    ///
    /// Equality is the assertion on purpose. The two texts drifted once
    /// already: the flag's help was corrected on 2026-08-31, the key's
    /// description kept the old `HTTP request timeout in seconds`, and
    /// the result was a registry telling an automated caller the exact
    /// opposite of what the flag told a human. Anything weaker than
    /// equality lets them drift again.
    #[test]
    fn the_timeout_key_and_its_flag_tell_the_same_story() {
        use clap::CommandFactory;

        let command = crate::cli::Cli::command();
        let flag = command
            .get_arguments()
            .find(|a| a.get_id() == "timeout")
            .expect("the CLI must carry a --timeout flag");
        let help = flag
            .get_help()
            .expect("--timeout must carry help text")
            .to_string();

        assert_eq!(
            doc_for("timeout"),
            help,
            "the `timeout` config key and the `--timeout` flag describe the \
             same ceiling and must not word it differently"
        );
    }

    #[test]
    fn every_registry_key_resolves_through_spec() {
        for entry in KEYS {
            assert!(spec(entry.key).is_some(), "{} must resolve", entry.key);
        }
        assert!(spec("definitely.not.a.key").is_none());
    }

    #[test]
    fn set_get_and_unset_round_trip_a_dotted_key() {
        let mut store = ConfigStore {
            path: tmp_path("roundtrip"),
            table: toml::Table::new(),
        };
        store
            .set("net.waf.max_consecutive_failures", "7")
            .expect("set succeeds");
        assert_eq!(
            store
                .get("net.waf.max_consecutive_failures")
                .and_then(toml::Value::as_integer),
            Some(7)
        );
        store
            .unset("net.waf.max_consecutive_failures")
            .expect("unset succeeds");
        assert!(store.get("net.waf.max_consecutive_failures").is_none());
    }

    #[test]
    fn unsetting_an_absent_key_succeeds() {
        let mut store = ConfigStore {
            path: tmp_path("absent"),
            table: toml::Table::new(),
        };
        assert!(store.unset("cli.max_url_chars").is_ok());
    }

    #[test]
    fn unknown_key_is_rejected_on_set_and_unset() {
        let mut store = ConfigStore {
            path: tmp_path("unknown"),
            table: toml::Table::new(),
        };
        assert!(matches!(
            store.set("nope", "1"),
            Err(AppError::InvalidUsage(_))
        ));
        assert!(matches!(
            store.unset("nope"),
            Err(AppError::InvalidUsage(_))
        ));
    }

    #[test]
    fn integer_key_rejects_non_numeric_input() {
        let mut store = ConfigStore {
            path: tmp_path("badint"),
            table: toml::Table::new(),
        };
        assert!(store.set("timeout", "abc").is_err());
        assert!(store.set("timeout", "45").is_ok());
    }

    #[test]
    fn string_list_key_splits_on_commas() {
        let mut store = ConfigStore {
            path: tmp_path("list"),
            table: toml::Table::new(),
        };
        store
            .set("net.session.header_order", "host, accept ,user-agent")
            .expect("set succeeds");
        let flat = store.flattened();
        assert_eq!(
            flat.get("net.session.header_order").map(String::as_str),
            Some("host,accept,user-agent")
        );
    }

    #[test]
    fn save_then_load_preserves_the_table() {
        let path = tmp_path("persist");
        std::fs::remove_file(&path).ok();
        let mut store = ConfigStore {
            path: path.clone(),
            table: toml::Table::new(),
        };
        store.set("timeout", "45").expect("set succeeds");
        // A DOTTED key is the whole point of the second assertion: it
        // proves the nesting survives the TOML round trip, and a flat
        // key would prove nothing about it. `browser.viewport_width`
        // played this role until 2026-09-04, when the browser keys were
        // removed with the subsystem; `stealth.seed` is the surviving
        // integer key that is nested one level deep.
        store.set("stealth.seed", "1366").expect("set");
        store.save().expect("save succeeds");

        let reloaded = ConfigStore::load_from(&path).expect("load succeeds");
        assert_eq!(
            reloaded.get("timeout").and_then(toml::Value::as_integer),
            Some(45)
        );
        assert_eq!(
            reloaded
                .get("stealth.seed")
                .and_then(toml::Value::as_integer),
            Some(1366)
        );
        std::fs::remove_file(&path).ok();
    }

    #[cfg(unix)]
    #[test]
    fn saved_config_is_owner_only() {
        use std::os::unix::fs::PermissionsExt;
        let path = tmp_path("perms");
        std::fs::remove_file(&path).ok();
        let mut store = ConfigStore {
            path: path.clone(),
            table: toml::Table::new(),
        };
        store.set("timeout", "10").expect("set succeeds");
        store.save().expect("save succeeds");
        let mode = std::fs::metadata(&path)
            .expect("metadata")
            .permissions()
            .mode();
        assert_eq!(mode & 0o777, 0o600, "config must not be world-readable");
        std::fs::remove_file(&path).ok();
    }

    /// The keys Mission C introduced must be addressable by
    /// `config set` / `config get`, which is what `spec` gates.
    #[test]
    fn concurrency_and_offline_keys_are_registered() {
        for key in [
            "offline",
            "jobs",
            "cli.max_jobs",
            "net.per_host_concurrency",
            "net.throttle_interval_ms",
        ] {
            assert!(spec(key).is_some(), "{key} must be in the registry");
        }
    }

    /// A key outside its declared range falls back to the compiled
    /// default instead of being applied. Without an installed table the
    /// same call already yields the default, which is the other half of
    /// the contract.
    #[test]
    fn out_of_range_and_absent_values_both_yield_the_default() {
        assert_eq!(tuning_u64_in_range("definitely.not.a.key", 7, 1, 10), 7);
        assert_eq!(tuning_usize_in_range("definitely.not.a.key", 3, 1, 10), 3);
        assert_eq!(tuning_u32_in_range("definitely.not.a.key", 5, 1, 10), 5);
        assert!(!tuning_bool_or("definitely.not.a.key", false));
        assert_eq!(tuning_string_or("definitely.not.a.key", "x"), "x");
        assert_eq!(
            tuning_str_list_or("definitely.not.a.key", &["a"]),
            vec!["a"]
        );
        assert_eq!(
            tuning_pairs_or("definitely.not.a.key", &[("a", "b")]),
            vec![("a".to_string(), "b".to_string())]
        );
    }

    #[test]
    fn tuning_accessors_return_none_without_an_installed_table() {
        // `install_tuning` may already have run in another test in this
        // binary; either way an unknown key must resolve to `None` and
        // leave the call site on its compiled default.
        assert_eq!(tuning_u64("definitely.not.a.key"), None);
        assert_eq!(tuning_bool("definitely.not.a.key"), None);
        assert_eq!(tuning_string("definitely.not.a.key"), None);
        assert_eq!(tuning_str_list("definitely.not.a.key"), None);
    }

    /// State must resolve wherever configuration resolves.
    ///
    /// `ProjectDirs::state_dir` is `None` on macOS and Windows, so a
    /// direct call would make every feature built on state vanish
    /// there while `config_dir` kept working — a difference no test
    /// running on Linux could ever observe. Tying the two together
    /// states the property in a form that holds on all three families
    /// and fails loudly if the fallback is ever removed.
    #[test]
    fn state_resolves_wherever_configuration_resolves() {
        assert_eq!(
            config_dir().is_ok(),
            state_dir().is_ok(),
            "state_dir must not fail on a platform where config_dir succeeds"
        );
        if let Ok(dir) = state_dir() {
            assert!(
                dir.is_absolute(),
                "a relative state directory would follow the working directory: {}",
                dir.display()
            );
        }
    }
}