yaml-edit 0.2.1

A lossless parser and editor for YAML files
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
//! YAML Schema validation support
//!
//! This module provides schema validation for YAML documents, supporting
//! the standard YAML schemas: Failsafe, JSON, and Core.

use crate::scalar::{ScalarType, ScalarValue};
use crate::yaml::{Document, Mapping, Scalar, Sequence, TaggedNode};

/// Specific type of validation error that occurred
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ValidationErrorKind {
    /// A scalar type is not allowed in the current schema
    TypeNotAllowed {
        /// The scalar type that was found
        found_type: ScalarType,
        /// The types that are allowed in this schema
        allowed_types: Vec<ScalarType>,
    },
    /// Custom validation constraint failed
    CustomConstraintFailed {
        /// The constraint that failed
        constraint_name: String,
        /// The actual value that failed validation
        actual_value: String,
    },
    /// Type coercion failed
    CoercionFailed {
        /// The type that was found
        from_type: ScalarType,
        /// The types that coercion was attempted to
        to_types: Vec<ScalarType>,
    },
}

/// Error that occurs during schema validation
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ValidationError {
    /// The specific kind of validation error
    pub kind: ValidationErrorKind,
    /// Path to the node that failed validation (e.g., "root.items\[0\].name")
    pub path: String,
    /// Name of the schema that was being validated against
    pub schema_name: String,
}

impl ValidationError {
    /// Create a new type not allowed error
    pub fn type_not_allowed(
        path: impl Into<String>,
        schema_name: impl Into<String>,
        found_type: ScalarType,
        allowed_types: Vec<ScalarType>,
    ) -> Self {
        Self {
            kind: ValidationErrorKind::TypeNotAllowed {
                found_type,
                allowed_types,
            },
            path: path.into(),
            schema_name: schema_name.into(),
        }
    }

    /// Create a new custom constraint failed error
    pub fn custom_constraint_failed(
        path: impl Into<String>,
        schema_name: impl Into<String>,
        constraint_name: impl Into<String>,
        actual_value: impl Into<String>,
    ) -> Self {
        Self {
            kind: ValidationErrorKind::CustomConstraintFailed {
                constraint_name: constraint_name.into(),
                actual_value: actual_value.into(),
            },
            path: path.into(),
            schema_name: schema_name.into(),
        }
    }

    /// Create a new coercion failed error
    pub fn coercion_failed(
        path: impl Into<String>,
        schema_name: impl Into<String>,
        from_type: ScalarType,
        to_types: Vec<ScalarType>,
    ) -> Self {
        Self {
            kind: ValidationErrorKind::CoercionFailed {
                from_type,
                to_types,
            },
            path: path.into(),
            schema_name: schema_name.into(),
        }
    }

    /// Get a human-readable error message
    pub fn message(&self) -> String {
        match &self.kind {
            ValidationErrorKind::TypeNotAllowed {
                found_type,
                allowed_types,
            } => {
                format!(
                    "type {:?} not allowed in {} schema, expected one of {:?}",
                    found_type, self.schema_name, allowed_types
                )
            }
            ValidationErrorKind::CustomConstraintFailed {
                constraint_name,
                actual_value,
            } => {
                format!(
                    "custom constraint '{}' failed for value '{}'",
                    constraint_name, actual_value
                )
            }
            ValidationErrorKind::CoercionFailed {
                from_type,
                to_types,
            } => {
                format!(
                    "cannot coerce {:?} to any of {:?} in {} schema",
                    from_type, to_types, self.schema_name
                )
            }
        }
    }
}

impl std::fmt::Display for ValidationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Validation error at {}: {}", self.path, self.message())
    }
}

impl std::error::Error for ValidationError {}

/// Result type for schema validation operations
pub type ValidationResult<T> = Result<T, Vec<ValidationError>>;

/// Result of a custom validation function
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CustomValidationResult {
    /// Validation passed
    Valid,
    /// Validation failed with a specific constraint name and reason
    Invalid {
        /// Name of the constraint that failed (e.g., "email_format", "port_range")
        constraint: String,
        /// Human-readable reason for failure
        reason: String,
    },
}

impl CustomValidationResult {
    /// Create a validation failure
    pub fn invalid(constraint: impl Into<String>, reason: impl Into<String>) -> Self {
        Self::Invalid {
            constraint: constraint.into(),
            reason: reason.into(),
        }
    }

    /// Check if validation passed
    pub fn is_valid(&self) -> bool {
        matches!(self, Self::Valid)
    }

    /// Check if validation failed
    pub fn is_invalid(&self) -> bool {
        matches!(self, Self::Invalid { .. })
    }
}

/// Custom validation function for scalar values
///
/// Takes (value, path) and returns CustomValidationResult
pub type CustomValidator = Box<dyn Fn(&str, &str) -> CustomValidationResult + Send + Sync>;

/// Custom schema definition with user-defined validation rules
pub struct CustomSchema {
    /// Schema name for error messages
    pub name: String,
    /// Allowed scalar types in this schema
    pub allowed_types: Vec<ScalarType>,
    /// Custom validation functions by type
    pub custom_validators: std::collections::HashMap<ScalarType, CustomValidator>,
    /// Whether to allow type coercion
    pub allow_coercion: bool,
}

impl std::fmt::Debug for CustomSchema {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CustomSchema")
            .field("name", &self.name)
            .field("allowed_types", &self.allowed_types)
            .field("allow_coercion", &self.allow_coercion)
            .field(
                "validators",
                &format!("<{} validators>", self.custom_validators.len()),
            )
            .finish()
    }
}

impl CustomSchema {
    /// Create a new custom schema
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            allowed_types: Vec::new(),
            custom_validators: std::collections::HashMap::new(),
            allow_coercion: true,
        }
    }

    /// Allow a specific scalar type
    pub fn allow_type(mut self, scalar_type: ScalarType) -> Self {
        if !self.allowed_types.contains(&scalar_type) {
            self.allowed_types.push(scalar_type);
        }
        self
    }

    /// Allow multiple scalar types
    pub fn allow_types(mut self, types: &[ScalarType]) -> Self {
        for &scalar_type in types {
            if !self.allowed_types.contains(&scalar_type) {
                self.allowed_types.push(scalar_type);
            }
        }
        self
    }

    /// Add a custom validator for a specific type
    pub fn with_validator<F>(mut self, scalar_type: ScalarType, validator: F) -> Self
    where
        F: Fn(&str, &str) -> CustomValidationResult + Send + Sync + 'static,
    {
        self.custom_validators
            .insert(scalar_type, Box::new(validator));
        self
    }

    /// Disable type coercion for strict validation
    pub fn strict(mut self) -> Self {
        self.allow_coercion = false;
        self
    }

    /// Check if a scalar type is allowed
    pub fn allows_type(&self, scalar_type: ScalarType) -> bool {
        self.allowed_types.contains(&scalar_type)
    }

    /// Validate a scalar value with custom rules
    pub fn validate_scalar(&self, content: &str, path: &str) -> Result<(), ValidationError> {
        let scalar_value = ScalarValue::parse(content.trim());
        let scalar_type = scalar_value.scalar_type();

        // Check if type is allowed
        if !self.allows_type(scalar_type) {
            if self.allow_coercion {
                // Try coercion to allowed types
                let mut coerced = false;
                for &allowed_type in &self.allowed_types {
                    if scalar_value.coerce_to_type(allowed_type).is_some() {
                        coerced = true;
                        break;
                    }
                }
                if !coerced {
                    return Err(ValidationError::coercion_failed(
                        path,
                        &self.name,
                        scalar_type,
                        self.allowed_types.clone(),
                    ));
                }
            } else {
                return Err(ValidationError::type_not_allowed(
                    path,
                    &self.name,
                    scalar_type,
                    self.allowed_types.clone(),
                ));
            }
        }

        // Run custom validator if present
        if let Some(validator) = self.custom_validators.get(&scalar_type) {
            let result = validator(content.trim(), path);
            if let CustomValidationResult::Invalid { constraint, reason } = result {
                return Err(ValidationError::custom_constraint_failed(
                    path,
                    &self.name,
                    format!("{}: {}", constraint, reason),
                    content.trim(),
                ));
            }
        }

        Ok(())
    }
}

/// YAML Schema types as defined in YAML 1.2 specification
#[derive(Debug)]
pub enum Schema {
    /// Failsafe schema - only strings, sequences, and mappings
    Failsafe,
    /// JSON schema - JSON-compatible types only
    Json,
    /// Core schema - full YAML 1.2 type system
    Core,
    /// User-defined custom schema
    Custom(CustomSchema),
}

impl PartialEq for Schema {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Schema::Failsafe, Schema::Failsafe) => true,
            (Schema::Json, Schema::Json) => true,
            (Schema::Core, Schema::Core) => true,
            (Schema::Custom(a), Schema::Custom(b)) => a.name == b.name,
            _ => false,
        }
    }
}

impl Schema {
    /// Get the name of this schema
    pub fn name(&self) -> &str {
        match self {
            Schema::Failsafe => "failsafe",
            Schema::Json => "json",
            Schema::Core => "core",
            Schema::Custom(custom) => &custom.name,
        }
    }

    /// Check if a scalar type is allowed in this schema
    pub fn allows_scalar_type(&self, scalar_type: ScalarType) -> bool {
        match self {
            Schema::Failsafe => matches!(scalar_type, ScalarType::String),
            Schema::Json => matches!(
                scalar_type,
                ScalarType::String
                    | ScalarType::Integer
                    | ScalarType::Float
                    | ScalarType::Boolean
                    | ScalarType::Null
            ),
            Schema::Core => true, // Core schema allows all types
            Schema::Custom(custom) => custom.allows_type(scalar_type),
        }
    }

    /// Get the allowed scalar types for this schema
    pub fn allowed_scalar_types(&self) -> Vec<ScalarType> {
        match self {
            Schema::Failsafe => vec![ScalarType::String],
            Schema::Json => vec![
                ScalarType::String,
                ScalarType::Integer,
                ScalarType::Float,
                ScalarType::Boolean,
                ScalarType::Null,
            ],
            Schema::Core => vec![
                ScalarType::String,
                ScalarType::Integer,
                ScalarType::Float,
                ScalarType::Boolean,
                ScalarType::Null,
                #[cfg(feature = "base64")]
                ScalarType::Binary,
                ScalarType::Timestamp,
                ScalarType::Regex,
            ],
            Schema::Custom(custom) => custom.allowed_types.clone(),
        }
    }
}

/// Schema validator for YAML documents
#[derive(Debug)]
pub struct SchemaValidator {
    schema: Schema,
    strict: bool,
}

impl SchemaValidator {
    /// Create a new schema validator
    pub fn new(schema: Schema) -> Self {
        Self {
            schema,
            strict: false,
        }
    }

    /// Create a failsafe schema validator
    pub fn failsafe() -> Self {
        Self::new(Schema::Failsafe)
    }

    /// Create a JSON schema validator  
    pub fn json() -> Self {
        Self::new(Schema::Json)
    }

    /// Create a core schema validator
    pub fn core() -> Self {
        Self::new(Schema::Core)
    }

    /// Create a validator for a custom schema
    pub fn custom(schema: CustomSchema) -> Self {
        Self::new(Schema::Custom(schema))
    }

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

    /// Get the schema type
    pub fn schema(&self) -> &Schema {
        &self.schema
    }

    /// Validate a YAML document against the schema
    pub fn validate(&self, document: &Document) -> ValidationResult<()> {
        let mut errors = Vec::new();
        self.validate_document(document, "root", &mut errors);

        if errors.is_empty() {
            Ok(())
        } else {
            Err(errors)
        }
    }

    /// Validate a document node
    fn validate_document(
        &self,
        document: &Document,
        path: &str,
        errors: &mut Vec<ValidationError>,
    ) {
        if let Some(scalar) = document.as_scalar() {
            self.validate_scalar(&scalar, path, errors);
        } else if let Some(sequence) = document.as_sequence() {
            self.validate_sequence(&sequence, path, errors);
        } else if let Some(mapping) = document.as_mapping() {
            self.validate_mapping(&mapping, path, errors);
        }
        // If none match, it might be empty or null - that's generally allowed
    }

    /// Validate a scalar value
    fn validate_scalar(&self, scalar: &Scalar, path: &str, errors: &mut Vec<ValidationError>) {
        let content = scalar.as_string();

        // Handle custom schema validation differently
        if let Schema::Custom(custom_schema) = &self.schema {
            if let Err(error) = custom_schema.validate_scalar(&content, path) {
                errors.push(error);
            }
            return;
        }

        // Standard schema validation
        let scalar_value = ScalarValue::parse(content.trim());
        let scalar_type = scalar_value.scalar_type();

        if !self.schema.allows_scalar_type(scalar_type) {
            // Try type coercion if not in strict mode
            if !self.strict {
                let allowed_types = self.schema.allowed_scalar_types();
                let mut coercion_successful = false;

                for allowed_type in allowed_types {
                    if scalar_value.coerce_to_type(allowed_type).is_some() {
                        coercion_successful = true;
                        break;
                    }
                }

                if !coercion_successful {
                    errors.push(ValidationError::coercion_failed(
                        path,
                        self.schema.name(),
                        scalar_type,
                        self.schema.allowed_scalar_types(),
                    ));
                }
            } else {
                errors.push(ValidationError::type_not_allowed(
                    path,
                    self.schema.name(),
                    scalar_type,
                    self.schema.allowed_scalar_types(),
                ));
            }
        }
    }

    /// Validate a sequence
    fn validate_sequence(&self, seq: &Sequence, path: &str, errors: &mut Vec<ValidationError>) {
        for (i, item) in seq.items().enumerate() {
            let item_path = format!("{}[{}]", path, i);
            self.validate_node(&item, &item_path, errors);
        }
    }

    /// Validate a mapping  
    fn validate_mapping(&self, map: &Mapping, path: &str, errors: &mut Vec<ValidationError>) {
        for (key_node, value_node) in map.pairs() {
            // Get the key name; KEY node wraps the actual content
            let key_name = key_node.text().to_string().trim().to_string();

            // Keys in YAML are typically strings and don't need schema validation
            // The schema applies to the values, not the keys
            let value_path = format!("{}.{}", path, key_name);
            self.validate_node(&value_node, &value_path, errors);
        }
    }

    /// Validate a syntax node (could be scalar, sequence, or mapping)
    fn validate_node(
        &self,
        node: &rowan::SyntaxNode<crate::yaml::Lang>,
        path: &str,
        errors: &mut Vec<ValidationError>,
    ) {
        use crate::yaml::{extract_mapping, extract_scalar, extract_sequence, extract_tagged_node};

        // Use smart extraction to handle wrapper nodes automatically
        if let Some(scalar) = extract_scalar(node) {
            self.validate_scalar(&scalar, path, errors);
        } else if let Some(tagged_node) = extract_tagged_node(node) {
            self.validate_tagged_node(&tagged_node, path, errors);
        } else if let Some(sequence) = extract_sequence(node) {
            self.validate_sequence(&sequence, path, errors);
        } else if let Some(mapping) = extract_mapping(node) {
            self.validate_mapping(&mapping, path, errors);
        }
        // If none match, it might be a different node type - skip validation
    }

    /// Validate a tagged scalar value (e.g., !!timestamp, !!regex)
    fn validate_tagged_node(
        &self,
        tagged_node: &TaggedNode,
        path: &str,
        errors: &mut Vec<ValidationError>,
    ) {
        // Handle custom schema validation
        if let Schema::Custom(custom_schema) = &self.schema {
            let content = tagged_node.to_string();
            if let Err(error) = custom_schema.validate_scalar(&content, path) {
                errors.push(error);
            }
            return;
        }

        // Standard tagged scalar validation
        let scalar_type = self.get_tagged_node_type(tagged_node);

        if !self.schema.allows_scalar_type(scalar_type) {
            // For tagged scalars, we can't coerce them to other types since they have explicit type information
            errors.push(ValidationError::type_not_allowed(
                path,
                self.schema.name(),
                scalar_type,
                self.schema.allowed_scalar_types(),
            ));
        }
    }

    /// Determine the scalar type from a tagged scalar
    fn get_tagged_node_type(&self, tagged_node: &TaggedNode) -> ScalarType {
        match tagged_node.tag().as_deref() {
            Some("!!timestamp") => ScalarType::Timestamp,
            Some("!!regex") => ScalarType::Regex,
            Some("!!binary") => {
                #[cfg(feature = "base64")]
                return ScalarType::Binary;
                #[cfg(not(feature = "base64"))]
                return ScalarType::String;
            }
            _ => ScalarType::String,
        }
    }

    /// Check if a document can be coerced to match the schema
    pub fn can_coerce(&self, document: &Document) -> ValidationResult<()> {
        if self.strict {
            return self.validate(document);
        }

        let mut errors = Vec::new();
        self.check_coercion(document, "root", &mut errors);

        if errors.is_empty() {
            Ok(())
        } else {
            Err(errors)
        }
    }

    /// Check if a document can be coerced to match the schema
    fn check_coercion(&self, document: &Document, path: &str, errors: &mut Vec<ValidationError>) {
        if let Some(scalar) = document.as_scalar() {
            let scalar_value = ScalarValue::parse(scalar.as_string().trim());
            let scalar_type = scalar_value.scalar_type();

            if !self.schema.allows_scalar_type(scalar_type) {
                // Try to coerce to an allowed type
                let allowed_types = self.schema.allowed_scalar_types();
                let mut coerced = false;

                for allowed_type in allowed_types {
                    if scalar_value.coerce_to_type(allowed_type).is_some() {
                        coerced = true;
                        break;
                    }
                }

                if !coerced {
                    errors.push(ValidationError::coercion_failed(
                        path,
                        self.schema.name(),
                        scalar_type,
                        self.schema.allowed_scalar_types(),
                    ));
                }
            }
        } else if let Some(sequence) = document.as_sequence() {
            // Recursively check sequence items for coercion
            for (i, item) in sequence.items().enumerate() {
                let item_path = format!("{}[{}]", path, i);
                self.check_coercion_node(&item, &item_path, errors);
            }
        } else if let Some(mapping) = document.as_mapping() {
            // Recursively check mapping key-value pairs for coercion
            for (key_node, value_node) in mapping.pairs() {
                let key_name = key_node.text().to_string().trim().to_string();
                let value_path = format!("{}.{}", path, key_name);
                self.check_coercion_node(&value_node, &value_path, errors);
            }
        }
    }

    /// Check coercion for a generic syntax node
    fn check_coercion_node(
        &self,
        node: &rowan::SyntaxNode<crate::yaml::Lang>,
        path: &str,
        errors: &mut Vec<ValidationError>,
    ) {
        use crate::yaml::{extract_mapping, extract_scalar, extract_sequence, extract_tagged_node};

        // Use smart extraction to handle wrapper nodes automatically
        if let Some(scalar) = extract_scalar(node) {
            let scalar_value = ScalarValue::parse(scalar.as_string().trim());
            let scalar_type = scalar_value.scalar_type();

            if !self.schema.allows_scalar_type(scalar_type) {
                let allowed_types = self.schema.allowed_scalar_types();
                let mut coerced = false;

                for allowed_type in allowed_types {
                    if scalar_value.coerce_to_type(allowed_type).is_some() {
                        coerced = true;
                        break;
                    }
                }

                if !coerced {
                    errors.push(ValidationError::coercion_failed(
                        path,
                        self.schema.name(),
                        scalar_type,
                        self.schema.allowed_scalar_types(),
                    ));
                }
            }
        } else if let Some(tagged_node) = extract_tagged_node(node) {
            let scalar_type = self.get_tagged_node_type(&tagged_node);

            if !self.schema.allows_scalar_type(scalar_type) {
                // Tagged scalars generally can't be coerced since they have explicit type info
                errors.push(ValidationError::type_not_allowed(
                    path,
                    self.schema.name(),
                    scalar_type,
                    self.schema.allowed_scalar_types(),
                ));
            }
        } else if let Some(sequence) = extract_sequence(node) {
            for (i, item) in sequence.items().enumerate() {
                let item_path = format!("{}[{}]", path, i);
                self.check_coercion_node(&item, &item_path, errors);
            }
        } else if let Some(mapping) = extract_mapping(node) {
            for (key_node, value_node) in mapping.pairs() {
                let key_name = key_node.text().to_string().trim().to_string();
                let value_path = format!("{}.{}", path, key_name);
                self.check_coercion_node(&value_node, &value_path, errors);
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::yaml::Document;
    use rowan::ast::AstNode;

    #[test]
    fn test_schema_names() {
        assert_eq!(Schema::Failsafe.name(), "failsafe");
        assert_eq!(Schema::Json.name(), "json");
        assert_eq!(Schema::Core.name(), "core");
    }

    #[test]
    fn test_failsafe_schema_allows_only_strings() {
        let schema = Schema::Failsafe;

        assert!(schema.allows_scalar_type(ScalarType::String));
        assert!(!schema.allows_scalar_type(ScalarType::Integer));
        assert!(!schema.allows_scalar_type(ScalarType::Float));
        assert!(!schema.allows_scalar_type(ScalarType::Boolean));
        assert!(!schema.allows_scalar_type(ScalarType::Null));
        #[cfg(feature = "base64")]
        assert!(!schema.allows_scalar_type(ScalarType::Binary));
        assert!(!schema.allows_scalar_type(ScalarType::Timestamp));
        assert!(!schema.allows_scalar_type(ScalarType::Regex));
    }

    #[test]
    fn test_json_schema_allows_json_types() {
        let schema = Schema::Json;

        assert!(schema.allows_scalar_type(ScalarType::String));
        assert!(schema.allows_scalar_type(ScalarType::Integer));
        assert!(schema.allows_scalar_type(ScalarType::Float));
        assert!(schema.allows_scalar_type(ScalarType::Boolean));
        assert!(schema.allows_scalar_type(ScalarType::Null));
        #[cfg(feature = "base64")]
        assert!(!schema.allows_scalar_type(ScalarType::Binary));
        assert!(!schema.allows_scalar_type(ScalarType::Timestamp));
        assert!(!schema.allows_scalar_type(ScalarType::Regex));
    }

    #[test]
    fn test_core_schema_allows_all_types() {
        let schema = Schema::Core;

        assert!(schema.allows_scalar_type(ScalarType::String));
        assert!(schema.allows_scalar_type(ScalarType::Integer));
        assert!(schema.allows_scalar_type(ScalarType::Float));
        assert!(schema.allows_scalar_type(ScalarType::Boolean));
        assert!(schema.allows_scalar_type(ScalarType::Null));
        #[cfg(feature = "base64")]
        assert!(schema.allows_scalar_type(ScalarType::Binary));
        assert!(schema.allows_scalar_type(ScalarType::Timestamp));
        assert!(schema.allows_scalar_type(ScalarType::Regex));
    }

    #[test]
    fn test_validator_creation() {
        let failsafe = SchemaValidator::failsafe();
        assert_eq!(*failsafe.schema(), Schema::Failsafe);
        assert!(!failsafe.strict);

        let json = SchemaValidator::json();
        assert_eq!(*json.schema(), Schema::Json);

        let core = SchemaValidator::core();
        assert_eq!(*core.schema(), Schema::Core);

        let strict_validator = SchemaValidator::json().strict();
        assert!(strict_validator.strict);
    }

    #[test]
    fn test_validation_error_display() {
        let error = ValidationError::type_not_allowed(
            "root.items[0]",
            "test-schema",
            ScalarType::Integer,
            vec![ScalarType::String],
        );

        assert_eq!(
            format!("{}", error),
            "Validation error at root.items[0]: type Integer not allowed in test-schema schema, expected one of [String]"
        );
    }

    fn create_test_document(content: &str) -> Document {
        use crate::yaml::YamlFile;
        let parsed = content
            .parse::<YamlFile>()
            .expect("Failed to parse test YAML");
        parsed.document().expect("Expected a document")
    }

    #[test]
    fn test_failsafe_validation_success() {
        let yaml_str = r#"
name: "John Doe"
items:
  - "item1"
  - "item2"
nested:
  key: "value"
"#;
        let document = create_test_document(yaml_str);
        let validator = SchemaValidator::failsafe();

        assert!(validator.validate(&document).is_ok());
    }

    #[test]
    fn test_json_validation_success() {
        let yaml_str = r#"
name: "John Doe"
age: 30
height: 5.9
active: true
metadata: null
items:
  - "item1"
  - 42
  - true
"#;
        let document = create_test_document(yaml_str);
        let validator = SchemaValidator::json();

        assert!(validator.validate(&document).is_ok());
    }

    #[test]
    fn test_core_validation_success() {
        let yaml_str = r#"
name: "John Doe" 
age: 30
birth_date: !!timestamp "2001-12-15T02:59:43.1Z"
pattern: !!regex '\d{3}-\d{4}'
"#;
        let document = create_test_document(yaml_str);
        let validator = SchemaValidator::core();

        assert!(validator.validate(&document).is_ok());
    }

    #[test]
    fn test_failsafe_validation_failure() {
        let yaml_str = r#"
name: "John"
age: 30
active: true
"#;
        let document = create_test_document(yaml_str);
        let validator = SchemaValidator::failsafe().strict();

        let result = validator.validate(&document);
        // Should fail because age (integer) and active (boolean) are not allowed in failsafe schema
        assert!(result.is_err());
        let errors = result.unwrap_err();
        assert!(!errors.is_empty());

        // Should have errors for integer and boolean types
        assert!(errors.iter().all(|e| e.schema_name == "failsafe"));
        assert!(errors
            .iter()
            .all(|e| matches!(&e.kind, ValidationErrorKind::TypeNotAllowed { .. })));
    }

    #[test]
    fn test_json_validation_with_yaml_specific_types() {
        let yaml_str = r#"
timestamp: !!timestamp "2023-12-25T10:30:45Z"
pattern: !!regex '\d+'
"#;
        let document = create_test_document(yaml_str);
        let validator = SchemaValidator::json().strict();

        let result = validator.validate(&document);

        // Debug: Check what types are detected
        if result.is_ok() {
            println!("JSON validation unexpectedly passed!");

            println!("Document is mapping: {}", document.as_mapping().is_some());
            println!("Document is sequence: {}", document.as_sequence().is_some());
            println!("Document is scalar: {}", document.as_scalar().is_some());

            if let Some(mapping) = document.as_mapping() {
                println!("Mapping has {} pairs", mapping.pairs().count());
                for (key, value) in mapping.pairs() {
                    if let Some(scalar) = Scalar::cast(value.clone()) {
                        let scalar_value = ScalarValue::parse(scalar.as_string().trim());
                        println!(
                            "JSON test - Key '{}' -> Value: '{}' -> Type: {:?}",
                            key.text().to_string().trim(),
                            scalar.as_string().trim(),
                            scalar_value.scalar_type()
                        );
                    } else {
                        println!(
                            "Value for key '{}' is not a scalar. Node kind: {:?}",
                            key.text().to_string().trim(),
                            value.kind()
                        );
                    }
                }
            } else {
                println!("Document is not a mapping");
            }
        } else {
            println!("JSON validation correctly failed");
        }

        // Should fail because timestamp and regex are not allowed in JSON schema
        assert!(result.is_err());
        let errors = result.unwrap_err();
        assert!(!errors.is_empty());

        // Should have errors for timestamp and regex types
        assert!(errors.iter().all(|e| e.schema_name == "json"));
        assert!(errors
            .iter()
            .all(|e| matches!(&e.kind, ValidationErrorKind::TypeNotAllowed { .. })));
    }

    #[test]
    fn test_strict_mode_validation() {
        // Test with unquoted integer (should fail in failsafe strict mode)
        let yaml_str = r#"
count: 42
active: true
"#;
        let document = create_test_document(yaml_str);

        // Non-strict failsafe should pass via coercion
        let validator = SchemaValidator::failsafe();
        assert!(validator.can_coerce(&document).is_ok());

        // Strict failsafe should fail (integers and booleans not allowed)
        let strict_validator = SchemaValidator::failsafe().strict();
        let result = strict_validator.validate(&document);
        assert!(result.is_err());

        // Test with actual string (should pass in both modes)
        let string_yaml = r#"
name: hello
message: world
"#;
        let string_document = create_test_document(string_yaml);

        // Both should pass since these are actual strings
        let non_strict_result = validator.validate(&string_document);
        let strict_result = strict_validator.validate(&string_document);

        // Debug: Check what types are detected for plain strings
        if strict_result.is_err() {
            println!("String validation failed!");
            if let Some(mapping) = string_document.as_mapping() {
                for (key, value) in mapping.pairs() {
                    if let Some(scalar) = Scalar::cast(value.clone()) {
                        let scalar_value = ScalarValue::parse(scalar.as_string().trim());
                        println!(
                            "String - Key '{}' -> Value: '{}' -> Type: {:?}",
                            key.text().to_string().trim(),
                            scalar.as_string().trim(),
                            scalar_value.scalar_type()
                        );
                    }
                }
            }
            if let Err(ref errors) = strict_result {
                for error in errors {
                    println!("  - {}: {}", error.path, error.message());
                }
            }
        }

        // Note: Due to current type inference limitations, quoted numbers like "42"
        // are detected as integers rather than strings. This is a limitation of
        // the ScalarValue::parse() function, not the schema validation logic.
        // For now, we test with unambiguous strings.
        assert!(non_strict_result.is_ok());
        assert!(strict_result.is_ok());
    }

    #[test]
    fn test_validation_error_paths() {
        let yaml_str = r#"
users:
  - name: "John"
    age: 30
  - name: "Jane" 
    active: true
"#;
        let document = create_test_document(yaml_str);
        let validator = SchemaValidator::failsafe();

        let result = validator.validate(&document);
        if let Err(errors) = result {
            // Check that error paths are meaningful and start with "root"
            for error in &errors {
                assert!(!error.path.is_empty());
                assert!(
                    error.path.starts_with("root"),
                    "expected path to start with 'root', got: {:?}",
                    error.path
                );
            }
        }
    }

    #[test]
    fn test_schema_type_lists() {
        assert_eq!(
            Schema::Failsafe.allowed_scalar_types(),
            vec![ScalarType::String]
        );

        assert_eq!(
            Schema::Json.allowed_scalar_types(),
            vec![
                ScalarType::String,
                ScalarType::Integer,
                ScalarType::Float,
                ScalarType::Boolean,
                ScalarType::Null,
            ]
        );

        let core_types = Schema::Core.allowed_scalar_types();
        // Core includes at minimum: String, Integer, Float, Boolean, Null, Timestamp, Regex
        // (plus Binary if the base64 feature is enabled)
        let mut expected_core = vec![
            ScalarType::String,
            ScalarType::Integer,
            ScalarType::Float,
            ScalarType::Boolean,
            ScalarType::Null,
            ScalarType::Timestamp,
            ScalarType::Regex,
        ];
        #[cfg(feature = "base64")]
        expected_core.insert(5, ScalarType::Binary);
        assert_eq!(core_types, expected_core);
    }

    #[test]
    fn test_deep_sequence_validation() {
        let yaml_str = r#"
numbers:
  - 1
  - 2.5
  - "three"
  - true
"#;
        let document = create_test_document(yaml_str);

        // Failsafe should fail for non-string types in the sequence
        let failsafe_validator = SchemaValidator::failsafe().strict();
        let result = failsafe_validator.validate(&document);
        assert!(result.is_err());
        let errors = result.unwrap_err();
        assert!(!errors.is_empty());

        // JSON should succeed since all types are JSON-compatible
        let json_validator = SchemaValidator::json();
        let result = json_validator.validate(&document);
        assert!(result.is_ok());

        // Core should succeed since all types are allowed
        let core_validator = SchemaValidator::core();
        let result = core_validator.validate(&document);
        assert!(result.is_ok());
    }

    #[test]
    fn test_deep_nested_mapping_validation() {
        let yaml_str = r#"
user:
  name: "John"
  details:
    age: 30
    active: true
    scores:
      - 95
      - 87.5
"#;
        let document = create_test_document(yaml_str);

        // Failsafe should fail due to nested integers and booleans
        let failsafe_validator = SchemaValidator::failsafe().strict();
        let result = failsafe_validator.validate(&document);
        assert!(result.is_err());
        let errors = result.unwrap_err();
        assert!(!errors.is_empty());
        // Check that errors have meaningful paths
        let paths: Vec<&str> = errors.iter().map(|e| e.path.as_str()).collect();
        assert!(paths.contains(&"root.user.details.age"));
        assert!(paths.contains(&"root.user.details.scores[0]"));

        // JSON should succeed
        let json_validator = SchemaValidator::json();
        let result = json_validator.validate(&document);
        assert!(result.is_ok());
    }

    #[test]
    fn test_complex_yaml_types_validation() {
        let yaml_str = r#"
metadata:
  created: !!timestamp "2023-12-25T10:30:45Z"
  pattern: !!regex '\d{3}-\d{4}'
values:
  - !!timestamp "2023-01-01"
  - !!regex '[a-zA-Z]+'
"#;
        let document = create_test_document(yaml_str);

        // Failsafe should fail
        let failsafe_validator = SchemaValidator::failsafe().strict();
        let result = failsafe_validator.validate(&document);
        assert!(result.is_err());

        // JSON should fail
        let json_validator = SchemaValidator::json().strict();
        let result = json_validator.validate(&document);
        assert!(result.is_err());

        // Core should succeed
        let core_validator = SchemaValidator::core();
        let result = core_validator.validate(&document);
        assert!(result.is_ok());
    }

    #[test]
    fn test_coercion_deep_validation() {
        let yaml_str = r#"
config:
  timeout: "30"  # string that looks like number
  enabled: "true"  # string that looks like boolean  
  items:
    - "42"
    - "false"
"#;
        let document = create_test_document(yaml_str);

        // Non-strict JSON validation should pass via coercion
        let json_validator = SchemaValidator::json();
        let result = json_validator.can_coerce(&document);
        assert!(result.is_ok());

        // Strict JSON validation should fail (strings are not the exact types)
        let strict_json_validator = SchemaValidator::json().strict();
        let result = strict_json_validator.validate(&document);
        // Actually strings are allowed in JSON schema, so this should pass
        assert!(result.is_ok());

        // But if we put non-JSON types, strict mode should fail
        let problematic_yaml = r#"
data:
  timestamp: !!timestamp "2023-12-25"
"#;
        let problematic_doc = create_test_document(problematic_yaml);
        let result = strict_json_validator.validate(&problematic_doc);
        assert!(result.is_err());
    }

    #[test]
    fn test_validation_error_paths_nested() {
        let yaml_str = r#"
users:
  - name: "Alice"
    metadata:
      created: !!timestamp "2023-01-01"
      tags:
        - "admin"
        - 42  # This should fail in failsafe
  - name: "Bob"
    active: true  # This should fail in failsafe
"#;
        let document = create_test_document(yaml_str);
        let validator = SchemaValidator::failsafe().strict();

        let result = validator.validate(&document);
        assert!(result.is_err());
        let errors = result.unwrap_err();
        assert!(!errors.is_empty());

        // Check that we have errors with proper path information
        let paths: Vec<&str> = errors.iter().map(|e| e.path.as_str()).collect();

        // Should have paths that show the nested structure
        assert!(paths.contains(&"root.users[0].metadata.created"));
        assert!(paths.contains(&"root.users[0].metadata.tags[1]"));
        assert!(paths.contains(&"root.users[1].active"));

        // Print paths for debugging if needed
        for error in &errors {
            println!("Error at {}: {}", error.path, error.message());
        }
    }

    #[test]
    fn test_yaml_1_2_spec_compliance() {
        // Test that our schemas match YAML 1.2 specification requirements

        // 1. Failsafe Schema - Should only allow strings, mappings, and sequences
        let failsafe = Schema::Failsafe;
        assert!(failsafe.allows_scalar_type(ScalarType::String));
        assert!(!failsafe.allows_scalar_type(ScalarType::Integer));
        assert!(!failsafe.allows_scalar_type(ScalarType::Float));
        assert!(!failsafe.allows_scalar_type(ScalarType::Boolean));
        assert!(!failsafe.allows_scalar_type(ScalarType::Null));
        assert!(!failsafe.allows_scalar_type(ScalarType::Timestamp));

        // 2. JSON Schema - Should allow JSON-compatible types
        let json = Schema::Json;
        assert!(json.allows_scalar_type(ScalarType::String));
        assert!(json.allows_scalar_type(ScalarType::Integer));
        assert!(json.allows_scalar_type(ScalarType::Float));
        assert!(json.allows_scalar_type(ScalarType::Boolean));
        assert!(json.allows_scalar_type(ScalarType::Null));
        assert!(!json.allows_scalar_type(ScalarType::Timestamp)); // Not in JSON
        assert!(!json.allows_scalar_type(ScalarType::Regex)); // Not in JSON
        #[cfg(feature = "base64")]
        assert!(!json.allows_scalar_type(ScalarType::Binary)); // Not in JSON

        // 3. Core Schema - Should allow all YAML types
        let core = Schema::Core;
        assert!(core.allows_scalar_type(ScalarType::String));
        assert!(core.allows_scalar_type(ScalarType::Integer));
        assert!(core.allows_scalar_type(ScalarType::Float));
        assert!(core.allows_scalar_type(ScalarType::Boolean));
        assert!(core.allows_scalar_type(ScalarType::Null));
        assert!(core.allows_scalar_type(ScalarType::Timestamp));
        assert!(core.allows_scalar_type(ScalarType::Regex));
        #[cfg(feature = "base64")]
        assert!(core.allows_scalar_type(ScalarType::Binary));

        // Test schema names match spec
        assert_eq!(failsafe.name(), "failsafe");
        assert_eq!(json.name(), "json");
        assert_eq!(core.name(), "core");
    }

    #[test]
    fn test_spec_compliant_validation_examples() {
        // Examples from YAML 1.2 specification

        // Failsafe: Should accept plain strings but reject typed values
        let failsafe_yaml = r#"
string: hello
number_as_string: "123"
"#;
        let failsafe_doc = create_test_document(failsafe_yaml);
        let failsafe_validator = SchemaValidator::failsafe();
        // Non-strict mode allows coercion
        assert!(failsafe_validator.validate(&failsafe_doc).is_ok());

        // JSON: Should accept JSON-compatible types
        let json_yaml = r#"
string: "hello"
number: 42
float: 3.14
boolean: true
null_value: null
"#;
        let json_doc = create_test_document(json_yaml);
        let json_validator = SchemaValidator::json();
        assert!(json_validator.validate(&json_doc).is_ok());

        // Core: Should accept all YAML types including timestamps
        let core_yaml = r#"
timestamp: 2023-01-01T00:00:00Z
regex: !!regex '[0-9]+'
binary: !!binary "SGVsbG8gV29ybGQ="
"#;
        let core_doc = create_test_document(core_yaml);
        let core_validator = SchemaValidator::core();
        assert!(core_validator.validate(&core_doc).is_ok());

        // JSON should reject YAML-specific types
        let json_strict = SchemaValidator::json().strict();
        assert!(json_strict.validate(&core_doc).is_err());
    }

    #[test]
    fn test_custom_schema_basic() {
        // Create a custom schema that only allows strings and integers (strict mode to prevent coercion)
        let custom_schema = CustomSchema::new("test")
            .allow_types(&[ScalarType::String, ScalarType::Integer])
            .strict(); // No coercion

        let validator = SchemaValidator::custom(custom_schema);

        // Test with allowed types
        let valid_yaml = r#"
name: hello world
count: 42
"#;
        let valid_doc = create_test_document(valid_yaml);
        let result = validator.validate(&valid_doc);
        if let Err(ref errors) = result {
            for error in errors {
                println!("Valid test error: {}", error);
            }
        }
        assert!(result.is_ok());

        // Test with disallowed type
        let invalid_yaml = r#"
name: hello world
enabled: true  # boolean not allowed
"#;
        let invalid_doc = create_test_document(invalid_yaml);
        let result = validator.validate(&invalid_doc);
        assert!(result.is_err());

        let errors = result.unwrap_err();
        assert_eq!(errors.len(), 1);
        assert_eq!(
            errors[0].message(),
            "type Boolean not allowed in test schema, expected one of [String, Integer]"
        );
    }

    #[test]
    fn test_custom_schema_with_validators() {
        // Create a custom schema with string validators
        let custom_schema = CustomSchema::new("email-validation")
            .allow_type(ScalarType::String)
            .with_validator(ScalarType::String, |value, _path| {
                if value.contains('@') && value.contains('.') {
                    CustomValidationResult::Valid
                } else {
                    CustomValidationResult::invalid("email_format", "invalid email format")
                }
            });

        let validator = SchemaValidator::custom(custom_schema);

        // Test with valid email
        let valid_yaml = r#"
email: "user@example.com"
"#;
        let valid_doc = create_test_document(valid_yaml);
        assert!(validator.validate(&valid_doc).is_ok());

        // Test with invalid email
        let invalid_yaml = r#"
email: "not-an-email"
"#;
        let invalid_doc = create_test_document(invalid_yaml);
        let result = validator.validate(&invalid_doc);
        assert!(result.is_err());

        let errors = result.unwrap_err();
        assert_eq!(errors.len(), 1);
        assert_eq!(
            errors[0].message(),
            "custom constraint 'email_format: invalid email format' failed for value 'not-an-email'"
        );
    }

    #[test]
    fn test_custom_schema_integer_range() {
        // Custom schema with integer range validation
        let custom_schema = CustomSchema::new("port-validation")
            .allow_type(ScalarType::Integer)
            .with_validator(ScalarType::Integer, |value, _path| {
                if let Ok(port) = value.parse::<u16>() {
                    if (1024..=65535).contains(&port) {
                        CustomValidationResult::Valid
                    } else {
                        CustomValidationResult::invalid(
                            "port_range",
                            format!("port {} must be between 1024 and 65535", port),
                        )
                    }
                } else {
                    CustomValidationResult::invalid(
                        "integer_format",
                        format!("invalid integer: {}", value),
                    )
                }
            });

        let validator = SchemaValidator::custom(custom_schema);

        // Test with valid port
        let valid_yaml = r#"
port: 8080
"#;
        let valid_doc = create_test_document(valid_yaml);
        assert!(validator.validate(&valid_doc).is_ok());

        // Test with invalid port (too low)
        let invalid_yaml = r#"
port: 80
"#;
        let invalid_doc = create_test_document(invalid_yaml);
        let result = validator.validate(&invalid_doc);
        assert!(result.is_err());

        let errors = result.unwrap_err();
        assert!(!errors.is_empty());
        assert_eq!(
            errors[0].message(),
            "custom constraint 'port_range: port 80 must be between 1024 and 65535' failed for value '80'"
        );
    }

    #[test]
    fn test_custom_schema_multiple_validators() {
        // Schema with multiple type validators
        let custom_schema = CustomSchema::new("config-validation")
            .allow_types(&[ScalarType::String, ScalarType::Integer])
            .with_validator(ScalarType::String, |value, _path| {
                if value.len() >= 3 {
                    CustomValidationResult::Valid
                } else {
                    CustomValidationResult::invalid(
                        "string_length",
                        format!("string too short: '{}'", value),
                    )
                }
            })
            .with_validator(ScalarType::Integer, |value, _path| {
                if let Ok(num) = value.parse::<i32>() {
                    if num >= 0 {
                        CustomValidationResult::Valid
                    } else {
                        CustomValidationResult::invalid(
                            "negative_number",
                            format!("negative numbers not allowed: {}", num),
                        )
                    }
                } else {
                    CustomValidationResult::invalid(
                        "integer_format",
                        format!("invalid integer: {}", value),
                    )
                }
            });

        let validator = SchemaValidator::custom(custom_schema);

        // Test with valid values
        let valid_yaml = r#"
name: "valid-name"
count: 100
"#;
        let valid_doc = create_test_document(valid_yaml);
        assert!(validator.validate(&valid_doc).is_ok());

        // Test with invalid string (too short)
        let invalid_yaml = r#"
name: "ab"
count: 100
"#;
        let invalid_doc = create_test_document(invalid_yaml);
        let result = validator.validate(&invalid_doc);
        assert!(result.is_err());

        let errors = result.unwrap_err();
        assert_eq!(errors.len(), 1);
        assert_eq!(
            errors[0].message(),
            "custom constraint 'string_length: string too short: 'ab'' failed for value 'ab'"
        );
    }

    #[test]
    fn test_custom_schema_strict_mode() {
        let custom_schema = CustomSchema::new("strict-test")
            .allow_type(ScalarType::String)
            .strict();

        let validator = SchemaValidator::custom(custom_schema);

        // Test that even valid integers are rejected in strict mode
        let yaml_with_int = r#"
value: 42
"#;
        let doc = create_test_document(yaml_with_int);
        let result = validator.validate(&doc);
        assert!(result.is_err());

        let errors = result.unwrap_err();
        assert_eq!(errors.len(), 1);
        assert_eq!(
            errors[0].message(),
            "type Integer not allowed in strict-test schema, expected one of [String]"
        );
    }

    #[test]
    fn test_custom_schema_name() {
        let custom_schema = CustomSchema::new("my-custom-schema").allow_type(ScalarType::String);
        let schema = Schema::Custom(custom_schema);

        assert_eq!(schema.name(), "my-custom-schema");
    }
}