premortem 0.6.2

A configuration library that performs a premortem on your app's config—finding all the ways it would die before it ever runs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
//! Validation trait and validators for configuration types.
//!
//! This module provides:
//! - The `Validate` trait that configuration types implement
//! - The `Validator` trait for composable validation functions
//! - Built-in validators for common patterns (strings, numbers, paths, collections)
//! - `ValidationContext` for source location lookup during validation
//!
//! # Stillwater Integration
//!
//! All validators integrate with stillwater's `Validation` type for error accumulation.
//! Use `Validation::all()` to combine multiple validators and collect ALL errors.
//!
//! # Example
//!
//! ```ignore
//! use premortem::{Validate, ConfigValidation, ConfigError, ConfigErrors};
//! use premortem::validate::{validate_field, validators::*};
//! use stillwater::Validation;
//!
//! struct ServerConfig {
//!     host: String,
//!     port: u16,
//! }
//!
//! impl Validate for ServerConfig {
//!     fn validate(&self) -> ConfigValidation<()> {
//!         Validation::all((
//!             validate_field(&self.host, "host", &[&NonEmpty]),
//!             validate_field(&self.port, "port", &[&Range(1..=65535)]),
//!         ))
//!         .map(|_| ())
//!     }
//! }
//! ```

use std::cell::RefCell;
use std::collections::HashMap;

use stillwater::Validation;

use crate::error::{ConfigError, ConfigErrors, ConfigValidation, SourceLocation};

// ============================================================================
// Validation Context (for source location lookup)
// ============================================================================

/// Map from config path to source location.
pub type SourceLocationMap = HashMap<String, SourceLocation>;

/// Context for validation with source location lookup.
///
/// This context is populated from `ConfigValues` during config building and
/// made available to validation code via thread-local storage. This enables
/// validation errors to include accurate source locations without changing
/// the `Validate` trait signature.
#[derive(Debug, Default)]
pub struct ValidationContext {
    locations: SourceLocationMap,
}

impl ValidationContext {
    /// Create a new validation context with the given source locations.
    pub fn new(locations: SourceLocationMap) -> Self {
        Self { locations }
    }

    /// Look up the source location for a config path.
    pub fn location_for(&self, path: &str) -> Option<&SourceLocation> {
        self.locations.get(path)
    }
}

// Thread-local storage for validation context.
// This is pragmatic (per stillwater philosophy) - it avoids breaking the Validate trait API
// while still enabling source location lookup from generated validation code.
thread_local! {
    static VALIDATION_CONTEXT: RefCell<Option<ValidationContext>> = const { RefCell::new(None) };
    static PATH_PREFIX: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };
}

/// Run a function with a validation context set.
///
/// The context is set for the duration of the function and cleared afterward.
/// This is used by `ConfigBuilder` to provide source locations during validation.
pub fn with_validation_context<F, R>(ctx: ValidationContext, f: F) -> R
where
    F: FnOnce() -> R,
{
    VALIDATION_CONTEXT.with(|cell| {
        *cell.borrow_mut() = Some(ctx);
    });
    let result = f();
    VALIDATION_CONTEXT.with(|cell| {
        *cell.borrow_mut() = None;
    });
    result
}

/// Look up the source location for a config path from the current context.
///
/// Returns `None` if no context is set or if the path is not found.
/// This is used by generated validation code to attach source locations to errors.
///
/// The lookup path is computed by prepending any active path prefixes (from nested
/// validation) to the given field path.
pub fn current_source_location(path: &str) -> Option<SourceLocation> {
    // Build full path by prepending the current prefix
    let full_path = PATH_PREFIX.with(|cell| {
        let prefixes = cell.borrow();
        if prefixes.is_empty() {
            path.to_string()
        } else {
            format!("{}.{}", prefixes.join("."), path)
        }
    });

    VALIDATION_CONTEXT.with(|cell| {
        cell.borrow()
            .as_ref()
            .and_then(|ctx| ctx.location_for(&full_path).cloned())
    })
}

/// Push a path prefix for nested validation.
///
/// Used by `validate_at` to track the current path context during nested struct validation.
pub fn push_path_prefix(prefix: &str) {
    PATH_PREFIX.with(|cell| {
        cell.borrow_mut().push(prefix.to_string());
    });
}

/// Pop a path prefix after nested validation completes.
pub fn pop_path_prefix() {
    PATH_PREFIX.with(|cell| {
        cell.borrow_mut().pop();
    });
}

/// Trait for validating configuration values.
///
/// Types implementing this trait can perform custom validation logic
/// after deserialization. The validation uses stillwater's `Validation`
/// type to accumulate all errors.
///
/// # Pure Core
///
/// Validators should be pure functions - no I/O allowed in the core validation.
/// Path validators like `FileExists` perform I/O but are acceptable for
/// configuration validation at startup time.
pub trait Validate {
    /// Validate this configuration value.
    ///
    /// Returns `ConfigValidation<()>` - either `Success(())` if validation
    /// passes, or `Failure(ConfigErrors)` with all accumulated validation errors.
    fn validate(&self) -> ConfigValidation<()>;

    /// Validate with a path prefix for error context.
    ///
    /// This adds context to all errors, following stillwater's error trail pattern.
    /// Used for nested struct validation.
    ///
    /// The path prefix is also pushed to thread-local storage so that source location
    /// lookups during nested validation use the correct full path (e.g., "server.host"
    /// instead of just "host").
    ///
    /// # Example
    ///
    /// ```ignore
    /// // If inner validation produces error at path "host",
    /// // validate_at("database") will produce error at path "database.host"
    /// database_config.validate_at("database")
    /// ```
    fn validate_at(&self, path: &str) -> ConfigValidation<()> {
        // Push prefix for source location lookups during nested validation
        push_path_prefix(path);
        let result = self.validate();
        pop_path_prefix();

        result.map_err(|errors| errors.with_path_prefix(path))
    }
}

/// Blanket implementation for types that don't need validation.
///
/// Any type that doesn't implement `Validate` will automatically pass validation.
/// This is implemented for the unit type as a no-op validator.
impl Validate for () {
    fn validate(&self) -> ConfigValidation<()> {
        Validation::Success(())
    }
}

/// Implementation for `Option<T>` where T: Validate.
///
/// None values pass validation; Some values delegate to the inner type.
impl<T: Validate> Validate for Option<T> {
    fn validate(&self) -> ConfigValidation<()> {
        match self {
            Some(inner) => inner.validate(),
            None => Validation::Success(()),
        }
    }
}

/// Implementation for `Vec<T>` where T: Validate.
///
/// Validates all elements and accumulates errors using stillwater's traverse pattern.
impl<T: Validate> Validate for Vec<T> {
    fn validate(&self) -> ConfigValidation<()> {
        if self.is_empty() {
            return Validation::Success(());
        }

        // Use traverse pattern to validate each item with index context
        let validations: Vec<ConfigValidation<()>> = self
            .iter()
            .enumerate()
            .map(|(i, item)| item.validate_at(&format!("[{}]", i)))
            .collect();
        Validation::all_vec(validations).map(|_| ())
    }
}

// Primitive types don't need validation
macro_rules! impl_validate_noop {
    ($($t:ty),*) => {
        $(
            impl Validate for $t {
                fn validate(&self) -> ConfigValidation<()> {
                    Validation::Success(())
                }
            }
        )*
    };
}

impl_validate_noop!(
    bool, i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize, f32, f64, char, String
);

impl Validate for &str {
    fn validate(&self) -> ConfigValidation<()> {
        Validation::Success(())
    }
}

impl Validate for std::path::PathBuf {
    fn validate(&self) -> ConfigValidation<()> {
        Validation::Success(())
    }
}

// ============================================================================
// Validator Trait
// ============================================================================

/// A validator function that checks a value and returns validation result.
///
/// Validators are pure functions: `&T -> ConfigValidation<()>`
/// They return either Success(()) or Failure(ConfigErrors).
///
/// # Type Parameters
///
/// - `T`: The type being validated (can be unsized, e.g., `str`, `[T]`)
pub trait Validator<T: ?Sized> {
    /// Validate a value at the given path.
    ///
    /// Returns `Success(())` if valid, or `Failure(ConfigErrors)` with an error
    /// that includes the path for context.
    fn validate(&self, value: &T, path: &str) -> ConfigValidation<()>;
}

/// Helper to create a validation failure with a single error.
fn fail(error: ConfigError) -> ConfigValidation<()> {
    Validation::Failure(ConfigErrors::single(error))
}

// ============================================================================
// Predicate-Validator Bridge (stillwater 0.13.0+)
// ============================================================================

use stillwater::predicate::Predicate;

/// Adapter that converts a `Predicate<T>` into a `Validator<T>`.
///
/// This enables using stillwater's composable predicates within premortem's
/// validation framework while maintaining source location tracking.
///
/// # Example
///
/// ```ignore
/// use premortem::validate::from_predicate;
/// use premortem::prelude::*;
///
/// let validator = from_predicate(
///     not_empty().and(len_between(3, 20))
/// );
///
/// // Use in validate_field
/// validate_field(&username, "username", &[&validator])
/// ```
pub fn from_predicate<T>(predicate: impl Predicate<T>) -> impl Validator<T>
where
    T: ?Sized,
{
    PredicateValidator(predicate)
}

/// Internal adapter struct that implements Validator for any Predicate.
struct PredicateValidator<P>(P);

impl<T, P> Validator<T> for PredicateValidator<P>
where
    T: ?Sized,
    P: Predicate<T>,
{
    fn validate(&self, value: &T, path: &str) -> ConfigValidation<()> {
        if self.0.check(value) {
            Validation::Success(())
        } else {
            // Get source location from thread-local context
            let source_location = current_source_location(path);

            Validation::Failure(ConfigErrors::single(ConfigError::ValidationError {
                path: path.to_string(),
                source_location,
                value: None, // Predicates don't provide value formatting
                message: "validation failed".to_string(),
            }))
        }
    }
}

/// Validate a field using a predicate with custom error message.
///
/// This is a convenience function that combines predicate testing with
/// premortem's error accumulation.
///
/// # Example
///
/// ```ignore
/// use premortem::validate::validate_with_predicate;
/// use premortem::prelude::*;
///
/// validate_with_predicate(
///     &port,
///     "port",
///     between(1, 65535),
///     "port must be between 1 and 65535"
/// )
/// ```
pub fn validate_with_predicate<T>(
    value: &T,
    path: &str,
    predicate: impl Predicate<T>,
    message: impl Into<String>,
) -> ConfigValidation<()>
where
    T: ?Sized,
{
    if predicate.check(value) {
        Validation::Success(())
    } else {
        let source_location = current_source_location(path);

        Validation::Failure(ConfigErrors::single(ConfigError::ValidationError {
            path: path.to_string(),
            source_location,
            value: None,
            message: message.into(),
        }))
    }
}

// ============================================================================
// Validation Helper Functions
// ============================================================================

/// Validate a field against multiple validators using Validation::all().
///
/// This is the core composition pattern - run all validators and accumulate errors.
/// Follows stillwater's "fail completely" philosophy.
///
/// # Example
///
/// ```ignore
/// use premortem::validate::{validate_field, validators::*};
///
/// let result = validate_field(&host, "host", &[&NonEmpty, &MinLength(3)]);
/// ```
pub fn validate_field<T>(
    value: &T,
    path: &str,
    validators: &[&dyn Validator<T>],
) -> ConfigValidation<()>
where
    T: ?Sized,
{
    if validators.is_empty() {
        return Validation::Success(());
    }

    let results: Vec<ConfigValidation<()>> =
        validators.iter().map(|v| v.validate(value, path)).collect();

    Validation::all_vec(results).map(|_| ())
}

/// Validate a nested struct with path context.
///
/// Delegates to the inner type's `validate_at` method.
pub fn validate_nested<T: Validate>(value: &T, path: &str) -> ConfigValidation<()> {
    value.validate_at(path)
}

/// Validate an optional nested struct.
///
/// None is always valid.
pub fn validate_optional_nested<T: Validate>(
    value: &Option<T>,
    path: &str,
) -> ConfigValidation<()> {
    match value {
        Some(v) => v.validate_at(path),
        None => Validation::Success(()),
    }
}

// ============================================================================
// Built-in Validators
// ============================================================================

/// Built-in validators for common validation patterns.
///
/// All validators are zero-cost structs that implement the `Validator` trait.
/// They can be composed using `validate_field()` for multiple checks on one field.
pub mod validators {
    use super::*;
    use std::fmt::Display;
    use std::ops::RangeInclusive;
    use std::path::Path;

    // ========================================================================
    // String Validators
    // ========================================================================

    /// Validates that a string is not empty.
    #[derive(Debug, Clone, Copy)]
    pub struct NonEmpty;

    impl Validator<str> for NonEmpty {
        fn validate(&self, value: &str, path: &str) -> ConfigValidation<()> {
            if value.is_empty() {
                fail(ConfigError::ValidationError {
                    path: path.to_string(),
                    source_location: None,
                    value: Some(String::new()),
                    message: "value cannot be empty".to_string(),
                })
            } else {
                Validation::Success(())
            }
        }
    }

    impl Validator<String> for NonEmpty {
        fn validate(&self, value: &String, path: &str) -> ConfigValidation<()> {
            <NonEmpty as Validator<str>>::validate(self, value.as_str(), path)
        }
    }

    /// Validates that a string has at least the specified length.
    #[derive(Debug, Clone, Copy)]
    pub struct MinLength(pub usize);

    impl Validator<str> for MinLength {
        fn validate(&self, value: &str, path: &str) -> ConfigValidation<()> {
            if value.len() < self.0 {
                fail(ConfigError::ValidationError {
                    path: path.to_string(),
                    source_location: None,
                    value: Some(value.to_string()),
                    message: format!("length {} is less than minimum {}", value.len(), self.0),
                })
            } else {
                Validation::Success(())
            }
        }
    }

    impl Validator<String> for MinLength {
        fn validate(&self, value: &String, path: &str) -> ConfigValidation<()> {
            <MinLength as Validator<str>>::validate(self, value.as_str(), path)
        }
    }

    /// Validates that a string has at most the specified length.
    #[derive(Debug, Clone, Copy)]
    pub struct MaxLength(pub usize);

    impl Validator<str> for MaxLength {
        fn validate(&self, value: &str, path: &str) -> ConfigValidation<()> {
            if value.len() > self.0 {
                fail(ConfigError::ValidationError {
                    path: path.to_string(),
                    source_location: None,
                    value: Some(value.to_string()),
                    message: format!("length {} exceeds maximum {}", value.len(), self.0),
                })
            } else {
                Validation::Success(())
            }
        }
    }

    impl Validator<String> for MaxLength {
        fn validate(&self, value: &String, path: &str) -> ConfigValidation<()> {
            <MaxLength as Validator<str>>::validate(self, value.as_str(), path)
        }
    }

    /// Validates that a string length is within a range (inclusive).
    #[derive(Debug, Clone)]
    pub struct Length(pub RangeInclusive<usize>);

    impl Validator<str> for Length {
        fn validate(&self, value: &str, path: &str) -> ConfigValidation<()> {
            let len = value.len();
            if !self.0.contains(&len) {
                fail(ConfigError::ValidationError {
                    path: path.to_string(),
                    source_location: None,
                    value: Some(value.to_string()),
                    message: format!(
                        "length {} is not in range {}..={}",
                        len,
                        self.0.start(),
                        self.0.end()
                    ),
                })
            } else {
                Validation::Success(())
            }
        }
    }

    impl Validator<String> for Length {
        fn validate(&self, value: &String, path: &str) -> ConfigValidation<()> {
            <Length as Validator<str>>::validate(self, value.as_str(), path)
        }
    }

    /// Validates that a string matches a regular expression pattern.
    ///
    /// The pattern string is compiled on first use. For performance-critical
    /// code, consider pre-compiling with `regex::Regex`.
    #[derive(Debug, Clone)]
    pub struct Pattern(pub String);

    impl Pattern {
        /// Create a new pattern validator.
        pub fn new(pattern: impl Into<String>) -> Self {
            Self(pattern.into())
        }
    }

    impl Validator<str> for Pattern {
        fn validate(&self, value: &str, path: &str) -> ConfigValidation<()> {
            // Compile regex - in production, consider caching
            match regex::Regex::new(&self.0) {
                Ok(re) => {
                    if re.is_match(value) {
                        Validation::Success(())
                    } else {
                        fail(ConfigError::ValidationError {
                            path: path.to_string(),
                            source_location: None,
                            value: Some(value.to_string()),
                            message: format!("value does not match pattern '{}'", self.0),
                        })
                    }
                }
                Err(e) => fail(ConfigError::ValidationError {
                    path: path.to_string(),
                    source_location: None,
                    value: Some(value.to_string()),
                    message: format!("invalid pattern '{}': {}", self.0, e),
                }),
            }
        }
    }

    impl Validator<String> for Pattern {
        fn validate(&self, value: &String, path: &str) -> ConfigValidation<()> {
            <Pattern as Validator<str>>::validate(self, value.as_str(), path)
        }
    }

    /// Validates that a string is a valid email address.
    ///
    /// Uses a simplified RFC 5322-like pattern. For strict compliance,
    /// consider using the `email_address` crate.
    #[derive(Debug, Clone, Copy)]
    pub struct Email;

    impl Validator<str> for Email {
        fn validate(&self, value: &str, path: &str) -> ConfigValidation<()> {
            // Simple email validation pattern
            // For strict RFC 5322, use email_address crate
            let email_pattern = r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$";
            let re = regex::Regex::new(email_pattern).expect("valid email regex");

            if re.is_match(value) {
                Validation::Success(())
            } else {
                fail(ConfigError::ValidationError {
                    path: path.to_string(),
                    source_location: None,
                    value: Some(value.to_string()),
                    message: "value is not a valid email address".to_string(),
                })
            }
        }
    }

    impl Validator<String> for Email {
        fn validate(&self, value: &String, path: &str) -> ConfigValidation<()> {
            <Email as Validator<str>>::validate(self, value.as_str(), path)
        }
    }

    /// Validates that a string is a valid URL.
    #[derive(Debug, Clone, Copy)]
    pub struct Url;

    impl Validator<str> for Url {
        fn validate(&self, value: &str, path: &str) -> ConfigValidation<()> {
            // Simple URL pattern - for strict validation, use the url crate
            let url_pattern = r"^(https?|ftp)://[^\s/$.?#].[^\s]*$";
            let re = regex::Regex::new(url_pattern).expect("valid url regex");

            if re.is_match(value) {
                Validation::Success(())
            } else {
                fail(ConfigError::ValidationError {
                    path: path.to_string(),
                    source_location: None,
                    value: Some(value.to_string()),
                    message: "value is not a valid URL".to_string(),
                })
            }
        }
    }

    impl Validator<String> for Url {
        fn validate(&self, value: &String, path: &str) -> ConfigValidation<()> {
            <Url as Validator<str>>::validate(self, value.as_str(), path)
        }
    }

    // ========================================================================
    // Numeric Validators
    // ========================================================================

    /// Validates that a numeric value is within a range (inclusive).
    #[derive(Debug, Clone)]
    pub struct Range<T>(pub RangeInclusive<T>);

    impl<T> Validator<T> for Range<T>
    where
        T: PartialOrd + Display + Clone,
    {
        fn validate(&self, value: &T, path: &str) -> ConfigValidation<()> {
            if !self.0.contains(value) {
                fail(ConfigError::ValidationError {
                    path: path.to_string(),
                    source_location: None,
                    value: Some(value.to_string()),
                    message: format!(
                        "value {} is not in range {}..={}",
                        value,
                        self.0.start(),
                        self.0.end()
                    ),
                })
            } else {
                Validation::Success(())
            }
        }
    }

    /// Validates that a numeric value is positive (> 0).
    #[derive(Debug, Clone, Copy)]
    pub struct Positive;

    macro_rules! impl_positive_for_signed {
        ($($t:ty),*) => {
            $(
                impl Validator<$t> for Positive {
                    fn validate(&self, value: &$t, path: &str) -> ConfigValidation<()> {
                        if *value > 0 {
                            Validation::Success(())
                        } else {
                            fail(ConfigError::ValidationError {
                                path: path.to_string(),
                                source_location: None,
                                value: Some(value.to_string()),
                                message: "value must be positive".to_string(),
                            })
                        }
                    }
                }
            )*
        };
    }

    macro_rules! impl_positive_for_unsigned {
        ($($t:ty),*) => {
            $(
                impl Validator<$t> for Positive {
                    fn validate(&self, value: &$t, path: &str) -> ConfigValidation<()> {
                        if *value > 0 {
                            Validation::Success(())
                        } else {
                            fail(ConfigError::ValidationError {
                                path: path.to_string(),
                                source_location: None,
                                value: Some(value.to_string()),
                                message: "value must be positive".to_string(),
                            })
                        }
                    }
                }
            )*
        };
    }

    macro_rules! impl_positive_for_float {
        ($($t:ty),*) => {
            $(
                impl Validator<$t> for Positive {
                    fn validate(&self, value: &$t, path: &str) -> ConfigValidation<()> {
                        if *value > 0.0 {
                            Validation::Success(())
                        } else {
                            fail(ConfigError::ValidationError {
                                path: path.to_string(),
                                source_location: None,
                                value: Some(value.to_string()),
                                message: "value must be positive".to_string(),
                            })
                        }
                    }
                }
            )*
        };
    }

    impl_positive_for_signed!(i8, i16, i32, i64, i128, isize);
    impl_positive_for_unsigned!(u8, u16, u32, u64, u128, usize);
    impl_positive_for_float!(f32, f64);

    /// Validates that a numeric value is negative (< 0).
    #[derive(Debug, Clone, Copy)]
    pub struct Negative;

    macro_rules! impl_negative_for_signed {
        ($($t:ty),*) => {
            $(
                impl Validator<$t> for Negative {
                    fn validate(&self, value: &$t, path: &str) -> ConfigValidation<()> {
                        if *value < 0 {
                            Validation::Success(())
                        } else {
                            fail(ConfigError::ValidationError {
                                path: path.to_string(),
                                source_location: None,
                                value: Some(value.to_string()),
                                message: "value must be negative".to_string(),
                            })
                        }
                    }
                }
            )*
        };
    }

    macro_rules! impl_negative_for_float {
        ($($t:ty),*) => {
            $(
                impl Validator<$t> for Negative {
                    fn validate(&self, value: &$t, path: &str) -> ConfigValidation<()> {
                        if *value < 0.0 {
                            Validation::Success(())
                        } else {
                            fail(ConfigError::ValidationError {
                                path: path.to_string(),
                                source_location: None,
                                value: Some(value.to_string()),
                                message: "value must be negative".to_string(),
                            })
                        }
                    }
                }
            )*
        };
    }

    impl_negative_for_signed!(i8, i16, i32, i64, i128, isize);
    impl_negative_for_float!(f32, f64);

    /// Validates that a numeric value is non-zero.
    #[derive(Debug, Clone, Copy)]
    pub struct NonZero;

    macro_rules! impl_nonzero_for_int {
        ($($t:ty),*) => {
            $(
                impl Validator<$t> for NonZero {
                    fn validate(&self, value: &$t, path: &str) -> ConfigValidation<()> {
                        if *value != 0 {
                            Validation::Success(())
                        } else {
                            fail(ConfigError::ValidationError {
                                path: path.to_string(),
                                source_location: None,
                                value: Some(value.to_string()),
                                message: "value cannot be zero".to_string(),
                            })
                        }
                    }
                }
            )*
        };
    }

    macro_rules! impl_nonzero_for_float {
        ($($t:ty),*) => {
            $(
                impl Validator<$t> for NonZero {
                    fn validate(&self, value: &$t, path: &str) -> ConfigValidation<()> {
                        #[allow(clippy::float_cmp)]
                        if *value != 0.0 {
                            Validation::Success(())
                        } else {
                            fail(ConfigError::ValidationError {
                                path: path.to_string(),
                                source_location: None,
                                value: Some(value.to_string()),
                                message: "value cannot be zero".to_string(),
                            })
                        }
                    }
                }
            )*
        };
    }

    impl_nonzero_for_int!(i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize);
    impl_nonzero_for_float!(f32, f64);

    // ========================================================================
    // Collection Validators
    // ========================================================================

    /// Validates that a collection is not empty.
    #[derive(Debug, Clone, Copy)]
    pub struct NonEmptyCollection;

    impl<T> Validator<Vec<T>> for NonEmptyCollection {
        fn validate(&self, value: &Vec<T>, path: &str) -> ConfigValidation<()> {
            if value.is_empty() {
                fail(ConfigError::ValidationError {
                    path: path.to_string(),
                    source_location: None,
                    value: Some("[]".to_string()),
                    message: "collection cannot be empty".to_string(),
                })
            } else {
                Validation::Success(())
            }
        }
    }

    impl<T> Validator<[T]> for NonEmptyCollection {
        fn validate(&self, value: &[T], path: &str) -> ConfigValidation<()> {
            if value.is_empty() {
                fail(ConfigError::ValidationError {
                    path: path.to_string(),
                    source_location: None,
                    value: Some("[]".to_string()),
                    message: "collection cannot be empty".to_string(),
                })
            } else {
                Validation::Success(())
            }
        }
    }

    /// Validates that a collection has at least the specified number of elements.
    #[derive(Debug, Clone, Copy)]
    pub struct MinItems(pub usize);

    impl<T> Validator<Vec<T>> for MinItems {
        fn validate(&self, value: &Vec<T>, path: &str) -> ConfigValidation<()> {
            if value.len() < self.0 {
                fail(ConfigError::ValidationError {
                    path: path.to_string(),
                    source_location: None,
                    value: Some(format!("[{} items]", value.len())),
                    message: format!(
                        "collection has {} items, minimum is {}",
                        value.len(),
                        self.0
                    ),
                })
            } else {
                Validation::Success(())
            }
        }
    }

    impl<T> Validator<[T]> for MinItems {
        fn validate(&self, value: &[T], path: &str) -> ConfigValidation<()> {
            if value.len() < self.0 {
                fail(ConfigError::ValidationError {
                    path: path.to_string(),
                    source_location: None,
                    value: Some(format!("[{} items]", value.len())),
                    message: format!(
                        "collection has {} items, minimum is {}",
                        value.len(),
                        self.0
                    ),
                })
            } else {
                Validation::Success(())
            }
        }
    }

    /// Validates that a collection has at most the specified number of elements.
    #[derive(Debug, Clone, Copy)]
    pub struct MaxItems(pub usize);

    impl<T> Validator<Vec<T>> for MaxItems {
        fn validate(&self, value: &Vec<T>, path: &str) -> ConfigValidation<()> {
            if value.len() > self.0 {
                fail(ConfigError::ValidationError {
                    path: path.to_string(),
                    source_location: None,
                    value: Some(format!("[{} items]", value.len())),
                    message: format!(
                        "collection has {} items, maximum is {}",
                        value.len(),
                        self.0
                    ),
                })
            } else {
                Validation::Success(())
            }
        }
    }

    impl<T> Validator<[T]> for MaxItems {
        fn validate(&self, value: &[T], path: &str) -> ConfigValidation<()> {
            if value.len() > self.0 {
                fail(ConfigError::ValidationError {
                    path: path.to_string(),
                    source_location: None,
                    value: Some(format!("[{} items]", value.len())),
                    message: format!(
                        "collection has {} items, maximum is {}",
                        value.len(),
                        self.0
                    ),
                })
            } else {
                Validation::Success(())
            }
        }
    }

    /// Validates each item in a collection using the given validator.
    ///
    /// Uses stillwater's traverse pattern to accumulate ALL errors across ALL items.
    #[derive(Debug, Clone)]
    pub struct Each<V>(pub V);

    impl<V, T> Validator<Vec<T>> for Each<V>
    where
        V: Validator<T>,
    {
        fn validate(&self, value: &Vec<T>, path: &str) -> ConfigValidation<()> {
            if value.is_empty() {
                return Validation::Success(());
            }

            let results: Vec<ConfigValidation<()>> = value
                .iter()
                .enumerate()
                .map(|(i, item)| self.0.validate(item, &format!("{}[{}]", path, i)))
                .collect();

            Validation::all_vec(results).map(|_| ())
        }
    }

    impl<V, T> Validator<[T]> for Each<V>
    where
        V: Validator<T>,
    {
        fn validate(&self, value: &[T], path: &str) -> ConfigValidation<()> {
            if value.is_empty() {
                return Validation::Success(());
            }

            let results: Vec<ConfigValidation<()>> = value
                .iter()
                .enumerate()
                .map(|(i, item)| self.0.validate(item, &format!("{}[{}]", path, i)))
                .collect();

            Validation::all_vec(results).map(|_| ())
        }
    }

    // ========================================================================
    // Path Validators
    // ========================================================================

    /// Validates that a path points to an existing file.
    ///
    /// **Note**: This performs I/O (filesystem check). For strict pure core /
    /// imperative shell separation, consider using stillwater's `Effect` type.
    /// Kept here for convenience in config validation at startup.
    #[derive(Debug, Clone, Copy)]
    pub struct FileExists;

    impl Validator<Path> for FileExists {
        fn validate(&self, value: &Path, path: &str) -> ConfigValidation<()> {
            if value.is_file() {
                Validation::Success(())
            } else {
                fail(ConfigError::ValidationError {
                    path: path.to_string(),
                    source_location: None,
                    value: Some(value.display().to_string()),
                    message: "file does not exist".to_string(),
                })
            }
        }
    }

    impl Validator<std::path::PathBuf> for FileExists {
        fn validate(&self, value: &std::path::PathBuf, path: &str) -> ConfigValidation<()> {
            <FileExists as Validator<Path>>::validate(self, value.as_path(), path)
        }
    }

    impl Validator<str> for FileExists {
        fn validate(&self, value: &str, path: &str) -> ConfigValidation<()> {
            <FileExists as Validator<Path>>::validate(self, Path::new(value), path)
        }
    }

    impl Validator<String> for FileExists {
        fn validate(&self, value: &String, path: &str) -> ConfigValidation<()> {
            <FileExists as Validator<str>>::validate(self, value.as_str(), path)
        }
    }

    /// Validates that a path points to an existing directory.
    ///
    /// **Note**: This performs I/O (filesystem check).
    #[derive(Debug, Clone, Copy)]
    pub struct DirExists;

    impl Validator<Path> for DirExists {
        fn validate(&self, value: &Path, path: &str) -> ConfigValidation<()> {
            if value.is_dir() {
                Validation::Success(())
            } else {
                fail(ConfigError::ValidationError {
                    path: path.to_string(),
                    source_location: None,
                    value: Some(value.display().to_string()),
                    message: "directory does not exist".to_string(),
                })
            }
        }
    }

    impl Validator<std::path::PathBuf> for DirExists {
        fn validate(&self, value: &std::path::PathBuf, path: &str) -> ConfigValidation<()> {
            <DirExists as Validator<Path>>::validate(self, value.as_path(), path)
        }
    }

    impl Validator<str> for DirExists {
        fn validate(&self, value: &str, path: &str) -> ConfigValidation<()> {
            <DirExists as Validator<Path>>::validate(self, Path::new(value), path)
        }
    }

    impl Validator<String> for DirExists {
        fn validate(&self, value: &String, path: &str) -> ConfigValidation<()> {
            <DirExists as Validator<str>>::validate(self, value.as_str(), path)
        }
    }

    /// Validates that a path's parent directory exists.
    ///
    /// Useful for validating output file paths before writing.
    ///
    /// **Note**: This performs I/O (filesystem check).
    #[derive(Debug, Clone, Copy)]
    pub struct ParentExists;

    impl Validator<Path> for ParentExists {
        fn validate(&self, value: &Path, path: &str) -> ConfigValidation<()> {
            match value.parent() {
                Some(parent) if parent.is_dir() || parent.as_os_str().is_empty() => {
                    Validation::Success(())
                }
                Some(_) => fail(ConfigError::ValidationError {
                    path: path.to_string(),
                    source_location: None,
                    value: Some(value.display().to_string()),
                    message: "parent directory does not exist".to_string(),
                }),
                None => fail(ConfigError::ValidationError {
                    path: path.to_string(),
                    source_location: None,
                    value: Some(value.display().to_string()),
                    message: "path has no parent directory".to_string(),
                }),
            }
        }
    }

    impl Validator<std::path::PathBuf> for ParentExists {
        fn validate(&self, value: &std::path::PathBuf, path: &str) -> ConfigValidation<()> {
            <ParentExists as Validator<Path>>::validate(self, value.as_path(), path)
        }
    }

    impl Validator<str> for ParentExists {
        fn validate(&self, value: &str, path: &str) -> ConfigValidation<()> {
            <ParentExists as Validator<Path>>::validate(self, Path::new(value), path)
        }
    }

    impl Validator<String> for ParentExists {
        fn validate(&self, value: &String, path: &str) -> ConfigValidation<()> {
            <ParentExists as Validator<str>>::validate(self, value.as_str(), path)
        }
    }

    /// Validates that a path has the specified file extension.
    #[derive(Debug, Clone)]
    pub struct Extension(pub String);

    impl Extension {
        /// Create a new extension validator.
        pub fn new(ext: impl Into<String>) -> Self {
            Self(ext.into())
        }
    }

    impl Validator<Path> for Extension {
        fn validate(&self, value: &Path, path: &str) -> ConfigValidation<()> {
            match value.extension() {
                Some(ext) if ext == self.0.as_str() => Validation::Success(()),
                Some(ext) => fail(ConfigError::ValidationError {
                    path: path.to_string(),
                    source_location: None,
                    value: Some(value.display().to_string()),
                    message: format!(
                        "expected extension '{}', found '{}'",
                        self.0,
                        ext.to_string_lossy()
                    ),
                }),
                None => fail(ConfigError::ValidationError {
                    path: path.to_string(),
                    source_location: None,
                    value: Some(value.display().to_string()),
                    message: format!("expected extension '{}', found none", self.0),
                }),
            }
        }
    }

    impl Validator<std::path::PathBuf> for Extension {
        fn validate(&self, value: &std::path::PathBuf, path: &str) -> ConfigValidation<()> {
            <Extension as Validator<Path>>::validate(self, value.as_path(), path)
        }
    }

    impl Validator<str> for Extension {
        fn validate(&self, value: &str, path: &str) -> ConfigValidation<()> {
            <Extension as Validator<Path>>::validate(self, Path::new(value), path)
        }
    }

    impl Validator<String> for Extension {
        fn validate(&self, value: &String, path: &str) -> ConfigValidation<()> {
            <Extension as Validator<str>>::validate(self, value.as_str(), path)
        }
    }
}

// ============================================================================
// Custom Validator Support
// ============================================================================

/// Create a custom validator from a pure function.
///
/// # Example
///
/// ```ignore
/// use premortem::validate::custom;
/// use premortem::{ConfigError, ConfigValidation};
/// use stillwater::Validation;
///
/// let even_validator = custom(|value: &i32, path: &str| {
///     if value % 2 == 0 {
///         Validation::Success(())
///     } else {
///         Validation::Failure(ConfigErrors::single(ConfigError::ValidationError {
///             path: path.to_string(),
///             source_location: None,
///             value: Some(value.to_string()),
///             message: "value must be even".to_string(),
///         }))
///     }
/// });
/// ```
pub fn custom<T, F>(f: F) -> impl Validator<T>
where
    F: Fn(&T, &str) -> ConfigValidation<()>,
{
    struct Custom<F>(F);

    impl<T, F> Validator<T> for Custom<F>
    where
        F: Fn(&T, &str) -> ConfigValidation<()>,
    {
        fn validate(&self, value: &T, path: &str) -> ConfigValidation<()> {
            (self.0)(value, path)
        }
    }

    Custom(f)
}

// ============================================================================
// Conditional Validation
// ============================================================================

/// Validator that only runs when a condition is true.
///
/// Useful for "when X is set, Y must be valid" patterns.
///
/// # Example
///
/// ```ignore
/// use premortem::validate::{When, validators::NonEmpty};
///
/// // Only validate host is non-empty when use_remote is true
/// let conditional = When::new(NonEmpty, || config.use_remote);
/// ```
pub struct When<V, F> {
    validator: V,
    condition: F,
}

impl<V, F> When<V, F> {
    /// Create a new conditional validator.
    pub fn new(validator: V, condition: F) -> Self {
        Self {
            validator,
            condition,
        }
    }
}

impl<V, F, T> Validator<T> for When<V, F>
where
    V: Validator<T>,
    F: Fn() -> bool,
    T: ?Sized,
{
    fn validate(&self, value: &T, path: &str) -> ConfigValidation<()> {
        if (self.condition)() {
            self.validator.validate(value, path)
        } else {
            Validation::Success(())
        }
    }
}

#[cfg(test)]
mod tests {
    use super::validators::*;
    use super::*;
    use std::path::{Path, PathBuf};

    // ========================================================================
    // Validate Trait Tests
    // ========================================================================

    #[test]
    fn test_unit_validate() {
        let result = ().validate();
        assert!(result.is_success());
    }

    #[test]
    fn test_option_validate_none() {
        let opt: Option<String> = None;
        let result = opt.validate();
        assert!(result.is_success());
    }

    #[test]
    fn test_option_validate_some() {
        let opt = Some("value".to_string());
        let result = opt.validate();
        assert!(result.is_success());
    }

    #[test]
    fn test_vec_validate_empty() {
        let v: Vec<String> = vec![];
        let result = v.validate();
        assert!(result.is_success());
    }

    #[test]
    fn test_vec_validate_with_items() {
        let v = vec!["a".to_string(), "b".to_string()];
        let result = v.validate();
        assert!(result.is_success());
    }

    #[test]
    fn test_primitive_validate() {
        assert!(42i32.validate().is_success());
        assert!((std::f64::consts::E).validate().is_success());
        assert!(true.validate().is_success());
        assert!("hello".to_string().validate().is_success());
    }

    #[test]
    fn test_pathbuf_validate() {
        let path = PathBuf::from("/some/path");
        assert!(path.validate().is_success());
    }

    // ========================================================================
    // validate_at Tests
    // ========================================================================

    struct FailingConfig;

    impl Validate for FailingConfig {
        fn validate(&self) -> ConfigValidation<()> {
            fail(ConfigError::ValidationError {
                path: "inner".to_string(),
                source_location: None,
                value: None,
                message: "always fails".to_string(),
            })
        }
    }

    #[test]
    fn test_validate_at_prefixes_path() {
        let config = FailingConfig;
        let result = config.validate_at("outer");
        assert!(result.is_failure());

        if let Validation::Failure(errors) = result {
            assert_eq!(errors.first().path(), Some("outer.inner"));
        }
    }

    // ========================================================================
    // String Validator Tests
    // ========================================================================

    #[test]
    fn test_non_empty_success() {
        let result = NonEmpty.validate("hello", "field");
        assert!(result.is_success());
    }

    #[test]
    fn test_non_empty_failure() {
        let result = NonEmpty.validate("", "field");
        assert!(result.is_failure());
    }

    #[test]
    fn test_min_length_success() {
        let result = MinLength(3).validate("hello", "field");
        assert!(result.is_success());
    }

    #[test]
    fn test_min_length_failure() {
        let result = MinLength(10).validate("hi", "field");
        assert!(result.is_failure());
    }

    #[test]
    fn test_max_length_success() {
        let result = MaxLength(10).validate("hello", "field");
        assert!(result.is_success());
    }

    #[test]
    fn test_max_length_failure() {
        let result = MaxLength(3).validate("hello", "field");
        assert!(result.is_failure());
    }

    #[test]
    fn test_length_success() {
        let result = Length(3..=10).validate("hello", "field");
        assert!(result.is_success());
    }

    #[test]
    fn test_length_failure_too_short() {
        let result = Length(5..=10).validate("hi", "field");
        assert!(result.is_failure());
    }

    #[test]
    fn test_length_failure_too_long() {
        let result = Length(1..=3).validate("hello", "field");
        assert!(result.is_failure());
    }

    #[test]
    fn test_pattern_success() {
        let result = Pattern::new(r"^\d+$").validate("12345", "field");
        assert!(result.is_success());
    }

    #[test]
    fn test_pattern_failure() {
        let result = Pattern::new(r"^\d+$").validate("abc", "field");
        assert!(result.is_failure());
    }

    #[test]
    fn test_email_success() {
        let result = Email.validate("user@example.com", "email");
        assert!(result.is_success());
    }

    #[test]
    fn test_email_failure() {
        let result = Email.validate("not-an-email", "email");
        assert!(result.is_failure());
    }

    #[test]
    fn test_url_success() {
        let result = Url.validate("https://example.com", "url");
        assert!(result.is_success());
    }

    #[test]
    fn test_url_failure() {
        let result = Url.validate("not-a-url", "url");
        assert!(result.is_failure());
    }

    // ========================================================================
    // Numeric Validator Tests
    // ========================================================================

    #[test]
    fn test_range_success() {
        let result = Range(1..=100).validate(&50i32, "field");
        assert!(result.is_success());
    }

    #[test]
    fn test_range_failure_below() {
        let result = Range(10..=100).validate(&5i32, "field");
        assert!(result.is_failure());
    }

    #[test]
    fn test_range_failure_above() {
        let result = Range(1..=10).validate(&50i32, "field");
        assert!(result.is_failure());
    }

    #[test]
    fn test_positive_success() {
        assert!(Positive.validate(&42i32, "field").is_success());
        assert!(Positive.validate(&1u32, "field").is_success());
        assert!(Positive.validate(&0.5f64, "field").is_success());
    }

    #[test]
    fn test_positive_failure() {
        assert!(Positive.validate(&-1i32, "field").is_failure());
        assert!(Positive.validate(&0i32, "field").is_failure());
        assert!(Positive.validate(&0u32, "field").is_failure());
        assert!(Positive.validate(&-0.5f64, "field").is_failure());
    }

    #[test]
    fn test_negative_success() {
        assert!(Negative.validate(&-42i32, "field").is_success());
        assert!(Negative.validate(&-0.5f64, "field").is_success());
    }

    #[test]
    fn test_negative_failure() {
        assert!(Negative.validate(&42i32, "field").is_failure());
        assert!(Negative.validate(&0i32, "field").is_failure());
        assert!(Negative.validate(&0.5f64, "field").is_failure());
    }

    #[test]
    fn test_non_zero_success() {
        assert!(NonZero.validate(&42i32, "field").is_success());
        assert!(NonZero.validate(&-1i32, "field").is_success());
        assert!(NonZero.validate(&1u32, "field").is_success());
        assert!(NonZero.validate(&0.5f64, "field").is_success());
    }

    #[test]
    fn test_non_zero_failure() {
        assert!(NonZero.validate(&0i32, "field").is_failure());
        assert!(NonZero.validate(&0u32, "field").is_failure());
        assert!(NonZero.validate(&0.0f64, "field").is_failure());
    }

    // ========================================================================
    // Collection Validator Tests
    // ========================================================================

    #[test]
    fn test_non_empty_collection_success() {
        let v = vec![1, 2, 3];
        let result = NonEmptyCollection.validate(&v, "items");
        assert!(result.is_success());
    }

    #[test]
    fn test_non_empty_collection_failure() {
        let v: Vec<i32> = vec![];
        let result = NonEmptyCollection.validate(&v, "items");
        assert!(result.is_failure());
    }

    #[test]
    fn test_min_items_success() {
        let v = vec![1, 2, 3];
        let result = MinItems(2).validate(&v, "items");
        assert!(result.is_success());
    }

    #[test]
    fn test_min_items_failure() {
        let v = vec![1];
        let result = MinItems(3).validate(&v, "items");
        assert!(result.is_failure());
    }

    #[test]
    fn test_max_items_success() {
        let v = vec![1, 2, 3];
        let result = MaxItems(5).validate(&v, "items");
        assert!(result.is_success());
    }

    #[test]
    fn test_max_items_failure() {
        let v = vec![1, 2, 3, 4, 5];
        let result = MaxItems(3).validate(&v, "items");
        assert!(result.is_failure());
    }

    #[test]
    fn test_each_success() {
        let v = vec![1, 2, 3];
        let result = Each(Positive).validate(&v, "items");
        assert!(result.is_success());
    }

    #[test]
    fn test_each_failure_accumulates_errors() {
        let v = vec![1, -2, -3, 4];
        let result = Each(Positive).validate(&v, "items");
        assert!(result.is_failure());

        if let Validation::Failure(errors) = result {
            // Should have 2 errors for -2 and -3
            assert_eq!(errors.len(), 2);
        }
    }

    #[test]
    fn test_each_empty_collection() {
        let v: Vec<i32> = vec![];
        let result = Each(Positive).validate(&v, "items");
        assert!(result.is_success());
    }

    // ========================================================================
    // Path Validator Tests
    // ========================================================================

    #[test]
    fn test_extension_success() {
        let result = Extension::new("toml").validate(Path::new("config.toml"), "file");
        assert!(result.is_success());
    }

    #[test]
    fn test_extension_failure_wrong() {
        let result = Extension::new("toml").validate(Path::new("config.json"), "file");
        assert!(result.is_failure());
    }

    #[test]
    fn test_extension_failure_none() {
        let result = Extension::new("toml").validate(Path::new("config"), "file");
        assert!(result.is_failure());
    }

    // ========================================================================
    // validate_field Tests
    // ========================================================================

    #[test]
    fn test_validate_field_empty_validators() {
        let empty: &[&dyn Validator<str>] = &[];
        let result = validate_field("value", "field", empty);
        assert!(result.is_success());
    }

    #[test]
    fn test_validate_field_single_validator() {
        let result = validate_field("hello", "field", &[&NonEmpty]);
        assert!(result.is_success());
    }

    #[test]
    fn test_validate_field_multiple_validators_all_pass() {
        let result = validate_field("hello", "field", &[&NonEmpty, &MinLength(3)]);
        assert!(result.is_success());
    }

    #[test]
    fn test_validate_field_accumulates_errors() {
        // Empty string fails both NonEmpty and MinLength
        let result = validate_field("", "field", &[&NonEmpty, &MinLength(3)]);
        assert!(result.is_failure());

        if let Validation::Failure(errors) = result {
            assert_eq!(errors.len(), 2);
        }
    }

    // ========================================================================
    // validate_nested Tests
    // ========================================================================

    struct InnerConfig {
        value: i32,
    }

    impl Validate for InnerConfig {
        fn validate(&self) -> ConfigValidation<()> {
            if self.value > 0 {
                Validation::Success(())
            } else {
                fail(ConfigError::ValidationError {
                    path: "value".to_string(),
                    source_location: None,
                    value: Some(self.value.to_string()),
                    message: "must be positive".to_string(),
                })
            }
        }
    }

    #[test]
    fn test_validate_nested_success() {
        let inner = InnerConfig { value: 42 };
        let result = validate_nested(&inner, "config");
        assert!(result.is_success());
    }

    #[test]
    fn test_validate_nested_failure() {
        let inner = InnerConfig { value: -1 };
        let result = validate_nested(&inner, "config");
        assert!(result.is_failure());

        if let Validation::Failure(errors) = result {
            assert_eq!(errors.first().path(), Some("config.value"));
        }
    }

    #[test]
    fn test_validate_optional_nested_none() {
        let opt: Option<InnerConfig> = None;
        let result = validate_optional_nested(&opt, "config");
        assert!(result.is_success());
    }

    #[test]
    fn test_validate_optional_nested_some() {
        let opt = Some(InnerConfig { value: -1 });
        let result = validate_optional_nested(&opt, "config");
        assert!(result.is_failure());
    }

    // ========================================================================
    // Custom Validator Tests
    // ========================================================================

    #[test]
    fn test_custom_validator() {
        let even_validator = custom(|value: &i32, path: &str| {
            if value % 2 == 0 {
                Validation::Success(())
            } else {
                fail(ConfigError::ValidationError {
                    path: path.to_string(),
                    source_location: None,
                    value: Some(value.to_string()),
                    message: "value must be even".to_string(),
                })
            }
        });

        assert!(even_validator.validate(&4, "num").is_success());
        assert!(even_validator.validate(&3, "num").is_failure());
    }

    // ========================================================================
    // Conditional Validator Tests
    // ========================================================================

    #[test]
    fn test_when_condition_true() {
        let validator = When::new(NonEmpty, || true);
        let result = validator.validate("", "field");
        assert!(result.is_failure());
    }

    #[test]
    fn test_when_condition_false() {
        let validator = When::new(NonEmpty, || false);
        let result = validator.validate("", "field");
        assert!(result.is_success());
    }

    // ========================================================================
    // Integration Tests
    // ========================================================================

    struct DatabaseConfig {
        host: String,
        port: u16,
        pool_size: u32,
    }

    impl Validate for DatabaseConfig {
        fn validate(&self) -> ConfigValidation<()> {
            let validations = vec![
                validate_field(&self.host, "host", &[&NonEmpty]),
                validate_field(&self.port, "port", &[&Range(1..=65535)]),
                validate_field(&self.pool_size, "pool_size", &[&Range(1..=100)]),
            ];
            Validation::all_vec(validations).map(|_| ())
        }
    }

    #[test]
    fn test_database_config_valid() {
        let config = DatabaseConfig {
            host: "localhost".to_string(),
            port: 5432,
            pool_size: 10,
        };
        assert!(config.validate().is_success());
    }

    #[test]
    fn test_database_config_accumulates_all_errors() {
        let config = DatabaseConfig {
            host: "".to_string(),
            port: 0,
            pool_size: 200,
        };

        let result = config.validate();
        assert!(result.is_failure());

        if let Validation::Failure(errors) = result {
            assert_eq!(errors.len(), 3);
        }
    }

    // Test Vec validation with custom type
    #[test]
    fn test_vec_custom_validate() {
        let configs = vec![
            InnerConfig { value: 1 },
            InnerConfig { value: -1 },
            InnerConfig { value: -2 },
        ];

        let result = configs.validate();
        assert!(result.is_failure());

        // Should have accumulated 2 errors with indexed paths
        if let Validation::Failure(errors) = result {
            assert_eq!(errors.len(), 2);
            let paths: Vec<_> = errors.iter().filter_map(|e| e.path()).collect();
            assert!(paths.contains(&"[1].value"));
            assert!(paths.contains(&"[2].value"));
        }
    }

    // ========================================================================
    // ValidationContext Tests
    // ========================================================================

    #[test]
    fn test_validation_context_lookup() {
        let mut locations = SourceLocationMap::new();
        locations.insert(
            "host".to_string(),
            SourceLocation::new("config.toml").with_line(5),
        );
        locations.insert(
            "port".to_string(),
            SourceLocation::new("config.toml").with_line(6),
        );

        let ctx = ValidationContext::new(locations);

        let host_loc = ctx.location_for("host").unwrap();
        assert_eq!(host_loc.source, "config.toml");
        assert_eq!(host_loc.line, Some(5));

        let port_loc = ctx.location_for("port").unwrap();
        assert_eq!(port_loc.line, Some(6));

        // Non-existent path returns None
        assert!(ctx.location_for("missing").is_none());
    }

    #[test]
    fn test_with_validation_context() {
        let mut locations = SourceLocationMap::new();
        locations.insert(
            "test_field".to_string(),
            SourceLocation::new("test.toml").with_line(10),
        );

        let ctx = ValidationContext::new(locations);

        // Before context is set, returns None
        assert!(current_source_location("test_field").is_none());

        // Within context, returns location
        let result = with_validation_context(ctx, || {
            let loc = current_source_location("test_field");
            assert!(loc.is_some());
            let loc = loc.unwrap();
            assert_eq!(loc.source, "test.toml");
            assert_eq!(loc.line, Some(10));
            "success"
        });

        assert_eq!(result, "success");

        // After context is cleared, returns None again
        assert!(current_source_location("test_field").is_none());
    }

    #[test]
    fn test_context_clears_on_completion() {
        let mut locations = SourceLocationMap::new();
        locations.insert("field".to_string(), SourceLocation::new("a.toml"));

        let ctx = ValidationContext::new(locations);
        with_validation_context(ctx, || ());

        // Context should be cleared
        assert!(current_source_location("field").is_none());
    }

    #[test]
    fn test_path_prefix_for_nested_lookup() {
        let mut locations = SourceLocationMap::new();
        locations.insert(
            "server.host".to_string(),
            SourceLocation::new("config.toml").with_line(3),
        );
        locations.insert(
            "server.port".to_string(),
            SourceLocation::new("config.toml").with_line(4),
        );
        locations.insert(
            "database.host".to_string(),
            SourceLocation::new("config.toml").with_line(7),
        );

        let ctx = ValidationContext::new(locations);

        with_validation_context(ctx, || {
            // Without prefix, "host" doesn't find anything
            assert!(current_source_location("host").is_none());

            // With "server" prefix, "host" finds "server.host"
            push_path_prefix("server");
            let loc = current_source_location("host");
            assert!(loc.is_some());
            let loc = loc.unwrap();
            assert_eq!(loc.source, "config.toml");
            assert_eq!(loc.line, Some(3));

            // port also works with prefix
            let port_loc = current_source_location("port").unwrap();
            assert_eq!(port_loc.line, Some(4));

            pop_path_prefix();

            // After popping, "host" doesn't find anything again
            assert!(current_source_location("host").is_none());

            // With "database" prefix
            push_path_prefix("database");
            let db_loc = current_source_location("host").unwrap();
            assert_eq!(db_loc.line, Some(7));
            pop_path_prefix();
        });
    }

    #[test]
    fn test_nested_path_prefix_stacking() {
        let mut locations = SourceLocationMap::new();
        locations.insert(
            "outer.inner.field".to_string(),
            SourceLocation::new("config.toml").with_line(10),
        );

        let ctx = ValidationContext::new(locations);

        with_validation_context(ctx, || {
            // No prefix - not found
            assert!(current_source_location("field").is_none());

            // Single prefix - still not found
            push_path_prefix("outer");
            assert!(current_source_location("field").is_none());

            // Nested prefix - found
            push_path_prefix("inner");
            let loc = current_source_location("field");
            assert!(loc.is_some());
            assert_eq!(loc.unwrap().line, Some(10));

            // Pop inner prefix
            pop_path_prefix();
            assert!(current_source_location("field").is_none());

            // Pop outer prefix
            pop_path_prefix();
        });
    }

    // ========================================================================
    // Predicate Bridge Tests (stillwater 0.13.0+)
    // ========================================================================

    use stillwater::predicate::prelude::*;

    #[test]
    fn test_from_predicate_success() {
        let validator = from_predicate(not_empty());
        let result = validator.validate("hello", "field");
        assert!(result.is_success());
    }

    #[test]
    fn test_from_predicate_failure() {
        let validator = from_predicate(not_empty());
        let result = validator.validate("", "field");
        assert!(result.is_failure());

        if let Validation::Failure(errors) = result {
            assert_eq!(errors.len(), 1);
            assert_eq!(errors.first().path(), Some("field"));
        }
    }

    #[test]
    fn test_validate_with_predicate_success() {
        let result = validate_with_predicate(
            &42,
            "port",
            between(1, 65535),
            "port must be between 1 and 65535",
        );
        assert!(result.is_success());
    }

    #[test]
    fn test_validate_with_predicate_failure() {
        let result = validate_with_predicate(
            &0,
            "port",
            between(1, 65535),
            "port must be between 1 and 65535",
        );
        assert!(result.is_failure());

        if let Validation::Failure(errors) = result {
            assert_eq!(errors.len(), 1);
            assert_eq!(errors.first().path(), Some("port"));
            // Check that custom message is used
            if let ConfigError::ValidationError { message, .. } = errors.first() {
                assert_eq!(message, "port must be between 1 and 65535");
            } else {
                panic!("Expected ValidationError");
            }
        }
    }

    #[test]
    fn test_validate_with_predicate_custom_message() {
        let result = validate_with_predicate("", "username", not_empty(), "username is required");

        assert!(result.is_failure());

        if let Validation::Failure(errors) = result {
            if let ConfigError::ValidationError { message, .. } = errors.first() {
                assert_eq!(message, "username is required");
            } else {
                panic!("Expected ValidationError");
            }
        }
    }

    #[test]
    fn test_predicate_preserves_source_location() {
        let mut locations = SourceLocationMap::new();
        locations.insert(
            "host".to_string(),
            SourceLocation::new("config.toml").with_line(5),
        );

        let ctx = ValidationContext::new(locations);

        with_validation_context(ctx, || {
            let result = validate_with_predicate("", "host", not_empty(), "host cannot be empty");

            assert!(result.is_failure());

            if let Validation::Failure(errors) = result {
                let err = errors.first();
                assert_eq!(
                    err.source_location().map(|l| l.source.as_str()),
                    Some("config.toml")
                );
                assert_eq!(err.source_location().and_then(|l| l.line), Some(5));
            }
        });
    }

    #[test]
    fn test_predicate_with_nested_validation() {
        let mut locations = SourceLocationMap::new();
        locations.insert(
            "database.host".to_string(),
            SourceLocation::new("config.toml").with_line(10),
        );

        let ctx = ValidationContext::new(locations);

        with_validation_context(ctx, || {
            push_path_prefix("database");
            let result = validate_with_predicate("", "host", not_empty(), "host required");
            pop_path_prefix();

            assert!(result.is_failure());

            if let Validation::Failure(errors) = result {
                let err = errors.first();
                assert_eq!(err.source_location().and_then(|l| l.line), Some(10));
            }
        });
    }

    #[test]
    fn test_complex_string_predicate() {
        // Valid username: non-empty and at least 3 chars
        assert!(validate_with_predicate(
            "user123",
            "username",
            len_min(3),
            "must be at least 3 chars"
        )
        .is_success());

        // Too short
        assert!(
            validate_with_predicate("ab", "username", len_min(3), "must be at least 3 chars")
                .is_failure()
        );

        // Test length range
        assert!(validate_with_predicate(
            "hello",
            "field",
            len_between(3, 10),
            "length must be 3-10 chars"
        )
        .is_success());
        assert!(validate_with_predicate(
            "hi",
            "field",
            len_between(3, 10),
            "length must be 3-10 chars"
        )
        .is_failure());
    }

    #[test]
    fn test_numeric_range_predicate() {
        let pred = gt(0).and(le(65535));
        let validator = from_predicate(pred);

        // Valid ports
        assert!(validator.validate(&1, "port").is_success());
        assert!(validator.validate(&8080, "port").is_success());
        assert!(validator.validate(&65535, "port").is_success());

        // Invalid ports
        assert!(validator.validate(&0, "port").is_failure());
        assert!(validator.validate(&65536, "port").is_failure());
        assert!(validator.validate(&-1, "port").is_failure());
    }

    #[test]
    fn test_string_length_predicates() {
        // Length minimum
        assert!(validate_with_predicate("hello", "field", len_min(3), "min 3 chars").is_success());
        assert!(validate_with_predicate("hi", "field", len_min(3), "min 3 chars").is_failure());

        // Length maximum
        assert!(
            validate_with_predicate("hello", "field", len_max(10), "max 10 chars").is_success()
        );
        assert!(
            validate_with_predicate("verylongstring", "field", len_max(10), "max 10 chars")
                .is_failure()
        );

        // Exact length
        assert!(
            validate_with_predicate("hello", "field", len_eq(5), "exactly 5 chars").is_success()
        );
        assert!(validate_with_predicate("hi", "field", len_eq(5), "exactly 5 chars").is_failure());
    }

    #[test]
    fn test_predicate_and_validator_together() {
        // Mix predicate-based and traditional validators
        let pred_validator = from_predicate(len_min(3));
        let trad_validator = NonEmpty;

        let result = validate_field("hello", "field", &[&trad_validator, &pred_validator]);
        assert!(result.is_success());

        // Fails traditional validator
        let result = validate_field("", "field", &[&trad_validator, &pred_validator]);
        assert!(result.is_failure());

        // Fails predicate validator
        let result = validate_field("hi", "field", &[&trad_validator, &pred_validator]);
        assert!(result.is_failure());
    }

    #[test]
    fn test_validate_field_with_predicate() {
        let validator = from_predicate(between(1, 100));

        // Valid value
        let result = validate_field(&50, "value", &[&validator]);
        assert!(result.is_success());

        // Invalid value
        let result = validate_field(&150, "value", &[&validator]);
        assert!(result.is_failure());
    }
}