clapfig 0.17.0

Rich, layered configuration for Rust CLI apps
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
//! Builder API for configuring and loading layered configuration.
//!
//! [`Clapfig::builder()`] is the entry point. The builder follows a "set what
//! you need, load" pattern: [`app_name()`](ClapfigBuilder::app_name) derives
//! sensible defaults (file name, search paths, env prefix), and everything
//! else is optional overrides. This means the minimal setup is two calls
//! (`.app_name().load()`), while the full surface is available for apps that
//! need fine-grained control.
//!
//! The builder also handles [`ConfigAction`](crate::ConfigAction) dispatch
//! via [`handle()`](ClapfigBuilder::handle) — the same builder that loads
//! config can also process `config get`, `config set`, and other operations.
//! This keeps all configuration wiring in one place.

use std::marker::PhantomData;
use std::path::PathBuf;

use confique::Config;
use serde::{Deserialize, Serialize};

use crate::error::ClapfigError;
use crate::file;
use crate::flatten;
use crate::ops::{self, ConfigResult};
use crate::overrides;
use crate::persist;
use crate::resolver::Resolver;
use crate::types::{ConfigAction, Layer, SearchMode, SearchPath};

/// Entry point for building a clapfig configuration.
pub struct Clapfig;

impl Clapfig {
    pub fn builder<C: Config>() -> ClapfigBuilder<C> {
        ClapfigBuilder::new()
    }
}

/// Boxed post-merge validation hook.
///
/// See [`ClapfigBuilder::post_validate`] for how it is invoked.
pub(crate) type PostValidateHook<C> = Box<dyn Fn(&C) -> Result<(), String> + Send + Sync>;

/// Builder for configuring and loading layered configuration.
///
/// Controls three orthogonal axes (see [`types`](crate::types) for the full picture):
///
/// - **Discovery**: [`search_paths()`](Self::search_paths) — where to look for config files.
/// - **Resolution**: [`search_mode()`](Self::search_mode) — merge all or pick one.
/// - **Persistence**: [`persist_scope()`](Self::persist_scope) — named targets for writes.
pub struct ClapfigBuilder<C: Config> {
    app_name: Option<String>,
    file_name: Option<String>,
    search_paths: Option<Vec<SearchPath>>,
    search_mode: SearchMode,
    persist_scopes: Vec<(String, SearchPath)>,
    env_prefix: Option<String>,
    env_enabled: bool,
    strict: bool,
    #[cfg(feature = "url")]
    url_overrides: Vec<(String, toml::Value)>,
    cli_overrides: Vec<(String, toml::Value)>,
    layer_order: Option<Vec<Layer>>,
    post_validate: Option<PostValidateHook<C>>,
    _phantom: PhantomData<C>,
}

impl<C: Config> ClapfigBuilder<C> {
    fn new() -> Self {
        Self {
            app_name: None,
            file_name: None,
            search_paths: None,
            search_mode: SearchMode::default(),
            persist_scopes: Vec::new(),
            env_prefix: None,
            env_enabled: true,
            strict: true,
            #[cfg(feature = "url")]
            url_overrides: Vec::new(),
            cli_overrides: Vec::new(),
            layer_order: None,
            post_validate: None,
            _phantom: PhantomData,
        }
    }

    /// Set the application name. This derives sensible defaults:
    /// - `file_name` → `"{app_name}.toml"`
    /// - `search_paths` → `[SearchPath::Platform]`
    /// - `env_prefix` → `"{APP_NAME}"` (uppercased)
    pub fn app_name(mut self, name: &str) -> Self {
        self.app_name = Some(name.to_string());
        self
    }

    /// Override the config file name (default: `"{app_name}.toml"`).
    pub fn file_name(mut self, name: &str) -> Self {
        self.file_name = Some(name.to_string());
        self
    }

    /// Replace the default search paths entirely.
    ///
    /// Paths are listed in **priority-ascending** order: the last entry has the
    /// highest priority. See [`SearchPath`] for the available variants.
    pub fn search_paths(mut self, paths: Vec<SearchPath>) -> Self {
        self.search_paths = Some(paths);
        self
    }

    /// Append a search path without replacing the defaults.
    /// If no paths have been set yet, starts from the default `[Platform]`.
    pub fn add_search_path(mut self, path: SearchPath) -> Self {
        self.search_paths
            .get_or_insert_with(|| vec![SearchPath::Platform])
            .push(path);
        self
    }

    /// Set the search mode (default: [`SearchMode::Merge`]).
    ///
    /// - [`Merge`](SearchMode::Merge): all found config files are deep-merged,
    ///   later (higher-priority) files overriding earlier ones.
    /// - [`FirstMatch`](SearchMode::FirstMatch): only the single highest-priority
    ///   config file found is used.
    pub fn search_mode(mut self, mode: SearchMode) -> Self {
        self.search_mode = mode;
        self
    }

    /// Add a named persist scope.
    ///
    /// Scopes are named config file targets for `config set`/`unset` (and optionally
    /// `config get`/`list` with `--scope`). The first scope added is the default
    /// for write operations when no `--scope` is specified.
    ///
    /// Scope paths are automatically added to the search paths (if not already
    /// present) so that persisted values are discoverable in the merged view.
    ///
    /// Must be a single-directory variant (`Platform`, `Home`, `Cwd`, or `Path`).
    /// Using [`Ancestors`](SearchPath::Ancestors) produces an error at handle time.
    ///
    /// If no scopes are configured, `config set` returns [`ClapfigError::NoPersistPath`].
    pub fn persist_scope(mut self, name: &str, path: SearchPath) -> Self {
        self.persist_scopes.push((name.to_string(), path));
        self
    }

    /// Override the environment variable prefix (default: uppercased `app_name`).
    pub fn env_prefix(mut self, prefix: &str) -> Self {
        self.env_prefix = Some(prefix.to_string());
        self
    }

    /// Disable environment variable loading entirely.
    pub fn no_env(mut self) -> Self {
        self.env_enabled = false;
        self
    }

    /// Enable or disable strict mode (default: `true`).
    /// In strict mode, unknown keys in config files produce errors.
    pub fn strict(mut self, strict: bool) -> Self {
        self.strict = strict;
        self
    }

    /// Set a custom layer merge order.
    ///
    /// Layers listed later override earlier ones. The default order is
    /// `[Files, Env, Url, Cli]` — the common-sense precedence where code
    /// defaults are lowest and explicit overrides are highest.
    ///
    /// Omit a layer to exclude it from merging entirely. Duplicate layers
    /// are applied in the order given (the second occurrence overrides the first).
    ///
    /// # Example
    ///
    /// ```ignore
    /// // Files override env vars; CLI still wins
    /// Clapfig::builder::<MyConfig>()
    ///     .app_name("myapp")
    ///     .layer_order(vec![Layer::Env, Layer::Files, Layer::Cli])
    ///     .load()?;
    /// ```
    pub fn layer_order(mut self, order: Vec<Layer>) -> Self {
        self.layer_order = Some(order);
        self
    }

    /// Register a post-merge validation hook.
    ///
    /// The hook runs after all layers have been merged and confique has
    /// type-validated the result, but before [`load()`](Self::load) returns
    /// the configuration. It receives the final `&C` and returns
    /// `Ok(())` to accept it or `Err(String)` to reject it with a message
    /// that will be wrapped in [`ClapfigError::PostValidationFailed`].
    ///
    /// Use it for constraints confique can't express: numeric ranges,
    /// cross-field invariants ("if A is set then B must be set"), enum
    /// combinations, filesystem preconditions, anything that depends on
    /// the merged value rather than on a single field's type.
    ///
    /// Calling this method more than once replaces the previous hook.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let config: AppConfig = Clapfig::builder()
    ///     .app_name("myapp")
    ///     .post_validate(|c| {
    ///         if c.port < 1024 {
    ///             return Err(format!("port {} is below 1024", c.port));
    ///         }
    ///         Ok(())
    ///     })
    ///     .load()?;
    /// ```
    pub fn post_validate<F>(mut self, f: F) -> Self
    where
        F: Fn(&C) -> Result<(), String> + Send + Sync + 'static,
    {
        self.post_validate = Some(Box::new(f));
        self
    }

    /// Add URL query parameters as a config layer.
    ///
    /// Parses the query string (e.g. `"port=9090&database.url=pg://prod"`) into
    /// config overrides. Keys use `.` for nesting, values are percent-decoded and
    /// parsed with the same heuristic as env vars (bool > int > float > string).
    ///
    /// A leading `?` is stripped if present.
    ///
    /// By default, URL parameters sit between env vars and CLI overrides in
    /// precedence: defaults < files < env < **URL** < CLI. This position can
    /// be changed with [`layer_order()`](Self::layer_order).
    #[cfg(feature = "url")]
    pub fn url_query(mut self, query: &str) -> Self {
        self.url_overrides
            .extend(crate::url::query_to_overrides(query));
        self
    }

    /// Add a CLI override. `None` values are ignored (useful for optional clap args).
    pub fn cli_override<V: Into<toml::Value>>(mut self, key: &str, value: Option<V>) -> Self {
        if let Some(v) = value {
            self.cli_overrides.push((key.to_string(), v.into()));
        }
        self
    }

    /// Add CLI overrides from any serializable source, auto-matching by field name.
    ///
    /// Serializes `source` into flat key-value pairs, skips `None` values, and keeps
    /// only keys that match config fields in `C`. Non-matching keys are silently ignored,
    /// so clap-only fields like `command` or `verbose` are automatically excluded.
    ///
    /// Works with clap-derived structs, `HashMap`s, or anything implementing `Serialize`.
    ///
    /// Composes with [`cli_override`](Self::cli_override) — both push to the same
    /// override list. Later calls take precedence.
    pub fn cli_overrides_from<S: Serialize>(mut self, source: &S) -> Self {
        let pairs = flatten::flatten(source)
            .expect("clapfig: failed to flatten CLI source for auto-matching");
        let valid = overrides::valid_keys(&C::META);
        for (key, value) in pairs {
            if let Some(v) = value
                && valid.contains(&key)
            {
                self.cli_overrides.push((key, v));
            }
        }
        self
    }

    /// Resolve the effective app name, or error if not set.
    fn effective_app_name(&self) -> Result<&str, ClapfigError> {
        self.app_name
            .as_deref()
            .ok_or(ClapfigError::AppNameRequired)
    }

    /// Resolve the effective file name.
    fn effective_file_name(&self) -> Result<String, ClapfigError> {
        if let Some(name) = &self.file_name {
            return Ok(name.clone());
        }
        let app = self.effective_app_name()?;
        Ok(format!("{app}.toml"))
    }

    /// Resolve the effective search paths.
    ///
    /// Starts from the user-configured paths (or `[Platform]` default), then
    /// appends any persist scope paths not already present.
    fn effective_search_paths(&self) -> Vec<SearchPath> {
        let mut paths = if let Some(paths) = &self.search_paths {
            paths.clone()
        } else {
            vec![SearchPath::Platform]
        };

        for (_, scope_path) in &self.persist_scopes {
            if !paths.contains(scope_path) {
                paths.push(scope_path.clone());
            }
        }

        paths
    }

    /// Resolve the effective env prefix (None if env disabled).
    fn effective_env_prefix(&self) -> Result<Option<String>, ClapfigError> {
        if !self.env_enabled {
            return Ok(None);
        }
        if let Some(prefix) = &self.env_prefix {
            return Ok(Some(prefix.clone()));
        }
        let app = self.effective_app_name()?;
        Ok(Some(app.to_uppercase()))
    }

    /// Build a reusable [`Resolver<C>`] that captures the current builder
    /// state and can be called repeatedly with different starting directories.
    ///
    /// Use this when you need to resolve configuration at multiple points in a
    /// directory tree — for example, a static site generator visiting every
    /// content leaf, or a linter walking a repository. Each
    /// [`resolve_at(dir)`](Resolver::resolve_at) call interprets
    /// [`SearchPath::Cwd`] and [`SearchPath::Ancestors`] relative to `dir`, so
    /// every leaf gets its own independently merged configuration. Files read
    /// from disk are cached inside the resolver so repeated walks pay the
    /// disk+parse cost once per unique file.
    ///
    /// Any [`post_validate`](Self::post_validate) hook registered on the
    /// builder is captured into the resolver and fires on every `resolve_at`
    /// call.
    ///
    /// Returns [`ClapfigError::AppNameRequired`] if `.app_name()` was not
    /// called on the builder.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let resolver = Clapfig::builder::<MyConfig>()
    ///     .app_name("myapp")
    ///     .search_paths(vec![SearchPath::Ancestors(Boundary::Marker(".git"))])
    ///     .build_resolver()?;
    ///
    /// for leaf in walk_tree("./content") {
    ///     let cfg = resolver.resolve_at(&leaf)?;
    ///     render(&leaf, &cfg);
    /// }
    /// ```
    pub fn build_resolver(self) -> Result<Resolver<C>, ClapfigError> {
        let app_name = self.effective_app_name()?.to_string();
        let file_name = self.effective_file_name()?;
        let search_paths = self.effective_search_paths();
        let env_prefix = self.effective_env_prefix()?;

        Ok(Resolver::from_builder(
            app_name,
            file_name,
            search_paths,
            self.search_mode,
            env_prefix,
            self.strict,
            #[cfg(feature = "url")]
            self.url_overrides,
            self.cli_overrides,
            self.layer_order,
            self.post_validate,
        ))
    }

    /// Load and resolve the configuration through all layers.
    ///
    /// If a [`post_validate`](Self::post_validate) hook is registered, it
    /// runs after the merged configuration has been produced and any
    /// rejection is returned as [`ClapfigError::PostValidationFailed`].
    ///
    /// Internally this is equivalent to
    /// `self.build_resolver()?.resolve_at(std::env::current_dir()?)`, so all
    /// resolution logic lives in exactly one place (see [`Resolver`]).
    pub fn load(self) -> Result<C, ClapfigError>
    where
        C::Layer: for<'de> Deserialize<'de>,
    {
        let start_dir = std::env::current_dir().map_err(|e| ClapfigError::IoError {
            path: PathBuf::from("."),
            source: e,
        })?;
        self.build_resolver()?.resolve_at(start_dir)
    }

    /// Handle a `ConfigAction` and print the result to stdout.
    ///
    /// Convenience wrapper around [`handle()`](Self::handle) for CLI apps that
    /// print directly. For programmatic use or integration with other output
    /// frameworks, prefer [`handle()`](Self::handle) (returns a
    /// [`ConfigResult`]) or [`handle_to_string()`](Self::handle_to_string).
    pub fn handle_and_print(self, action: &ConfigAction) -> Result<(), ClapfigError>
    where
        C: Serialize,
        C::Layer: for<'de> Deserialize<'de>,
    {
        let result = self.handle(action)?;
        print!("{result}");
        Ok(())
    }

    /// Handle a `ConfigAction` and return the result as a `String`.
    ///
    /// Like [`handle_and_print()`](Self::handle_and_print), but captures the
    /// output instead of printing to stdout. Useful when integrating with
    /// output frameworks or custom rendering pipelines.
    ///
    /// ```ignore
    /// let output = builder.handle_to_string(&action)?;
    /// my_output_framework.write(&output);
    /// ```
    pub fn handle_to_string(self, action: &ConfigAction) -> Result<String, ClapfigError>
    where
        C: Serialize,
        C::Layer: for<'de> Deserialize<'de>,
    {
        self.handle(action).map(|r| r.to_string())
    }

    /// Resolve the file path for a persist scope.
    ///
    /// When `scope` is `None`, uses the default (first) scope.
    /// Returns `NoPersistPath` if no scopes are configured, or `UnknownScope`
    /// if the named scope doesn't exist.
    fn resolve_scope_persist_path(
        &self,
        scope: Option<&str>,
    ) -> Result<std::path::PathBuf, ClapfigError> {
        if self.persist_scopes.is_empty() {
            return Err(ClapfigError::NoPersistPath);
        }

        let app_name = self.effective_app_name()?;
        let file_name = self.effective_file_name()?;

        let (_, search_path) = match scope {
            None => &self.persist_scopes[0],
            Some(name) => self
                .persist_scopes
                .iter()
                .find(|(n, _)| n == name)
                .ok_or_else(|| ClapfigError::UnknownScope {
                    scope: name.to_string(),
                    available: self.persist_scopes.iter().map(|(n, _)| n.clone()).collect(),
                })?,
        };

        file::resolve_persist_path(search_path, &file_name, app_name)
    }

    /// Handle a `ConfigAction` and return the structured result.
    ///
    /// This is the core dispatch method for config operations (list, gen,
    /// schema, get, set, unset). Returns a [`ConfigResult`] enum that can be
    /// inspected programmatically or converted to a string via its `Display`
    /// implementation.
    ///
    /// For convenience wrappers see
    /// [`handle_and_print()`](Self::handle_and_print) (prints to stdout) and
    /// [`handle_to_string()`](Self::handle_to_string) (returns a `String`).
    pub fn handle(self, action: &ConfigAction) -> Result<ConfigResult, ClapfigError>
    where
        C: Serialize,
        C::Layer: for<'de> Deserialize<'de>,
    {
        match action {
            ConfigAction::List { scope } => match scope {
                None => {
                    let config = self.load()?;
                    ops::list_values(&config)
                }
                Some(name) => {
                    let path = self.resolve_scope_persist_path(Some(name))?;
                    ops::list_scope_file(&path)
                }
            },
            ConfigAction::Gen { output } => {
                let template = ops::generate_template::<C>();
                match output {
                    Some(path) => {
                        if let Some(parent) = path.parent() {
                            std::fs::create_dir_all(parent).map_err(|e| ClapfigError::IoError {
                                path: parent.to_path_buf(),
                                source: e,
                            })?;
                        }
                        std::fs::write(path, &template).map_err(|e| ClapfigError::IoError {
                            path: path.clone(),
                            source: e,
                        })?;
                        Ok(ConfigResult::TemplateWritten { path: path.clone() })
                    }
                    None => Ok(ConfigResult::Template(template)),
                }
            }
            ConfigAction::Schema { output } => {
                let schema = ops::generate_schema_string::<C>();
                match output {
                    Some(path) => {
                        if let Some(parent) = path.parent() {
                            std::fs::create_dir_all(parent).map_err(|e| ClapfigError::IoError {
                                path: parent.to_path_buf(),
                                source: e,
                            })?;
                        }
                        std::fs::write(path, &schema).map_err(|e| ClapfigError::IoError {
                            path: path.clone(),
                            source: e,
                        })?;
                        Ok(ConfigResult::SchemaWritten { path: path.clone() })
                    }
                    None => Ok(ConfigResult::Schema(schema)),
                }
            }
            ConfigAction::Get { key, scope } => match scope {
                None => {
                    let config = self.load()?;
                    ops::get_value(&config, key)
                }
                Some(name) => {
                    let path = self.resolve_scope_persist_path(Some(name))?;
                    ops::get_scope_value::<C>(&path, key)
                }
            },
            ConfigAction::Set { key, value, scope } => {
                let path = self.resolve_scope_persist_path(scope.as_deref())?;
                persist::persist_value::<C>(&path, key, value)
            }
            ConfigAction::Unset { key, scope } => {
                let path = self.resolve_scope_persist_path(scope.as_deref())?;
                persist::unset_value(&path, key)
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::fixtures::test::{EnumConfig, TestConfig};
    use crate::types::Boundary;
    use std::fs;
    use tempfile::TempDir;

    #[test]
    fn app_name_sets_defaults() {
        let builder = Clapfig::builder::<TestConfig>().app_name("myapp");
        assert_eq!(builder.effective_file_name().unwrap(), "myapp.toml");
        assert_eq!(
            builder.effective_env_prefix().unwrap(),
            Some("MYAPP".to_string())
        );
        assert_eq!(builder.effective_search_paths(), vec![SearchPath::Platform]);
    }

    #[test]
    fn override_file_name() {
        let builder = Clapfig::builder::<TestConfig>()
            .app_name("myapp")
            .file_name("custom.toml");
        assert_eq!(builder.effective_file_name().unwrap(), "custom.toml");
    }

    #[test]
    fn override_env_prefix() {
        let builder = Clapfig::builder::<TestConfig>()
            .app_name("myapp")
            .env_prefix("CUSTOM");
        assert_eq!(
            builder.effective_env_prefix().unwrap(),
            Some("CUSTOM".to_string())
        );
    }

    #[test]
    fn no_env_disables_prefix() {
        let builder = Clapfig::builder::<TestConfig>().app_name("myapp").no_env();
        assert_eq!(builder.effective_env_prefix().unwrap(), None);
    }

    #[test]
    fn search_paths_replace() {
        let builder = Clapfig::builder::<TestConfig>()
            .app_name("myapp")
            .search_paths(vec![SearchPath::Cwd]);
        assert_eq!(builder.effective_search_paths(), vec![SearchPath::Cwd]);
    }

    #[test]
    fn add_search_path_appends_to_defaults() {
        let builder = Clapfig::builder::<TestConfig>()
            .app_name("myapp")
            .add_search_path(SearchPath::Cwd);
        assert_eq!(
            builder.effective_search_paths(),
            vec![SearchPath::Platform, SearchPath::Cwd]
        );
    }

    #[test]
    fn add_search_path_appends_to_existing_list() {
        let builder = Clapfig::builder::<TestConfig>()
            .app_name("myapp")
            .search_paths(vec![SearchPath::Cwd])
            .add_search_path(SearchPath::Platform);
        assert_eq!(
            builder.effective_search_paths(),
            vec![SearchPath::Cwd, SearchPath::Platform]
        );
    }

    #[test]
    fn search_mode_defaults_to_merge() {
        let builder = Clapfig::builder::<TestConfig>().app_name("myapp");
        assert_eq!(builder.search_mode, SearchMode::Merge);
    }

    #[test]
    fn search_mode_can_be_set() {
        let builder = Clapfig::builder::<TestConfig>()
            .app_name("myapp")
            .search_mode(SearchMode::FirstMatch);
        assert_eq!(builder.search_mode, SearchMode::FirstMatch);
    }

    #[test]
    fn persist_scopes_default_empty() {
        let builder = Clapfig::builder::<TestConfig>().app_name("myapp");
        assert!(builder.persist_scopes.is_empty());
    }

    #[test]
    fn persist_scope_can_be_added() {
        let builder = Clapfig::builder::<TestConfig>()
            .app_name("myapp")
            .persist_scope("local", SearchPath::Cwd);
        assert_eq!(builder.persist_scopes.len(), 1);
        assert_eq!(builder.persist_scopes[0].0, "local");
        assert_eq!(builder.persist_scopes[0].1, SearchPath::Cwd);
    }

    #[test]
    fn persist_scope_auto_adds_to_search_paths() {
        let builder = Clapfig::builder::<TestConfig>()
            .app_name("myapp")
            .persist_scope("local", SearchPath::Cwd);
        let paths = builder.effective_search_paths();
        // Platform (default) + Cwd (auto-added from scope)
        assert_eq!(paths, vec![SearchPath::Platform, SearchPath::Cwd]);
    }

    #[test]
    fn persist_scope_deduplicates_search_paths() {
        let builder = Clapfig::builder::<TestConfig>()
            .app_name("myapp")
            .search_paths(vec![SearchPath::Platform, SearchPath::Cwd])
            .persist_scope("local", SearchPath::Cwd);
        let paths = builder.effective_search_paths();
        // Cwd already present, should not be duplicated
        assert_eq!(paths, vec![SearchPath::Platform, SearchPath::Cwd]);
    }

    #[test]
    fn cli_override_some_added() {
        let builder = Clapfig::builder::<TestConfig>()
            .app_name("myapp")
            .cli_override("port", Some(3000i64));
        assert_eq!(builder.cli_overrides.len(), 1);
        assert_eq!(builder.cli_overrides[0].0, "port");
    }

    #[test]
    fn cli_override_none_skipped() {
        let builder = Clapfig::builder::<TestConfig>()
            .app_name("myapp")
            .cli_override::<i64>("port", None);
        assert!(builder.cli_overrides.is_empty());
    }

    #[test]
    fn missing_app_name_errors() {
        let builder = Clapfig::builder::<TestConfig>();
        let result = builder.load();
        assert!(matches!(result, Err(ClapfigError::AppNameRequired)));
    }

    // --- Load tests ---

    #[test]
    fn load_with_file() {
        let dir = TempDir::new().unwrap();
        fs::write(dir.path().join("test.toml"), "port = 3000\n").unwrap();

        let config: TestConfig = Clapfig::builder()
            .app_name("test")
            .file_name("test.toml")
            .search_paths(vec![SearchPath::Path(dir.path().to_path_buf())])
            .no_env()
            .load()
            .unwrap();

        assert_eq!(config.port, 3000);
        assert_eq!(config.host, "localhost"); // default preserved
    }

    #[test]
    fn load_with_cli_override() {
        let dir = TempDir::new().unwrap();
        fs::write(dir.path().join("test.toml"), "port = 3000\n").unwrap();

        let config: TestConfig = Clapfig::builder()
            .app_name("test")
            .file_name("test.toml")
            .search_paths(vec![SearchPath::Path(dir.path().to_path_buf())])
            .no_env()
            .cli_override("port", Some(9999i64))
            .load()
            .unwrap();

        assert_eq!(config.port, 9999);
    }

    #[test]
    fn load_defaults_only() {
        let dir = TempDir::new().unwrap();
        // No config file — just defaults
        let config: TestConfig = Clapfig::builder()
            .app_name("test")
            .search_paths(vec![SearchPath::Path(dir.path().to_path_buf())])
            .no_env()
            .load()
            .unwrap();

        assert_eq!(config.host, "localhost");
        assert_eq!(config.port, 8080);
        assert!(!config.debug);
    }

    // --- post_validate hook ---

    #[test]
    fn post_validate_sees_merged_values() {
        let dir = TempDir::new().unwrap();
        fs::write(dir.path().join("test.toml"), "port = 3000\n").unwrap();

        let seen_port = std::sync::Arc::new(std::sync::Mutex::new(0u16));
        let seen_port_clone = seen_port.clone();

        let _config: TestConfig = Clapfig::builder()
            .app_name("test")
            .file_name("test.toml")
            .search_paths(vec![SearchPath::Path(dir.path().to_path_buf())])
            .no_env()
            .post_validate(move |c: &TestConfig| {
                *seen_port_clone.lock().unwrap() = c.port;
                Ok(())
            })
            .load()
            .unwrap();

        assert_eq!(
            *seen_port.lock().unwrap(),
            3000,
            "hook must see post-merge values"
        );
    }

    #[test]
    fn post_validate_ok_passes_config_through() {
        let dir = TempDir::new().unwrap();

        let config: TestConfig = Clapfig::builder()
            .app_name("test")
            .search_paths(vec![SearchPath::Path(dir.path().to_path_buf())])
            .no_env()
            .post_validate(|_: &TestConfig| Ok(()))
            .load()
            .unwrap();

        assert_eq!(config.port, 8080);
    }

    #[test]
    fn post_validate_err_returns_post_validation_failed() {
        let dir = TempDir::new().unwrap();

        let result: Result<TestConfig, _> = Clapfig::builder()
            .app_name("test")
            .search_paths(vec![SearchPath::Path(dir.path().to_path_buf())])
            .no_env()
            .post_validate(|c: &TestConfig| {
                if c.port < 10_000 {
                    Err(format!("port {} is below 10000", c.port))
                } else {
                    Ok(())
                }
            })
            .load();

        match result {
            Err(ClapfigError::PostValidationFailed(msg)) => {
                assert!(msg.contains("8080"), "expected port in message: {msg}");
                assert!(msg.contains("below"), "expected reason in message: {msg}");
            }
            Err(other) => panic!("expected PostValidationFailed, got {other:?}"),
            Ok(_) => panic!("expected PostValidationFailed, got Ok"),
        }
    }

    #[test]
    fn post_validate_not_called_when_upstream_fails() {
        let dir = TempDir::new().unwrap();
        fs::write(dir.path().join("test.toml"), "typo_key = 1\n").unwrap();

        let called = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
        let called_clone = called.clone();

        let result: Result<TestConfig, _> = Clapfig::builder()
            .app_name("test")
            .file_name("test.toml")
            .search_paths(vec![SearchPath::Path(dir.path().to_path_buf())])
            .no_env()
            .strict(true)
            .post_validate(move |_: &TestConfig| {
                called_clone.store(true, std::sync::atomic::Ordering::SeqCst);
                Ok(())
            })
            .load();

        assert!(result.is_err(), "strict validation should have failed");
        assert!(
            !called.load(std::sync::atomic::Ordering::SeqCst),
            "hook must not run when upstream resolution fails"
        );
    }

    #[test]
    fn post_validate_second_call_replaces_first() {
        let dir = TempDir::new().unwrap();

        let result: Result<TestConfig, _> = Clapfig::builder()
            .app_name("test")
            .search_paths(vec![SearchPath::Path(dir.path().to_path_buf())])
            .no_env()
            .post_validate(|_: &TestConfig| Err("first".into()))
            .post_validate(|_: &TestConfig| Err("second".into()))
            .load();

        match result {
            Err(ClapfigError::PostValidationFailed(msg)) => assert_eq!(msg, "second"),
            other => panic!("expected PostValidationFailed('second'), got {other:?}"),
        }
    }

    #[test]
    fn strict_rejects_unknown_key() {
        let dir = TempDir::new().unwrap();
        fs::write(dir.path().join("test.toml"), "typo = 1\n").unwrap();

        let result: Result<TestConfig, _> = Clapfig::builder()
            .app_name("test")
            .file_name("test.toml")
            .search_paths(vec![SearchPath::Path(dir.path().to_path_buf())])
            .no_env()
            .strict(true)
            .load();

        assert!(result.is_err());
    }

    #[test]
    fn lenient_allows_unknown_key() {
        let dir = TempDir::new().unwrap();
        fs::write(dir.path().join("test.toml"), "typo = 1\nport = 3000\n").unwrap();

        let config: TestConfig = Clapfig::builder()
            .app_name("test")
            .file_name("test.toml")
            .search_paths(vec![SearchPath::Path(dir.path().to_path_buf())])
            .no_env()
            .strict(false)
            .load()
            .unwrap();

        assert_eq!(config.port, 3000);
    }

    // --- SearchMode tests ---

    #[test]
    fn first_match_uses_highest_priority_file_only() {
        let dir1 = TempDir::new().unwrap();
        let dir2 = TempDir::new().unwrap();
        fs::write(
            dir1.path().join("test.toml"),
            "port = 1000\nhost = \"low\"\n",
        )
        .unwrap();
        fs::write(dir2.path().join("test.toml"), "port = 2000\n").unwrap();

        let config: TestConfig = Clapfig::builder()
            .app_name("test")
            .file_name("test.toml")
            .search_paths(vec![
                SearchPath::Path(dir1.path().to_path_buf()),
                SearchPath::Path(dir2.path().to_path_buf()), // highest priority
            ])
            .search_mode(SearchMode::FirstMatch)
            .no_env()
            .load()
            .unwrap();

        // Should use dir2 only — port from dir2, host from defaults (not dir1!)
        assert_eq!(config.port, 2000);
        assert_eq!(config.host, "localhost"); // default, NOT "low" from dir1
    }

    #[test]
    fn merge_mode_combines_both_files() {
        let dir1 = TempDir::new().unwrap();
        let dir2 = TempDir::new().unwrap();
        fs::write(
            dir1.path().join("test.toml"),
            "port = 1000\nhost = \"base\"\n",
        )
        .unwrap();
        fs::write(dir2.path().join("test.toml"), "port = 2000\n").unwrap();

        let config: TestConfig = Clapfig::builder()
            .app_name("test")
            .file_name("test.toml")
            .search_paths(vec![
                SearchPath::Path(dir1.path().to_path_buf()),
                SearchPath::Path(dir2.path().to_path_buf()),
            ])
            .search_mode(SearchMode::Merge)
            .no_env()
            .load()
            .unwrap();

        // Merge: port from dir2 (higher priority), host from dir1 (lower priority)
        assert_eq!(config.port, 2000);
        assert_eq!(config.host, "base");
    }

    #[test]
    fn first_match_falls_back_when_high_priority_missing() {
        let dir1 = TempDir::new().unwrap();
        let dir2 = TempDir::new().unwrap();
        // Only dir1 (lower priority) has a config
        fs::write(dir1.path().join("test.toml"), "port = 1000\n").unwrap();

        let config: TestConfig = Clapfig::builder()
            .app_name("test")
            .file_name("test.toml")
            .search_paths(vec![
                SearchPath::Path(dir1.path().to_path_buf()),
                SearchPath::Path(dir2.path().to_path_buf()),
            ])
            .search_mode(SearchMode::FirstMatch)
            .no_env()
            .load()
            .unwrap();

        assert_eq!(config.port, 1000);
    }

    // --- handle tests ---

    #[test]
    fn handle_gen() {
        let result: ConfigResult = Clapfig::builder::<TestConfig>()
            .app_name("test")
            .no_env()
            .handle(&ConfigAction::Gen { output: None })
            .unwrap();

        match result {
            ConfigResult::Template(t) => {
                assert!(t.contains("host"));
                assert!(t.contains("port"));
            }
            other => panic!("Expected Template, got {other:?}"),
        }
    }

    #[test]
    fn handle_gen_with_output() {
        let dir = TempDir::new().unwrap();
        let out_path = dir.path().join("generated.toml");

        let result: ConfigResult = Clapfig::builder::<TestConfig>()
            .app_name("test")
            .no_env()
            .handle(&ConfigAction::Gen {
                output: Some(out_path.clone()),
            })
            .unwrap();

        assert!(matches!(result, ConfigResult::TemplateWritten { .. }));
        let content = fs::read_to_string(&out_path).unwrap();
        assert!(content.contains("host"));
        assert!(content.contains("port"));
    }

    #[test]
    fn handle_schema() {
        let result: ConfigResult = Clapfig::builder::<TestConfig>()
            .app_name("test")
            .no_env()
            .handle(&ConfigAction::Schema { output: None })
            .unwrap();

        match result {
            ConfigResult::Schema(s) => {
                let value: serde_json::Value = serde_json::from_str(&s).unwrap();
                assert_eq!(value["type"], "object");
                assert_eq!(value["title"], "TestConfig");
                assert!(value["properties"].get("host").is_some());
                assert!(value["properties"].get("database").is_some());
            }
            other => panic!("Expected Schema, got {other:?}"),
        }
    }

    #[test]
    fn handle_schema_with_output() {
        let dir = TempDir::new().unwrap();
        let out_path = dir.path().join("schema.json");

        let result: ConfigResult = Clapfig::builder::<TestConfig>()
            .app_name("test")
            .no_env()
            .handle(&ConfigAction::Schema {
                output: Some(out_path.clone()),
            })
            .unwrap();

        assert!(matches!(result, ConfigResult::SchemaWritten { .. }));
        let content = fs::read_to_string(&out_path).unwrap();
        let value: serde_json::Value = serde_json::from_str(&content).unwrap();
        assert_eq!(value["title"], "TestConfig");
    }

    #[test]
    fn handle_get_merged() {
        let dir = TempDir::new().unwrap();
        fs::write(dir.path().join("test.toml"), "port = 3000\n").unwrap();

        let result = Clapfig::builder::<TestConfig>()
            .app_name("test")
            .file_name("test.toml")
            .search_paths(vec![SearchPath::Path(dir.path().to_path_buf())])
            .no_env()
            .handle(&ConfigAction::Get {
                key: "port".into(),
                scope: None,
            })
            .unwrap();

        match result {
            ConfigResult::KeyValue { value, .. } => assert_eq!(value, "3000"),
            other => panic!("Expected KeyValue, got {other:?}"),
        }
    }

    #[test]
    fn handle_set_requires_persist_scope() {
        let dir = TempDir::new().unwrap();

        let result = Clapfig::builder::<TestConfig>()
            .app_name("test")
            .file_name("test.toml")
            .search_paths(vec![SearchPath::Path(dir.path().to_path_buf())])
            .no_env()
            .handle(&ConfigAction::Set {
                key: "port".into(),
                value: "3000".into(),
                scope: None,
            });

        assert!(matches!(result, Err(ClapfigError::NoPersistPath)));
    }

    #[test]
    fn handle_set_default_scope() {
        let dir = TempDir::new().unwrap();

        let result = Clapfig::builder::<TestConfig>()
            .app_name("test")
            .file_name("test.toml")
            .search_paths(vec![SearchPath::Path(dir.path().to_path_buf())])
            .persist_scope("local", SearchPath::Path(dir.path().to_path_buf()))
            .no_env()
            .handle(&ConfigAction::Set {
                key: "port".into(),
                value: "3000".into(),
                scope: None,
            })
            .unwrap();

        assert!(matches!(result, ConfigResult::ValueSet { .. }));
        let content = fs::read_to_string(dir.path().join("test.toml")).unwrap();
        assert!(content.contains("port = 3000"));
    }

    #[test]
    fn handle_set_named_scope() {
        let local_dir = TempDir::new().unwrap();
        let global_dir = TempDir::new().unwrap();

        let result = Clapfig::builder::<TestConfig>()
            .app_name("test")
            .file_name("test.toml")
            .persist_scope("local", SearchPath::Path(local_dir.path().to_path_buf()))
            .persist_scope("global", SearchPath::Path(global_dir.path().to_path_buf()))
            .no_env()
            .handle(&ConfigAction::Set {
                key: "port".into(),
                value: "9999".into(),
                scope: Some("global".into()),
            })
            .unwrap();

        assert!(matches!(result, ConfigResult::ValueSet { .. }));
        // Written to global dir, not local
        let content = fs::read_to_string(global_dir.path().join("test.toml")).unwrap();
        assert!(content.contains("port = 9999"));
        assert!(!local_dir.path().join("test.toml").exists());
    }

    #[test]
    fn handle_unset_requires_persist_scope() {
        let dir = TempDir::new().unwrap();

        let result = Clapfig::builder::<TestConfig>()
            .app_name("test")
            .file_name("test.toml")
            .search_paths(vec![SearchPath::Path(dir.path().to_path_buf())])
            .no_env()
            .handle(&ConfigAction::Unset {
                key: "port".into(),
                scope: None,
            });

        assert!(matches!(result, Err(ClapfigError::NoPersistPath)));
    }

    #[test]
    fn handle_unset_removes_key() {
        let dir = TempDir::new().unwrap();
        fs::write(
            dir.path().join("test.toml"),
            "port = 3000\nhost = \"localhost\"\n",
        )
        .unwrap();

        let result = Clapfig::builder::<TestConfig>()
            .app_name("test")
            .file_name("test.toml")
            .search_paths(vec![SearchPath::Path(dir.path().to_path_buf())])
            .persist_scope("local", SearchPath::Path(dir.path().to_path_buf()))
            .no_env()
            .handle(&ConfigAction::Unset {
                key: "port".into(),
                scope: None,
            })
            .unwrap();

        assert!(matches!(result, ConfigResult::ValueUnset { .. }));
        let content = fs::read_to_string(dir.path().join("test.toml")).unwrap();
        assert!(!content.contains("port"));
        assert!(content.contains("host = \"localhost\""));
    }

    #[test]
    fn handle_set_rejects_ancestors_scope() {
        let result = Clapfig::builder::<TestConfig>()
            .app_name("test")
            .persist_scope("bad", SearchPath::Ancestors(Boundary::Root))
            .no_env()
            .handle(&ConfigAction::Set {
                key: "port".into(),
                value: "3000".into(),
                scope: None,
            });

        assert!(matches!(
            result,
            Err(ClapfigError::AncestorsNotAllowedAsPersistPath)
        ));
    }

    #[test]
    fn handle_unknown_scope_errors() {
        let dir = TempDir::new().unwrap();

        let result = Clapfig::builder::<TestConfig>()
            .app_name("test")
            .file_name("test.toml")
            .persist_scope("local", SearchPath::Path(dir.path().to_path_buf()))
            .no_env()
            .handle(&ConfigAction::Set {
                key: "port".into(),
                value: "3000".into(),
                scope: Some("nonexistent".into()),
            });

        match result {
            Err(ClapfigError::UnknownScope { scope, available }) => {
                assert_eq!(scope, "nonexistent");
                assert_eq!(available, vec!["local"]);
            }
            other => panic!("Expected UnknownScope, got {other:?}"),
        }
    }

    #[test]
    fn handle_list_with_scope() {
        let dir = TempDir::new().unwrap();
        fs::write(dir.path().join("test.toml"), "port = 3000\n").unwrap();

        let result = Clapfig::builder::<TestConfig>()
            .app_name("test")
            .file_name("test.toml")
            .persist_scope("local", SearchPath::Path(dir.path().to_path_buf()))
            .no_env()
            .handle(&ConfigAction::List {
                scope: Some("local".into()),
            })
            .unwrap();

        match result {
            ConfigResult::Listing { entries } => {
                assert_eq!(entries.len(), 1);
                assert_eq!(entries[0], ("port".into(), "3000".into()));
            }
            other => panic!("Expected Listing, got {other:?}"),
        }
    }

    #[test]
    fn handle_get_with_scope() {
        let dir = TempDir::new().unwrap();
        fs::write(dir.path().join("test.toml"), "port = 3000\n").unwrap();

        let result = Clapfig::builder::<TestConfig>()
            .app_name("test")
            .file_name("test.toml")
            .persist_scope("local", SearchPath::Path(dir.path().to_path_buf()))
            .no_env()
            .handle(&ConfigAction::Get {
                key: "port".into(),
                scope: Some("local".into()),
            })
            .unwrap();

        match result {
            ConfigResult::KeyValue { value, .. } => assert_eq!(value, "3000"),
            other => panic!("Expected KeyValue, got {other:?}"),
        }
    }

    #[test]
    fn multiple_scopes_separate_files() {
        let local_dir = TempDir::new().unwrap();
        let global_dir = TempDir::new().unwrap();

        let make_builder = || {
            Clapfig::builder::<TestConfig>()
                .app_name("test")
                .file_name("test.toml")
                .persist_scope("local", SearchPath::Path(local_dir.path().to_path_buf()))
                .persist_scope("global", SearchPath::Path(global_dir.path().to_path_buf()))
                .no_env()
        };

        // Set in local
        make_builder()
            .handle(&ConfigAction::Set {
                key: "port".into(),
                value: "3000".into(),
                scope: None, // defaults to "local"
            })
            .unwrap();

        // Set in global
        make_builder()
            .handle(&ConfigAction::Set {
                key: "host".into(),
                value: "0.0.0.0".into(),
                scope: Some("global".into()),
            })
            .unwrap();

        // Verify separate files
        let local_content = fs::read_to_string(local_dir.path().join("test.toml")).unwrap();
        assert!(local_content.contains("port = 3000"));
        // host should NOT be set (template may have commented-out host)
        assert!(!local_content.contains("host = \"0.0.0.0\""));

        let global_content = fs::read_to_string(global_dir.path().join("test.toml")).unwrap();
        assert!(global_content.contains("host = \"0.0.0.0\""));
        // port should NOT be set in global
        assert!(!global_content.contains("port = 3000"));

        // List scoped: only that file's entries
        let local_list = make_builder()
            .handle(&ConfigAction::List {
                scope: Some("local".into()),
            })
            .unwrap();
        match local_list {
            ConfigResult::Listing { entries } => {
                assert_eq!(entries.len(), 1);
                assert_eq!(entries[0].0, "port");
            }
            other => panic!("Expected Listing, got {other:?}"),
        }

        // List merged (no scope): sees both files merged + defaults
        let merged_list = make_builder()
            .handle(&ConfigAction::List { scope: None })
            .unwrap();
        match merged_list {
            ConfigResult::Listing { entries } => {
                let keys: Vec<&str> = entries.iter().map(|(k, _)| k.as_str()).collect();
                assert!(keys.contains(&"port"));
                assert!(keys.contains(&"host"));
            }
            other => panic!("Expected Listing, got {other:?}"),
        }
    }

    // --- cli_overrides_from tests ---

    #[test]
    fn overrides_from_matches_known_keys() {
        #[derive(Serialize)]
        struct Args {
            host: Option<String>,
            port: Option<u16>,
        }
        let args = Args {
            host: Some("1.2.3.4".into()),
            port: Some(9999),
        };
        let builder = Clapfig::builder::<TestConfig>()
            .app_name("test")
            .cli_overrides_from(&args);
        assert_eq!(builder.cli_overrides.len(), 2);
    }

    #[test]
    fn overrides_from_skips_none() {
        #[derive(Serialize)]
        struct Args {
            host: Option<String>,
            port: Option<u16>,
        }
        let args = Args {
            host: None,
            port: Some(9999),
        };
        let builder = Clapfig::builder::<TestConfig>()
            .app_name("test")
            .cli_overrides_from(&args);
        assert_eq!(builder.cli_overrides.len(), 1);
        assert_eq!(builder.cli_overrides[0].0, "port");
    }

    #[test]
    fn overrides_from_ignores_unknown_keys() {
        #[derive(Serialize)]
        struct Args {
            host: Option<String>,
            verbose: bool,
            output: Option<String>,
        }
        let args = Args {
            host: Some("x".into()),
            verbose: true,
            output: Some("f".into()),
        };
        let builder = Clapfig::builder::<TestConfig>()
            .app_name("test")
            .cli_overrides_from(&args);
        assert_eq!(builder.cli_overrides.len(), 1);
        assert_eq!(builder.cli_overrides[0].0, "host");
    }

    #[test]
    fn overrides_from_composes_with_cli_override() {
        #[derive(Serialize)]
        struct Args {
            host: Option<String>,
        }
        let args = Args {
            host: Some("from_struct".into()),
        };
        let builder = Clapfig::builder::<TestConfig>()
            .app_name("test")
            .cli_override("port", Some(1234i64))
            .cli_overrides_from(&args);
        assert_eq!(builder.cli_overrides.len(), 2);
        assert_eq!(builder.cli_overrides[0].0, "port");
        assert_eq!(builder.cli_overrides[1].0, "host");
    }

    #[test]
    fn overrides_from_hashmap() {
        use std::collections::HashMap;
        let mut map = HashMap::new();
        map.insert("port".to_string(), 3000i64);
        let builder = Clapfig::builder::<TestConfig>()
            .app_name("test")
            .cli_overrides_from(&map);
        assert_eq!(builder.cli_overrides.len(), 1);
        assert_eq!(builder.cli_overrides[0].0, "port");
    }

    #[test]
    fn overrides_from_all_none() {
        #[derive(Serialize)]
        struct Args {
            host: Option<String>,
            port: Option<u16>,
        }
        let args = Args {
            host: None,
            port: None,
        };
        let builder = Clapfig::builder::<TestConfig>()
            .app_name("test")
            .cli_overrides_from(&args);
        assert!(builder.cli_overrides.is_empty());
    }

    #[test]
    fn overrides_from_end_to_end() {
        let dir = TempDir::new().unwrap();
        fs::write(dir.path().join("test.toml"), "port = 3000\n").unwrap();

        #[derive(Serialize)]
        struct Args {
            host: Option<String>,
            port: Option<i64>,
            verbose: bool,
        }
        let args = Args {
            host: Some("1.2.3.4".into()),
            port: None,
            verbose: true,
        };

        let config: TestConfig = Clapfig::builder()
            .app_name("test")
            .file_name("test.toml")
            .search_paths(vec![SearchPath::Path(dir.path().to_path_buf())])
            .no_env()
            .cli_overrides_from(&args)
            .load()
            .unwrap();

        assert_eq!(config.host, "1.2.3.4"); // from cli
        assert_eq!(config.port, 3000); // from file (cli was None)
        assert!(!config.debug); // default (verbose not in config)
    }

    #[test]
    fn handle_list() {
        let dir = TempDir::new().unwrap();
        fs::write(dir.path().join("test.toml"), "port = 3000\n").unwrap();

        let result = Clapfig::builder::<TestConfig>()
            .app_name("test")
            .file_name("test.toml")
            .search_paths(vec![SearchPath::Path(dir.path().to_path_buf())])
            .no_env()
            .handle(&ConfigAction::List { scope: None })
            .unwrap();

        match result {
            ConfigResult::Listing { entries } => {
                let port = entries.iter().find(|(k, _)| k == "port").unwrap();
                assert_eq!(port.1, "3000");
                let host = entries.iter().find(|(k, _)| k == "host").unwrap();
                assert_eq!(host.1, "localhost"); // default
            }
            other => panic!("Expected Listing, got {other:?}"),
        }
    }

    #[test]
    fn handle_set_rejects_invalid_enum_value() {
        let dir = TempDir::new().unwrap();

        let result = Clapfig::builder::<EnumConfig>()
            .app_name("test")
            .file_name("test.toml")
            .persist_scope("local", SearchPath::Path(dir.path().to_path_buf()))
            .no_env()
            .handle(&ConfigAction::Set {
                key: "mode".into(),
                value: "garbage".into(),
                scope: None,
            });

        assert!(matches!(result, Err(ClapfigError::InvalidValue { .. })));
        // File should NOT have been written
        assert!(!dir.path().join("test.toml").exists());
    }

    #[test]
    fn handle_set_accepts_valid_enum_value() {
        let dir = TempDir::new().unwrap();

        let result = Clapfig::builder::<EnumConfig>()
            .app_name("test")
            .file_name("test.toml")
            .persist_scope("local", SearchPath::Path(dir.path().to_path_buf()))
            .no_env()
            .handle(&ConfigAction::Set {
                key: "mode".into(),
                value: "slow".into(),
                scope: None,
            });

        assert!(matches!(result, Ok(ConfigResult::ValueSet { .. })));
        let content = fs::read_to_string(dir.path().join("test.toml")).unwrap();
        assert!(content.contains("mode = \"slow\""));
    }

    #[test]
    fn handle_set_rejects_unknown_key() {
        let dir = TempDir::new().unwrap();

        let result = Clapfig::builder::<TestConfig>()
            .app_name("test")
            .file_name("test.toml")
            .persist_scope("local", SearchPath::Path(dir.path().to_path_buf()))
            .no_env()
            .handle(&ConfigAction::Set {
                key: "nonexistent".into(),
                value: "whatever".into(),
                scope: None,
            });

        assert!(matches!(result, Err(ClapfigError::KeyNotFound(_))));
    }

    #[test]
    fn handle_list_defaults_only() {
        let dir = TempDir::new().unwrap();

        let result = Clapfig::builder::<TestConfig>()
            .app_name("test")
            .search_paths(vec![SearchPath::Path(dir.path().to_path_buf())])
            .no_env()
            .handle(&ConfigAction::List { scope: None })
            .unwrap();

        match result {
            ConfigResult::Listing { entries } => {
                assert_eq!(entries.len(), 5);
                let db_url = entries.iter().find(|(k, _)| k == "database.url").unwrap();
                assert_eq!(db_url.1, "<not set>");
            }
            other => panic!("Expected Listing, got {other:?}"),
        }
    }

    #[test]
    fn layer_order_defaults_to_none() {
        let builder = Clapfig::builder::<TestConfig>().app_name("myapp");
        assert_eq!(builder.layer_order, None);
    }

    #[test]
    fn layer_order_can_be_set() {
        let builder = Clapfig::builder::<TestConfig>()
            .app_name("myapp")
            .layer_order(vec![Layer::Env, Layer::Files, Layer::Cli]);
        assert_eq!(
            builder.layer_order,
            Some(vec![Layer::Env, Layer::Files, Layer::Cli])
        );
    }

    #[test]
    fn layer_order_cli_below_files() {
        let dir = TempDir::new().unwrap();
        fs::write(dir.path().join("test.toml"), "port = 3000\n").unwrap();

        // Custom order: Cli < Files (files win over cli)
        let config: TestConfig = Clapfig::builder()
            .app_name("test")
            .file_name("test.toml")
            .search_paths(vec![SearchPath::Path(dir.path().to_path_buf())])
            .no_env()
            .cli_override("port", Some(9999))
            .layer_order(vec![Layer::Cli, Layer::Files])
            .load()
            .unwrap();

        // Files comes after Cli in the order, so Files wins
        assert_eq!(config.port, 3000);
    }

    #[test]
    fn layer_order_default_cli_wins() {
        let dir = TempDir::new().unwrap();
        fs::write(dir.path().join("test.toml"), "port = 3000\n").unwrap();

        // Default order: Files < Cli, so cli should win
        let config: TestConfig = Clapfig::builder()
            .app_name("test")
            .file_name("test.toml")
            .search_paths(vec![SearchPath::Path(dir.path().to_path_buf())])
            .no_env()
            .cli_override("port", Some(9999))
            .load()
            .unwrap();

        assert_eq!(config.port, 9999);
    }
}