teamy-figue 2.0.2

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

use std::string::{String, ToString};
use std::vec::Vec;

use facet_reflect::Span;
use indexmap::IndexMap;

use crate::config_value::{ConfigValue, ConfigValueVisitorMut};
use crate::driver::LayerOutput;
use crate::path::Path;
use crate::provenance::Provenance;
use crate::schema::{ConfigStructSchema, ConfigValueSchema, Schema};
use crate::value_builder::{LeafValue, ValueBuilder};

// ============================================================================
// EnvSource trait
// ============================================================================

/// Trait for abstracting over environment variable sources.
///
/// This allows testing without modifying the actual environment.
pub trait EnvSource {
    /// Get the value of an environment variable by name.
    fn get(&self, name: &str) -> Option<String>;

    /// Iterate over all environment variables.
    fn vars(&self) -> Box<dyn Iterator<Item = (String, String)> + '_>;
}

/// Environment source that reads from the actual process environment.
#[derive(Debug, Clone, Copy, Default)]
pub struct StdEnv;

impl EnvSource for StdEnv {
    fn get(&self, name: &str) -> Option<String> {
        std::env::var(name).ok()
    }

    fn vars(&self) -> Box<dyn Iterator<Item = (String, String)> + '_> {
        Box::new(std::env::vars())
    }
}

/// Environment source backed by a map (for testing).
#[derive(Debug, Clone, Default)]
pub struct MockEnv {
    vars: IndexMap<String, String, std::hash::RandomState>,
}

impl MockEnv {
    /// Create a new empty mock environment.
    pub fn new() -> Self {
        Self::default()
    }

    /// Create a mock environment from an iterator of key-value pairs.
    pub fn from_pairs<I, K, V>(iter: I) -> Self
    where
        I: IntoIterator<Item = (K, V)>,
        K: Into<String>,
        V: Into<String>,
    {
        Self {
            vars: iter
                .into_iter()
                .map(|(k, v)| (k.into(), v.into()))
                .collect(),
        }
    }

    /// Set an environment variable.
    pub fn set(&mut self, name: impl Into<String>, value: impl Into<String>) {
        self.vars.insert(name.into(), value.into());
    }
}

impl EnvSource for MockEnv {
    fn get(&self, name: &str) -> Option<String> {
        self.vars.get(name).cloned()
    }

    fn vars(&self) -> Box<dyn Iterator<Item = (String, String)> + '_> {
        Box::new(self.vars.iter().map(|(k, v)| (k.clone(), v.clone())))
    }
}

// ============================================================================
// EnvConfig
// ============================================================================

/// Configuration for environment variable parsing.
pub struct EnvConfig {
    /// The prefix to look for (e.g., `MYAPP`). For example, configuration variable
    /// foo.bar will be overrideable via `MYAPP__FOO__BAR`.
    pub prefix: String,

    /// Whether to error out if any env vars that start with `MYAPP__` should be reported
    /// as errors and stop the program entirely (to try and catch typos)
    pub strict: bool,

    /// Custom environment source (for testing). If None, uses StdEnv.
    pub source: Option<Box<dyn EnvSource>>,
}

impl EnvConfig {
    /// Create a new EnvConfig with the given prefix.
    pub fn new(prefix: impl Into<String>) -> Self {
        Self {
            prefix: prefix.into(),
            strict: false,
            source: None,
        }
    }

    /// Enable strict mode.
    pub fn strict(mut self) -> Self {
        self.strict = true;
        self
    }

    /// Get the env source, or StdEnv if none set.
    pub fn source(&self) -> &dyn EnvSource {
        self.source.as_ref().map(|s| s.as_ref()).unwrap_or(&StdEnv)
    }
}

/// Builder for environment variable configuration.
#[derive(Default)]
pub struct EnvConfigBuilder {
    prefix: String,
    strict: bool,
    source: Option<Box<dyn EnvSource>>,
}

impl EnvConfigBuilder {
    /// Create a new env config builder.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the environment variable prefix.
    pub fn prefix(mut self, prefix: impl Into<String>) -> Self {
        self.prefix = prefix.into();
        self
    }

    /// Enable strict mode - error on unknown env vars with the prefix.
    pub fn strict(mut self) -> Self {
        self.strict = true;
        self
    }

    /// Use a custom environment source (for testing).
    pub fn source(mut self, source: impl EnvSource + 'static) -> Self {
        self.source = Some(Box::new(source));
        self
    }

    /// Build the env configuration.
    pub fn build(self) -> EnvConfig {
        let mut config = EnvConfig::new(self.prefix);
        if self.strict {
            config = config.strict();
        }
        config.source = self.source;
        config
    }
}

/// Parse environment variables using the schema, returning a LayerOutput.
///
/// This reads env vars with the configured prefix and builds a ConfigValue tree
/// under the schema's config field.
pub fn parse_env(schema: &Schema, env_config: &EnvConfig, source: &dyn EnvSource) -> LayerOutput {
    // Get the config schema - if there's no config field, we can't parse env vars
    let Some(config_schema) = schema.config() else {
        return parse_env_no_config(env_config, source);
    };

    // Use explicit prefix from config, or fall back to schema's env_prefix
    let prefix = if env_config.prefix.is_empty() {
        config_schema.env_prefix().unwrap_or("")
    } else {
        &env_config.prefix
    };

    let prefix_with_sep = format!("{}__", prefix);

    // Create a ValueBuilder
    let mut builder = ValueBuilder::new(config_schema);

    // Track which paths were set by prefixed vars (so aliases don't override them)
    let mut prefixed_paths: Vec<Vec<String>> = Vec::new();

    // First pass: collect all prefixed env vars (higher priority)
    for (name, value) in source.vars() {
        // Check if this var matches our prefix
        if !name.starts_with(&prefix_with_sep) {
            continue;
        }

        // Extract the path after the prefix
        let rest = &name[prefix_with_sep.len()..];
        if rest.is_empty() {
            builder.warn(format!(
                "invalid environment variable name: {} (empty after prefix)",
                name
            ));
            continue;
        }

        // Parse the path segments
        let segments: Vec<&str> = rest.split("__").collect();

        // Check for empty segments
        if segments.iter().any(|s| s.is_empty()) {
            builder.warn(format!(
                "invalid environment variable name: {} (contains empty segment)",
                name
            ));
            continue;
        }

        // Convert to lowercase for field matching
        let path: Vec<String> = segments.iter().map(|s| s.to_lowercase()).collect();

        // Create provenance for this env var
        let prov = Provenance::env(&name, &value);

        // Validate enum values if the target is an enum
        validate_enum_value_if_applicable(&mut builder, config_schema, &path, &value, &name);

        // Parse the value (handle comma-separated lists)
        let leaf_value = parse_env_value(&value);

        // Set the value with its provenance
        // Unknown keys are tracked in unused_keys by the builder.
        // In strict mode, they'll be reported by the driver alongside the config dump.
        if builder.set(&path, leaf_value, None, prov) {
            prefixed_paths.push(path);
        }
    }

    // Second pass: check env aliases (lower priority than prefixed vars)
    check_env_aliases(&mut builder, config_schema, source, &[], &prefixed_paths);

    let mut output = builder.into_output(config_schema.field_name());

    // Assign spans to env-sourced values and build the virtual source document
    if let Some(ref mut value) = output.value {
        let source_text = assign_env_spans(value);
        if !source_text.is_empty() {
            output.source_text = Some(source_text);
        }
    }

    output
}

/// Recursively check env aliases for all fields in a config struct.
fn check_env_aliases(
    builder: &mut ValueBuilder,
    schema: &ConfigStructSchema,
    source: &dyn EnvSource,
    parent_path: &[String],
    prefixed_paths: &[Vec<String>],
) {
    for (field_name, field_schema) in schema.fields() {
        let mut field_path = parent_path.to_vec();
        field_path.push(field_name.clone());

        // Check if this field has aliases and wasn't already set by a prefixed var
        let already_set = prefixed_paths.contains(&field_path);
        if !already_set {
            for alias in field_schema.env_aliases() {
                if let Some(value) = source.get(alias) {
                    let prov = Provenance::env(alias, &value);
                    let leaf_value = parse_env_value(&value);
                    builder.set(&field_path, leaf_value, None, prov);
                    // Only use the first matching alias
                    break;
                }
            }
        }

        // Recurse into nested structs
        match field_schema.value() {
            ConfigValueSchema::Struct(nested) => {
                check_env_aliases(builder, nested, source, &field_path, prefixed_paths);
            }
            ConfigValueSchema::Option { value, .. } => {
                if let ConfigValueSchema::Struct(nested) = value.as_ref() {
                    check_env_aliases(builder, nested, source, &field_path, prefixed_paths);
                }
            }
            _ => {}
        }
    }
}

/// Handle the case where there's no config field in the schema.
fn parse_env_no_config(env_config: &EnvConfig, source: &dyn EnvSource) -> LayerOutput {
    use crate::config_value::{ConfigValue, Sourced};
    use crate::driver::UnusedKey;

    let prefix = &env_config.prefix;
    let prefix_with_sep = format!("{}__", prefix);

    let mut unused_keys = Vec::new();

    for (name, _value) in source.vars() {
        if name.starts_with(&prefix_with_sep) {
            let rest = &name[prefix_with_sep.len()..];
            if !rest.is_empty() {
                let segments: Vec<&str> = rest.split("__").collect();
                if !segments.iter().any(|s| s.is_empty()) {
                    let path: Vec<String> = segments.iter().map(|s| s.to_lowercase()).collect();
                    unused_keys.push(UnusedKey {
                        key: path,
                        provenance: Provenance::env(&name, ""),
                    });
                }
            }
        }
    }

    LayerOutput {
        value: Some(ConfigValue::Object(Sourced::new(IndexMap::default()))),
        unused_keys,
        diagnostics: Vec::new(),
        source_text: None,
        config_file_path: None,
        help_list_mode: None,
    }
}

/// Parse an env var value, handling comma-separated lists.
fn parse_env_value(value: &str) -> LeafValue {
    if value.contains(',') {
        let elements = parse_comma_separated(value);
        if elements.len() > 1 {
            return LeafValue::StringArray(elements);
        } else if elements.len() == 1 {
            return LeafValue::String(elements.into_iter().next().unwrap());
        }
    }
    LeafValue::String(value.to_string())
}

/// Validate enum value if the target path points to an enum field.
fn validate_enum_value_if_applicable(
    builder: &mut ValueBuilder,
    schema: &ConfigStructSchema,
    path: &[String],
    value: &str,
    var_name: &str,
) {
    if let Some(value_schema) = schema.get_by_path(&path.to_vec()) {
        // Unwrap Option wrapper if present
        let inner_schema = match value_schema {
            ConfigValueSchema::Option { value: inner, .. } => inner.as_ref(),
            other => other,
        };

        // For enum fields, validate the value is a known variant
        if let ConfigValueSchema::Enum(enum_schema) = inner_schema {
            let variants = enum_schema.variants();
            if !variants.contains_key(value) {
                let valid_variants: Vec<&str> = variants.keys().map(|s| s.as_str()).collect();

                // Try to find a similar variant
                let suggestion =
                    crate::suggest::format_suggestion(value, valid_variants.iter().copied());

                builder.warn(format!(
                    "{}: unknown variant '{}' for {}{} Valid variants are: {}",
                    var_name,
                    value,
                    path.join("."),
                    suggestion,
                    valid_variants
                        .iter()
                        .map(|v| format!("'{}'", v))
                        .collect::<Vec<_>>()
                        .join(", ")
                ));
            }
        }
    }
}

/// Parse a comma-separated string, handling escaping.
fn parse_comma_separated(input: &str) -> Vec<String> {
    let mut result = Vec::new();
    let mut current = String::new();
    let mut chars = input.chars().peekable();

    while let Some(ch) = chars.next() {
        if ch == '\\' {
            if let Some(&next) = chars.peek() {
                if next == ',' {
                    chars.next();
                    current.push(',');
                } else {
                    current.push(ch);
                }
            } else {
                current.push(ch);
            }
        } else if ch == ',' {
            let trimmed = current.trim().to_string();
            if !trimmed.is_empty() {
                result.push(trimmed);
            }
            current.clear();
        } else {
            current.push(ch);
        }
    }

    let trimmed = current.trim().to_string();
    if !trimmed.is_empty() {
        result.push(trimmed);
    }

    if result.is_empty() {
        result.push(input.to_string());
    }

    result
}

// ============================================================================
// Virtual env document for span tracking
// ============================================================================

/// Result of assigning env spans to a ConfigValue tree.
/// Assign spans to all env-sourced values in a ConfigValue tree.
///
/// This walks the tree, collects all unique env vars, builds a virtual document
/// like:
/// ```text
/// REEF__PORT="8080"
/// DATABASE_URL="postgres://localhost/db"
/// ```
///
/// And updates each value's span to point to its position in this document.
/// Returns the virtual document for error reporting.
pub fn assign_env_spans(value: &mut ConfigValue) -> String {
    let mut visitor = EnvSpanVisitor::new();
    let mut path = Path::new();
    value.visit_mut(&mut visitor, &mut path);
    visitor.document
}

/// Visitor that assigns spans to env-sourced values.
struct EnvSpanVisitor {
    /// The virtual document being built.
    document: String,
    /// Map from var name to (offset, len) in the document.
    var_spans: IndexMap<String, (usize, usize), std::hash::RandomState>,
}

impl EnvSpanVisitor {
    fn new() -> Self {
        Self {
            document: String::new(),
            var_spans: IndexMap::default(),
        }
    }

    /// Ensure an env var is in the document and return its value span.
    fn ensure_var(&mut self, var: &str, env_value: &str) -> Span {
        if let Some(&(offset, len)) = self.var_spans.get(var) {
            return Span::new(offset, len);
        }

        // Add to document: VAR="value"\n
        // The span points to just the value part (inside quotes)
        self.document.push_str(var);
        self.document.push_str("=\"");
        let value_offset = self.document.len();
        self.document.push_str(env_value);
        let value_len = env_value.len();
        self.document.push_str("\"\n");

        self.var_spans
            .insert(var.to_string(), (value_offset, value_len));

        Span::new(value_offset, value_len)
    }
}

impl ConfigValueVisitorMut for EnvSpanVisitor {
    fn visit_value(&mut self, _path: &Path, value: &mut ConfigValue) {
        if let Some(Provenance::Env {
            var,
            value: env_value,
        }) = value.provenance().cloned()
        {
            *value.span_mut() = Some(self.ensure_var(&var, &env_value));
        }
    }
}

#[cfg(test)]
mod tests {
    use facet::Facet;
    use figue_attrs as args;

    use crate::config_value::ConfigValue;
    use crate::driver::Severity;
    use crate::schema::Schema;

    use super::*;

    // ========================================================================
    // Test schemas
    // ========================================================================

    #[derive(Facet)]
    struct ArgsWithConfig {
        #[facet(args::named)]
        verbose: bool,

        #[facet(args::config)]
        config: ServerConfig,
    }

    #[derive(Facet)]
    struct ServerConfig {
        port: u16,
        host: String,
    }

    #[derive(Facet)]
    struct ArgsWithNestedConfig {
        #[facet(args::config)]
        settings: AppSettings,
    }

    #[derive(Facet)]
    struct AppSettings {
        port: u16,
        smtp: SmtpConfig,
    }

    #[derive(Facet)]
    struct SmtpConfig {
        host: String,
        connection_timeout: u64,
    }

    #[derive(Facet)]
    struct ArgsWithListConfig {
        #[facet(args::config)]
        config: ListConfig,
    }

    #[derive(Facet)]
    struct ListConfig {
        ports: Vec<u16>,
        allowed_hosts: Vec<String>,
    }

    // ========================================================================
    // Helper functions
    // ========================================================================

    fn env_config(prefix: &str) -> EnvConfig {
        EnvConfigBuilder::new().prefix(prefix).build()
    }

    fn env_config_strict(prefix: &str) -> EnvConfig {
        EnvConfigBuilder::new().prefix(prefix).strict().build()
    }

    fn get_nested<'a>(cv: &'a ConfigValue, path: &[&str]) -> Option<&'a ConfigValue> {
        let mut current = cv;
        for key in path {
            match current {
                ConfigValue::Object(obj) => {
                    current = obj.value.get(*key)?;
                }
                _ => return None,
            }
        }
        Some(current)
    }

    fn get_string(cv: &ConfigValue) -> Option<&str> {
        match cv {
            ConfigValue::String(s) => Some(&s.value),
            _ => None,
        }
    }

    fn get_array_len(cv: &ConfigValue) -> Option<usize> {
        match cv {
            ConfigValue::Array(arr) => Some(arr.value.len()),
            _ => None,
        }
    }

    // ========================================================================
    // Tests: Basic parsing
    // ========================================================================

    #[test]
    fn test_empty_env() {
        let schema = Schema::from_shape(ArgsWithConfig::SHAPE).unwrap();
        let env = MockEnv::new();
        let config = env_config("REEF");

        let output = parse_env(&schema, &config, &env);

        assert!(output.diagnostics.is_empty());
        assert!(output.unused_keys.is_empty());
        // Empty env should produce an empty object (or None?)
        // Let's say it produces an object with just the config field as empty object
    }

    #[test]
    fn test_single_flat_field() {
        let schema = Schema::from_shape(ArgsWithConfig::SHAPE).unwrap();
        let env = MockEnv::from_pairs([("REEF__PORT", "8080")]);
        let config = env_config("REEF");

        let output = parse_env(&schema, &config, &env);

        assert!(output.diagnostics.is_empty());
        let value = output.value.expect("should have value");

        // Should be {config: {port: "8080"}}
        let port = get_nested(&value, &["config", "port"]).expect("should have config.port");
        assert_eq!(get_string(port), Some("8080"));
    }

    #[test]
    fn test_multiple_flat_fields() {
        let schema = Schema::from_shape(ArgsWithConfig::SHAPE).unwrap();
        let env = MockEnv::from_pairs([("REEF__PORT", "8080"), ("REEF__HOST", "localhost")]);
        let config = env_config("REEF");

        let output = parse_env(&schema, &config, &env);

        assert!(output.diagnostics.is_empty());
        let value = output.value.expect("should have value");

        let port = get_nested(&value, &["config", "port"]).expect("should have config.port");
        assert_eq!(get_string(port), Some("8080"));

        let host = get_nested(&value, &["config", "host"]).expect("should have config.host");
        assert_eq!(get_string(host), Some("localhost"));
    }

    #[test]
    fn test_nested_field() {
        let schema = Schema::from_shape(ArgsWithNestedConfig::SHAPE).unwrap();
        let env = MockEnv::from_pairs([("REEF__SMTP__HOST", "mail.example.com")]);
        let config = env_config("REEF");

        let output = parse_env(&schema, &config, &env);

        assert!(output.diagnostics.is_empty());
        let value = output.value.expect("should have value");

        // Config field is named "settings" in this schema
        let host = get_nested(&value, &["settings", "smtp", "host"])
            .expect("should have settings.smtp.host");
        assert_eq!(get_string(host), Some("mail.example.com"));
    }

    #[test]
    fn test_deeply_nested() {
        let schema = Schema::from_shape(ArgsWithNestedConfig::SHAPE).unwrap();
        let env = MockEnv::from_pairs([
            ("REEF__PORT", "8080"),
            ("REEF__SMTP__HOST", "mail.example.com"),
            ("REEF__SMTP__CONNECTION_TIMEOUT", "30"),
        ]);
        let config = env_config("REEF");

        let output = parse_env(&schema, &config, &env);

        assert!(output.diagnostics.is_empty());
        let value = output.value.expect("should have value");

        let port = get_nested(&value, &["settings", "port"]).expect("port");
        assert_eq!(get_string(port), Some("8080"));

        let host = get_nested(&value, &["settings", "smtp", "host"]).expect("smtp.host");
        assert_eq!(get_string(host), Some("mail.example.com"));

        let timeout = get_nested(&value, &["settings", "smtp", "connection_timeout"])
            .expect("smtp.connection_timeout");
        assert_eq!(get_string(timeout), Some("30"));
    }

    // ========================================================================
    // Tests: Value handling
    // ========================================================================

    #[test]
    fn test_comma_separated_list() {
        let schema = Schema::from_shape(ArgsWithListConfig::SHAPE).unwrap();
        let env = MockEnv::from_pairs([("REEF__PORTS", "8080,8081,8082")]);
        let config = env_config("REEF");

        let output = parse_env(&schema, &config, &env);

        assert!(output.diagnostics.is_empty());
        let value = output.value.expect("should have value");

        let ports = get_nested(&value, &["config", "ports"]).expect("config.ports");
        assert_eq!(get_array_len(ports), Some(3));
    }

    #[test]
    fn test_escaped_comma() {
        let schema = Schema::from_shape(ArgsWithConfig::SHAPE).unwrap();
        let env = MockEnv::from_pairs([("REEF__HOST", r"hello\, world")]);
        let config = env_config("REEF");

        let output = parse_env(&schema, &config, &env);

        assert!(output.diagnostics.is_empty());
        let value = output.value.expect("should have value");

        let host = get_nested(&value, &["config", "host"]).expect("config.host");
        assert_eq!(get_string(host), Some("hello, world"));
    }

    #[test]
    fn test_values_stay_as_strings() {
        // We don't parse "8080" into an integer - that's the driver's job
        let schema = Schema::from_shape(ArgsWithConfig::SHAPE).unwrap();
        let env = MockEnv::from_pairs([("REEF__PORT", "8080")]);
        let config = env_config("REEF");

        let output = parse_env(&schema, &config, &env);

        let value = output.value.expect("should have value");
        let port = get_nested(&value, &["config", "port"]).expect("config.port");

        // Should be a string, not an integer
        assert!(matches!(port, ConfigValue::String(_)));
    }

    // ========================================================================
    // Tests: Provenance
    // ========================================================================

    #[test]
    fn test_provenance_is_set() {
        use crate::provenance::Provenance;

        let schema = Schema::from_shape(ArgsWithConfig::SHAPE).unwrap();
        let env = MockEnv::from_pairs([("REEF__PORT", "8080")]);
        let config = env_config("REEF");

        let output = parse_env(&schema, &config, &env);
        let value = output.value.expect("should have value");

        let port = get_nested(&value, &["config", "port"]).expect("config.port");
        if let ConfigValue::String(s) = port {
            let prov = s.provenance.as_ref().expect("should have provenance");
            assert!(matches!(prov, Provenance::Env { .. }));
            if let Provenance::Env { var, value } = prov {
                assert_eq!(var, "REEF__PORT");
                assert_eq!(value, "8080");
            }
        } else {
            panic!("expected string");
        }
    }

    // ========================================================================
    // Tests: Malformed names (diagnostics)
    // ========================================================================

    #[test]
    fn test_empty_segment_diagnostic() {
        let schema = Schema::from_shape(ArgsWithConfig::SHAPE).unwrap();
        let env = MockEnv::from_pairs([("REEF__FOO____BAR", "x")]);
        let config = env_config("REEF");

        let output = parse_env(&schema, &config, &env);

        // Should have a diagnostic about invalid env var name
        assert!(!output.diagnostics.is_empty());
        assert!(
            output
                .diagnostics
                .iter()
                .any(|d| d.message.contains("empty segment") || d.message.contains("invalid"))
        );
    }

    #[test]
    fn test_just_prefix_diagnostic() {
        let schema = Schema::from_shape(ArgsWithConfig::SHAPE).unwrap();
        let env = MockEnv::from_pairs([("REEF__", "x")]);
        let config = env_config("REEF");

        let output = parse_env(&schema, &config, &env);

        // Should have a diagnostic
        assert!(!output.diagnostics.is_empty());
    }

    #[test]
    fn test_wrong_prefix_ignored() {
        let schema = Schema::from_shape(ArgsWithConfig::SHAPE).unwrap();
        let env = MockEnv::from_pairs([("OTHER__PORT", "8080")]);
        let config = env_config("REEF");

        let output = parse_env(&schema, &config, &env);

        // No diagnostics - it's just a different prefix
        assert!(output.diagnostics.is_empty());
        assert!(output.unused_keys.is_empty());
        // No value or empty object
    }

    #[test]
    fn test_single_underscore_ignored() {
        let schema = Schema::from_shape(ArgsWithConfig::SHAPE).unwrap();
        let env = MockEnv::from_pairs([("REEF_PORT", "8080")]);
        let config = env_config("REEF");

        let output = parse_env(&schema, &config, &env);

        // Single underscore doesn't match PREFIX__ pattern
        assert!(output.diagnostics.is_empty());
        assert!(output.unused_keys.is_empty());
    }

    // ========================================================================
    // Tests: Unused keys (schema-aware)
    // ========================================================================

    #[test]
    fn test_unknown_field_unused_key() {
        let schema = Schema::from_shape(ArgsWithConfig::SHAPE).unwrap();
        // Typo: PORTT instead of PORT
        let env = MockEnv::from_pairs([("REEF__PORTT", "8080")]);
        let config = env_config("REEF");

        let output = parse_env(&schema, &config, &env);

        // Should be in unused_keys
        assert!(!output.unused_keys.is_empty());
        assert!(output.unused_keys.iter().any(|k| {
            // The key path should contain "portt"
            k.key.iter().any(|s| s == "portt")
        }));
    }

    #[test]
    fn test_unknown_nested_field_unused_key() {
        let schema = Schema::from_shape(ArgsWithNestedConfig::SHAPE).unwrap();
        // Typo: HOSTT instead of HOST
        let env = MockEnv::from_pairs([("REEF__SMTP__HOSTT", "x")]);
        let config = env_config("REEF");

        let output = parse_env(&schema, &config, &env);

        assert!(!output.unused_keys.is_empty());
    }

    #[test]
    fn test_strict_mode_tracks_unknown_keys() {
        // In strict mode, unknown keys are tracked in unused_keys.
        // The driver will report them alongside the config dump (not as early errors).
        let schema = Schema::from_shape(ArgsWithConfig::SHAPE).unwrap();
        let env = MockEnv::from_pairs([("REEF__PORTT", "8080")]);
        let config = env_config_strict("REEF");

        let output = parse_env(&schema, &config, &env);

        // Unknown keys should be tracked in unused_keys
        assert!(
            !output.unused_keys.is_empty(),
            "should track unknown key in unused_keys"
        );
        assert!(
            output
                .unused_keys
                .iter()
                .any(|uk| uk.key.join(".") == "portt"),
            "unused_keys should contain 'portt': {:?}",
            output.unused_keys
        );

        // No error diagnostics at parse time - driver handles reporting with dump
        let errors: Vec<_> = output
            .diagnostics
            .iter()
            .filter(|d| d.severity == Severity::Error)
            .collect();
        assert!(
            errors.is_empty(),
            "should not have error diagnostics at parse time, got: {:?}",
            errors
        );
    }

    // ========================================================================
    // Tests: Edge cases
    // ========================================================================

    #[test]
    fn test_case_matching() {
        // Env vars are SCREAMING_SNAKE, schema fields are snake_case
        let schema = Schema::from_shape(ArgsWithConfig::SHAPE).unwrap();
        let env = MockEnv::from_pairs([("REEF__PORT", "8080")]);
        let config = env_config("REEF");

        let output = parse_env(&schema, &config, &env);

        assert!(output.diagnostics.is_empty());
        let value = output.value.expect("should have value");
        // "PORT" should match "port"
        assert!(get_nested(&value, &["config", "port"]).is_some());
    }

    #[test]
    fn test_field_with_underscore() {
        // connection_timeout in schema should match CONNECTION_TIMEOUT in env
        let schema = Schema::from_shape(ArgsWithNestedConfig::SHAPE).unwrap();
        let env = MockEnv::from_pairs([("REEF__SMTP__CONNECTION_TIMEOUT", "30")]);
        let config = env_config("REEF");

        let output = parse_env(&schema, &config, &env);

        assert!(output.diagnostics.is_empty());
        let value = output.value.expect("should have value");
        assert!(get_nested(&value, &["settings", "smtp", "connection_timeout"]).is_some());
    }

    #[test]
    fn test_empty_value() {
        let schema = Schema::from_shape(ArgsWithConfig::SHAPE).unwrap();
        let env = MockEnv::from_pairs([("REEF__PORT", "")]);
        let config = env_config("REEF");

        let output = parse_env(&schema, &config, &env);

        // Empty value should still be set (as empty string), not skipped
        assert!(output.diagnostics.is_empty());
        let value = output.value.expect("should have value");
        let port = get_nested(&value, &["config", "port"]).expect("config.port");
        assert_eq!(get_string(port), Some(""));
    }

    // ========================================================================
    // Tests: No config field in schema
    // ========================================================================

    #[derive(Facet)]
    struct ArgsWithoutConfig {
        #[facet(args::named)]
        verbose: bool,
    }

    #[test]
    fn test_no_config_field_in_schema() {
        // If the schema has no config field, env vars matching the prefix
        // should all be unused keys (or we could emit a warning?)
        let schema = Schema::from_shape(ArgsWithoutConfig::SHAPE).unwrap();
        let env = MockEnv::from_pairs([("REEF__PORT", "8080")]);
        let config = env_config("REEF");

        let output = parse_env(&schema, &config, &env);

        // No config field means all env vars are unused
        assert!(!output.unused_keys.is_empty());
    }

    // ========================================================================
    // Tests: Flattened config fields
    // ========================================================================

    #[derive(Facet)]
    struct CommonConfig {
        log_level: String,
        debug: bool,
    }

    #[derive(Facet)]
    struct ServerConfigWithFlatten {
        port: u16,
        #[facet(flatten)]
        common: CommonConfig,
    }

    #[derive(Facet)]
    struct ArgsWithFlattenConfig {
        #[facet(args::named)]
        verbose: bool,

        #[facet(args::config)]
        config: ServerConfigWithFlatten,
    }

    #[test]
    fn test_flatten_config_parses_flattened_field() {
        // With flatten, REEF__LOG_LEVEL (not REEF__COMMON__LOG_LEVEL) sets log_level
        // The schema hoists flattened fields to the parent level
        let schema = Schema::from_shape(ArgsWithFlattenConfig::SHAPE).unwrap();
        let env = MockEnv::from_pairs([("REEF__LOG_LEVEL", "debug")]);
        let config = env_config("REEF");

        let output = parse_env(&schema, &config, &env);

        assert!(
            output.diagnostics.is_empty(),
            "diagnostics: {:?}",
            output.diagnostics
        );
        assert!(
            output.unused_keys.is_empty(),
            "unused keys: {:?}",
            output.unused_keys
        );

        let value = output.value.expect("should have value");
        // Flattened field appears at the flattened level, not nested
        let log_level = get_nested(&value, &["config", "log_level"]).expect("config.log_level");
        assert_eq!(get_string(log_level), Some("debug"));
    }

    #[test]
    fn test_flatten_config_top_level_and_flattened() {
        // Mix of top-level (port) and flattened (debug from common) config fields
        let schema = Schema::from_shape(ArgsWithFlattenConfig::SHAPE).unwrap();
        // PORT is not flattened, DEBUG is flattened from common
        let env = MockEnv::from_pairs([("REEF__PORT", "8080"), ("REEF__DEBUG", "true")]);
        let config = env_config("REEF");

        let output = parse_env(&schema, &config, &env);

        assert!(
            output.diagnostics.is_empty(),
            "diagnostics: {:?}",
            output.diagnostics
        );
        assert!(
            output.unused_keys.is_empty(),
            "unused keys: {:?}",
            output.unused_keys
        );

        let value = output.value.expect("should have value");
        let port = get_nested(&value, &["config", "port"]).expect("config.port");
        assert_eq!(get_string(port), Some("8080"));

        // Flattened field appears at the flattened level
        let debug = get_nested(&value, &["config", "debug"]).expect("config.debug");
        assert_eq!(get_string(debug), Some("true"));
    }

    // ------------------------------------------------------------------------
    // Two-level flatten tests
    // ------------------------------------------------------------------------

    #[derive(Facet)]
    struct DeepConfig {
        trace: bool,
    }

    #[derive(Facet)]
    struct MiddleConfig {
        #[facet(flatten)]
        deep: DeepConfig,
        verbose: bool,
    }

    #[derive(Facet)]
    struct OuterConfigWithDeepFlatten {
        name: String,
        #[facet(flatten)]
        middle: MiddleConfig,
    }

    #[derive(Facet)]
    struct ArgsWithDeepFlattenConfig {
        #[facet(args::config)]
        config: OuterConfigWithDeepFlatten,
    }

    #[test]
    fn test_two_level_flatten_config() {
        // trace is flattened from deep -> middle -> outer
        // So REEF__TRACE should work (not REEF__MIDDLE__DEEP__TRACE)
        let schema = Schema::from_shape(ArgsWithDeepFlattenConfig::SHAPE).unwrap();
        let env = MockEnv::from_pairs([
            ("REEF__NAME", "myapp"),
            ("REEF__VERBOSE", "true"),
            ("REEF__TRACE", "true"),
        ]);
        let config = env_config("REEF");

        let output = parse_env(&schema, &config, &env);

        assert!(
            output.diagnostics.is_empty(),
            "diagnostics: {:?}",
            output.diagnostics
        );
        assert!(
            output.unused_keys.is_empty(),
            "unused keys: {:?}",
            output.unused_keys
        );

        let value = output.value.expect("should have value");

        // All fields appear at the top config level due to flattening
        let name = get_nested(&value, &["config", "name"]).expect("config.name");
        assert_eq!(get_string(name), Some("myapp"));

        let verbose = get_nested(&value, &["config", "verbose"]).expect("config.verbose");
        assert_eq!(get_string(verbose), Some("true"));

        let trace = get_nested(&value, &["config", "trace"]).expect("config.trace");
        assert_eq!(get_string(trace), Some("true"));
    }

    #[test]
    fn test_nested_path_rejected_for_flattened_field() {
        // REEF__COMMON__LOG_LEVEL should be rejected because "common" doesn't exist
        // in the flattened schema (log_level is hoisted to the parent)
        let schema = Schema::from_shape(ArgsWithFlattenConfig::SHAPE).unwrap();
        let env = MockEnv::from_pairs([("REEF__COMMON__LOG_LEVEL", "debug")]);
        let config = env_config("REEF");

        let output = parse_env(&schema, &config, &env);

        // Should have an unused key because "common" doesn't exist in schema
        assert!(
            !output.unused_keys.is_empty(),
            "should reject nested path for flattened field"
        );
        assert!(
            output
                .unused_keys
                .iter()
                .any(|k| k.key.contains(&"common".to_string())),
            "unused key should contain 'common': {:?}",
            output.unused_keys
        );
    }

    // ========================================================================
    // Tests: Env aliases
    // ========================================================================

    #[derive(Facet)]
    struct ConfigWithAlias {
        /// Database URL with standard alias
        #[facet(args::env_alias = "DATABASE_URL")]
        database_url: String,

        /// Port without alias
        port: u16,
    }

    #[derive(Facet)]
    struct ArgsWithAliasConfig {
        #[facet(args::config)]
        config: ConfigWithAlias,
    }

    #[test]
    fn test_env_alias_basic() {
        // DATABASE_URL should be read via the alias
        let schema = Schema::from_shape(ArgsWithAliasConfig::SHAPE).unwrap();
        let env = MockEnv::from_pairs([("DATABASE_URL", "postgres://localhost/mydb")]);
        let config = env_config("REEF");

        let output = parse_env(&schema, &config, &env);

        assert!(
            output.diagnostics.is_empty(),
            "diagnostics: {:?}",
            output.diagnostics
        );
        let value = output.value.expect("should have value");

        let db_url = get_nested(&value, &["config", "database_url"]).expect("config.database_url");
        assert_eq!(get_string(db_url), Some("postgres://localhost/mydb"));
    }

    #[test]
    fn test_env_alias_prefixed_wins() {
        // When both prefixed and alias are set, prefixed wins
        let schema = Schema::from_shape(ArgsWithAliasConfig::SHAPE).unwrap();
        let env = MockEnv::from_pairs([
            ("DATABASE_URL", "alias_value"),
            ("REEF__DATABASE_URL", "prefixed_value"),
        ]);
        let config = env_config("REEF");

        let output = parse_env(&schema, &config, &env);

        assert!(
            output.diagnostics.is_empty(),
            "diagnostics: {:?}",
            output.diagnostics
        );
        let value = output.value.expect("should have value");

        let db_url = get_nested(&value, &["config", "database_url"]).expect("config.database_url");
        // Prefixed var should win over alias
        assert_eq!(get_string(db_url), Some("prefixed_value"));
    }

    #[test]
    fn test_env_alias_only_alias_set() {
        // Only alias set, no prefixed - alias should be used
        let schema = Schema::from_shape(ArgsWithAliasConfig::SHAPE).unwrap();
        let env = MockEnv::from_pairs([("DATABASE_URL", "alias_value"), ("REEF__PORT", "8080")]);
        let config = env_config("REEF");

        let output = parse_env(&schema, &config, &env);

        assert!(
            output.diagnostics.is_empty(),
            "diagnostics: {:?}",
            output.diagnostics
        );
        let value = output.value.expect("should have value");

        let db_url = get_nested(&value, &["config", "database_url"]).expect("config.database_url");
        assert_eq!(get_string(db_url), Some("alias_value"));

        let port = get_nested(&value, &["config", "port"]).expect("config.port");
        assert_eq!(get_string(port), Some("8080"));
    }

    #[derive(Facet)]
    struct ConfigWithMultipleAliases {
        /// Database URL with multiple aliases
        #[facet(args::env_alias = "DATABASE_URL", args::env_alias = "DB_URL")]
        database_url: String,
    }

    #[derive(Facet)]
    struct ArgsWithMultipleAliasConfig {
        #[facet(args::config)]
        config: ConfigWithMultipleAliases,
    }

    #[test]
    fn test_env_alias_multiple_aliases_first_wins() {
        // When multiple aliases exist, the first one found is used
        let schema = Schema::from_shape(ArgsWithMultipleAliasConfig::SHAPE).unwrap();
        // Only the second alias is set
        let env = MockEnv::from_pairs([("DB_URL", "second_alias_value")]);
        let config = env_config("REEF");

        let output = parse_env(&schema, &config, &env);

        assert!(
            output.diagnostics.is_empty(),
            "diagnostics: {:?}",
            output.diagnostics
        );
        let value = output.value.expect("should have value");

        let db_url = get_nested(&value, &["config", "database_url"]).expect("config.database_url");
        assert_eq!(get_string(db_url), Some("second_alias_value"));
    }

    #[test]
    fn test_env_alias_provenance() {
        // Provenance should show the actual alias var that was used
        use crate::provenance::Provenance;

        let schema = Schema::from_shape(ArgsWithAliasConfig::SHAPE).unwrap();
        let env = MockEnv::from_pairs([("DATABASE_URL", "postgres://localhost/mydb")]);
        let config = env_config("REEF");

        let output = parse_env(&schema, &config, &env);

        let value = output.value.expect("should have value");
        let db_url = get_nested(&value, &["config", "database_url"]).expect("config.database_url");

        if let ConfigValue::String(s) = db_url {
            let prov = s.provenance.as_ref().expect("should have provenance");
            if let Provenance::Env { var, value } = prov {
                // Should show DATABASE_URL, not REEF__DATABASE_URL
                assert_eq!(var, "DATABASE_URL");
                assert_eq!(value, "postgres://localhost/mydb");
            } else {
                panic!("expected Env provenance");
            }
        } else {
            panic!("expected string");
        }
    }

    #[derive(Facet)]
    struct NestedConfigWithAlias {
        db: DbConfig,
    }

    #[derive(Facet)]
    struct DbConfig {
        #[facet(args::env_alias = "DATABASE_URL")]
        url: String,
    }

    #[derive(Facet)]
    struct ArgsWithNestedAliasConfig {
        #[facet(args::config)]
        config: NestedConfigWithAlias,
    }

    #[test]
    fn test_env_alias_in_nested_struct() {
        // Alias should work even when field is in a nested struct
        let schema = Schema::from_shape(ArgsWithNestedAliasConfig::SHAPE).unwrap();
        let env = MockEnv::from_pairs([("DATABASE_URL", "postgres://localhost/mydb")]);
        let config = env_config("REEF");

        let output = parse_env(&schema, &config, &env);

        assert!(
            output.diagnostics.is_empty(),
            "diagnostics: {:?}",
            output.diagnostics
        );
        let value = output.value.expect("should have value");

        let url = get_nested(&value, &["config", "db", "url"]).expect("config.db.url");
        assert_eq!(get_string(url), Some("postgres://localhost/mydb"));
    }

    #[test]
    fn test_env_alias_nested_prefixed_wins() {
        // Prefixed var should win over alias even in nested struct
        let schema = Schema::from_shape(ArgsWithNestedAliasConfig::SHAPE).unwrap();
        let env = MockEnv::from_pairs([
            ("DATABASE_URL", "alias_value"),
            ("REEF__DB__URL", "prefixed_value"),
        ]);
        let config = env_config("REEF");

        let output = parse_env(&schema, &config, &env);

        let value = output.value.expect("should have value");
        let url = get_nested(&value, &["config", "db", "url"]).expect("config.db.url");
        assert_eq!(get_string(url), Some("prefixed_value"));
    }

    // ========================================================================
    // Tests: Schema-guided enum validation
    // ========================================================================

    /// Log level enum for testing enum validation
    #[derive(Facet)]
    #[repr(u8)]
    #[allow(dead_code)]
    enum LogLevel {
        Debug,
        Info,
        Warn,
        Error,
    }

    #[derive(Facet)]
    struct ConfigWithEnum {
        log_level: LogLevel,
        port: u16,
    }

    #[derive(Facet)]
    struct ArgsWithEnumConfig {
        #[facet(args::config)]
        config: ConfigWithEnum,
    }

    #[test]
    fn test_enum_valid_variant_no_warning() {
        // Valid variant should not produce a warning
        let schema = Schema::from_shape(ArgsWithEnumConfig::SHAPE).unwrap();
        let env = MockEnv::from_pairs([("REEF__LOG_LEVEL", "Debug")]);
        let config = env_config("REEF");

        let output = parse_env(&schema, &config, &env);

        assert!(
            output.diagnostics.is_empty(),
            "valid enum variant should not produce warnings: {:?}",
            output.diagnostics
        );

        let value = output.value.expect("should have value");
        let log_level = get_nested(&value, &["config", "log_level"]).expect("config.log_level");
        assert_eq!(get_string(log_level), Some("Debug"));
    }

    #[test]
    fn test_enum_invalid_variant_produces_warning() {
        // Invalid variant should produce a warning with helpful message
        let schema = Schema::from_shape(ArgsWithEnumConfig::SHAPE).unwrap();
        let env = MockEnv::from_pairs([("REEF__LOG_LEVEL", "Debugg")]); // typo
        let config = env_config("REEF");

        let output = parse_env(&schema, &config, &env);

        // Should have a warning
        assert!(
            !output.diagnostics.is_empty(),
            "invalid enum variant should produce a warning"
        );

        // Warning should mention the invalid value and valid variants
        let warning = &output.diagnostics[0];
        assert!(
            warning.message.contains("Debugg"),
            "warning should mention the invalid value: {}",
            warning.message
        );
        assert!(
            warning.message.contains("Debug")
                && warning.message.contains("Info")
                && warning.message.contains("Warn")
                && warning.message.contains("Error"),
            "warning should list valid variants: {}",
            warning.message
        );
        // Should include a "did you mean" suggestion since "Debugg" is similar to "Debug"
        assert!(
            warning.message.contains("Did you mean 'Debug'?"),
            "warning should suggest similar variant: {}",
            warning.message
        );

        // Value should still be set (the driver will do the actual parsing/rejection)
        let value = output.value.expect("should have value");
        let log_level = get_nested(&value, &["config", "log_level"]).expect("config.log_level");
        assert_eq!(get_string(log_level), Some("Debugg"));
    }

    #[derive(Facet)]
    struct ConfigWithOptionalEnum {
        log_level: Option<LogLevel>,
    }

    #[derive(Facet)]
    struct ArgsWithOptionalEnumConfig {
        #[facet(args::config)]
        config: ConfigWithOptionalEnum,
    }

    #[test]
    fn test_optional_enum_validation() {
        // Optional enum should also be validated
        let schema = Schema::from_shape(ArgsWithOptionalEnumConfig::SHAPE).unwrap();
        let env = MockEnv::from_pairs([("REEF__LOG_LEVEL", "invalid")]);
        let config = env_config("REEF");

        let output = parse_env(&schema, &config, &env);

        // Should have a warning even for optional enum
        assert!(
            !output.diagnostics.is_empty(),
            "invalid optional enum variant should produce a warning"
        );
    }

    #[derive(Facet)]
    struct NestedConfigWithEnum {
        logging: LoggingConfig,
    }

    #[derive(Facet)]
    struct LoggingConfig {
        level: LogLevel,
    }

    #[derive(Facet)]
    struct ArgsWithNestedEnumConfig {
        #[facet(args::config)]
        config: NestedConfigWithEnum,
    }

    #[test]
    fn test_nested_enum_validation() {
        // Enum in nested struct should be validated
        let schema = Schema::from_shape(ArgsWithNestedEnumConfig::SHAPE).unwrap();
        let env = MockEnv::from_pairs([("REEF__LOGGING__LEVEL", "unknown")]);
        let config = env_config("REEF");

        let output = parse_env(&schema, &config, &env);

        // Should have a warning
        assert!(
            !output.diagnostics.is_empty(),
            "invalid nested enum variant should produce a warning"
        );
    }

    // ========================================================================
    // Tests: Enum variant field setting (issue #37)
    // ========================================================================

    /// Storage enum with struct variants for testing enum variant field paths
    #[derive(Facet)]
    #[repr(u8)]
    #[allow(dead_code)]
    enum Storage {
        S3 { bucket: String, region: String },
        Gcp { project: String, zone: String },
        Local { path: String },
    }

    #[derive(Facet)]
    struct ConfigWithEnumVariants {
        storage: Storage,
        port: u16,
    }

    #[derive(Facet)]
    struct ArgsWithEnumVariantConfig {
        #[facet(args::config)]
        config: ConfigWithEnumVariants,
    }

    #[test]
    fn test_enum_variant_field_single() {
        // Setting a single field within an enum variant: REEF__STORAGE__S3__BUCKET
        let schema = Schema::from_shape(ArgsWithEnumVariantConfig::SHAPE).unwrap();
        let env = MockEnv::from_pairs([("REEF__STORAGE__S3__BUCKET", "my-bucket")]);
        let config = env_config("REEF");

        let output = parse_env(&schema, &config, &env);

        assert!(
            output.diagnostics.is_empty(),
            "should not have diagnostics: {:?}",
            output.diagnostics
        );
        assert!(
            output.unused_keys.is_empty(),
            "should not have unused keys: {:?}",
            output.unused_keys
        );

        let value = output.value.expect("should have value");
        // Should produce: {config: {storage: {s3: {bucket: "my-bucket"}}}}
        let bucket = get_nested(&value, &["config", "storage", "S3", "bucket"])
            .expect("should have config.storage.S3.bucket");
        assert_eq!(get_string(bucket), Some("my-bucket"));
    }

    #[test]
    fn test_enum_variant_field_multiple() {
        // Setting multiple fields within the same enum variant
        let schema = Schema::from_shape(ArgsWithEnumVariantConfig::SHAPE).unwrap();
        let env = MockEnv::from_pairs([
            ("REEF__STORAGE__S3__BUCKET", "my-bucket"),
            ("REEF__STORAGE__S3__REGION", "us-east-1"),
        ]);
        let config = env_config("REEF");

        let output = parse_env(&schema, &config, &env);

        assert!(
            output.diagnostics.is_empty(),
            "should not have diagnostics: {:?}",
            output.diagnostics
        );
        assert!(
            output.unused_keys.is_empty(),
            "should not have unused keys: {:?}",
            output.unused_keys
        );

        let value = output.value.expect("should have value");
        let bucket = get_nested(&value, &["config", "storage", "S3", "bucket"])
            .expect("should have config.storage.S3.bucket");
        assert_eq!(get_string(bucket), Some("my-bucket"));

        let region = get_nested(&value, &["config", "storage", "S3", "region"])
            .expect("should have config.storage.S3.region");
        assert_eq!(get_string(region), Some("us-east-1"));
    }

    #[test]
    fn test_enum_variant_field_different_variant() {
        // Setting fields in a different variant (Gcp instead of S3)
        let schema = Schema::from_shape(ArgsWithEnumVariantConfig::SHAPE).unwrap();
        let env = MockEnv::from_pairs([("REEF__STORAGE__GCP__PROJECT", "my-project")]);
        let config = env_config("REEF");

        let output = parse_env(&schema, &config, &env);

        assert!(
            output.diagnostics.is_empty(),
            "should not have diagnostics: {:?}",
            output.diagnostics
        );
        assert!(
            output.unused_keys.is_empty(),
            "should not have unused keys: {:?}",
            output.unused_keys
        );

        let value = output.value.expect("should have value");
        let project = get_nested(&value, &["config", "storage", "Gcp", "project"])
            .expect("should have config.storage.Gcp.project");
        assert_eq!(get_string(project), Some("my-project"));
    }

    #[test]
    fn test_enum_variant_field_with_regular_field() {
        // Mix of enum variant field and regular config field
        let schema = Schema::from_shape(ArgsWithEnumVariantConfig::SHAPE).unwrap();
        let env = MockEnv::from_pairs([
            ("REEF__STORAGE__S3__BUCKET", "my-bucket"),
            ("REEF__PORT", "8080"),
        ]);
        let config = env_config("REEF");

        let output = parse_env(&schema, &config, &env);

        assert!(
            output.diagnostics.is_empty(),
            "should not have diagnostics: {:?}",
            output.diagnostics
        );
        assert!(
            output.unused_keys.is_empty(),
            "should not have unused keys: {:?}",
            output.unused_keys
        );

        let value = output.value.expect("should have value");
        let bucket = get_nested(&value, &["config", "storage", "S3", "bucket"])
            .expect("should have config.storage.S3.bucket");
        assert_eq!(get_string(bucket), Some("my-bucket"));

        let port = get_nested(&value, &["config", "port"]).expect("should have config.port");
        assert_eq!(get_string(port), Some("8080"));
    }

    #[test]
    fn test_enum_variant_unknown_variant_rejected() {
        // Unknown variant name should be rejected
        let schema = Schema::from_shape(ArgsWithEnumVariantConfig::SHAPE).unwrap();
        let env = MockEnv::from_pairs([("REEF__STORAGE__AZURE__CONTAINER", "my-container")]);
        let config = env_config("REEF");

        let output = parse_env(&schema, &config, &env);

        // Should have an unused key
        assert!(
            !output.unused_keys.is_empty(),
            "unknown variant should produce unused key"
        );
        assert!(
            output
                .unused_keys
                .iter()
                .any(|k| k.key.iter().any(|s| s == "azure")),
            "unused key should mention azure: {:?}",
            output.unused_keys
        );
    }

    #[test]
    fn test_enum_variant_unknown_field_rejected() {
        // Unknown field within a valid variant should be rejected
        let schema = Schema::from_shape(ArgsWithEnumVariantConfig::SHAPE).unwrap();
        let env = MockEnv::from_pairs([("REEF__STORAGE__S3__UNKNOWN_FIELD", "value")]);
        let config = env_config("REEF");

        let output = parse_env(&schema, &config, &env);

        // Should have an unused key
        assert!(
            !output.unused_keys.is_empty(),
            "unknown field in variant should produce unused key"
        );
    }

    #[derive(Facet)]
    struct ConfigWithOptionalEnumVariants {
        storage: Option<Storage>,
    }

    #[derive(Facet)]
    struct ArgsWithOptionalEnumVariantConfig {
        #[facet(args::config)]
        config: ConfigWithOptionalEnumVariants,
    }

    #[test]
    fn test_optional_enum_variant_field() {
        // Setting field within optional enum variant
        let schema = Schema::from_shape(ArgsWithOptionalEnumVariantConfig::SHAPE).unwrap();
        let env = MockEnv::from_pairs([("REEF__STORAGE__LOCAL__PATH", "/data")]);
        let config = env_config("REEF");

        let output = parse_env(&schema, &config, &env);

        assert!(
            output.diagnostics.is_empty(),
            "should not have diagnostics: {:?}",
            output.diagnostics
        );
        assert!(
            output.unused_keys.is_empty(),
            "should not have unused keys: {:?}",
            output.unused_keys
        );

        let value = output.value.expect("should have value");
        let path = get_nested(&value, &["config", "storage", "Local", "path"])
            .expect("should have config.storage.Local.path");
        assert_eq!(get_string(path), Some("/data"));
    }

    // ========================================================================
    // Tests: Virtual env document and span assignment
    // ========================================================================

    #[test]
    fn test_env_spans_are_assigned() {
        // Env vars should have spans pointing into a virtual document
        let schema = Schema::from_shape(ArgsWithConfig::SHAPE).unwrap();
        let env = MockEnv::from_pairs([("REEF__PORT", "8080"), ("REEF__HOST", "localhost")]);
        let config = env_config("REEF");

        let output = parse_env(&schema, &config, &env);

        // Should have source_text set
        assert!(
            output.source_text.is_some(),
            "source_text should be set when env vars are parsed"
        );

        let source_text = output.source_text.as_ref().unwrap();

        // The source_text should contain both env vars
        assert!(
            source_text.contains("REEF__PORT=\"8080\""),
            "source_text should contain REEF__PORT: {}",
            source_text
        );
        assert!(
            source_text.contains("REEF__HOST=\"localhost\""),
            "source_text should contain REEF__HOST: {}",
            source_text
        );

        // Check that spans are set on the values
        let value = output.value.expect("should have value");
        let port = get_nested(&value, &["config", "port"]).expect("config.port");

        // The port value should have a span
        assert!(port.span().is_some(), "port should have a span");

        // The span should point to the value "8080" in the source_text
        let span = port.span().unwrap();
        let offset = span.offset as usize;
        let len = span.len as usize;
        let pointed_text = &source_text[offset..offset + len];
        assert_eq!(
            pointed_text, "8080",
            "span should point to the value in source_text"
        );
    }

    #[test]
    fn test_env_spans_with_alias() {
        // Env aliases should also get spans
        let schema = Schema::from_shape(ArgsWithAliasConfig::SHAPE).unwrap();
        let env = MockEnv::from_pairs([("DATABASE_URL", "postgres://localhost/db")]);
        let config = env_config("REEF");

        let output = parse_env(&schema, &config, &env);

        assert!(
            output.source_text.is_some(),
            "source_text should be set for aliased env vars"
        );

        let source_text = output.source_text.as_ref().unwrap();
        assert!(
            source_text.contains("DATABASE_URL=\"postgres://localhost/db\""),
            "source_text should contain DATABASE_URL: {}",
            source_text
        );

        let value = output.value.expect("should have value");
        let db_url = get_nested(&value, &["config", "database_url"]).expect("config.database_url");

        let span = db_url.span().expect("db_url should have a span");
        let offset = span.offset as usize;
        let len = span.len as usize;
        let pointed_text = &source_text[offset..offset + len];
        assert_eq!(
            pointed_text, "postgres://localhost/db",
            "span should point to the value in source_text"
        );
    }

    #[test]
    fn test_env_spans_no_env_vars_no_source_text() {
        // If no env vars are set, source_text should be None (or empty)
        let schema = Schema::from_shape(ArgsWithConfig::SHAPE).unwrap();
        let env = MockEnv::new();
        let config = env_config("REEF");

        let output = parse_env(&schema, &config, &env);

        // No env vars means no source_text
        assert!(
            output.source_text.is_none(),
            "source_text should be None when no env vars are parsed"
        );
    }
}