boxmux 0.240.3373

YAML-driven terminal UI framework for rich, interactive CLI applications and dashboards with PTY support
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
use crate::model::common::Config;
use crate::{App, Layout, MuxBox};
use jsonschema::JSONSchema;
use serde_json::{Map, Value};
use std::collections::HashSet;

/// App JSON schema, embedded at compile time so validation works regardless of
/// the current working directory or where the binary is installed.
const APP_SCHEMA: &str = include_str!("../schemas/app_schema.json");

/// Embedded schema parsed once.
static APP_SCHEMA_VALUE: once_cell::sync::Lazy<Value> = once_cell::sync::Lazy::new(|| {
    serde_json::from_str(APP_SCHEMA).expect("embedded app schema must be valid JSON")
});

/// Embedded schema compiled once. Recompiling this 30KB schema on every config
/// load is expensive (regex compilation), so it is built a single time and shared.
static APP_SCHEMA_COMPILED: once_cell::sync::Lazy<JSONSchema> =
    once_cell::sync::Lazy::new(|| {
        JSONSchema::compile(&APP_SCHEMA_VALUE).expect("embedded app schema must compile")
    });

/// Configuration schema validation errors
#[derive(Debug, Clone)]
pub enum ValidationError {
    InvalidFieldType {
        field: String,
        expected: String,
        actual: String,
    },
    MissingRequiredField {
        field: String,
    },
    InvalidFieldValue {
        field: String,
        value: String,
        constraint: String,
    },
    DuplicateId {
        id: String,
        location: String,
    },
    InvalidReference {
        field: String,
        reference: String,
        target_type: String,
    },
    SchemaStructure {
        message: String,
    },
    JsonSchemaValidation {
        field: String,
        message: String,
    },
    DeprecationWarning {
        field: String,
        message: String,
    },
}

impl std::fmt::Display for ValidationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ValidationError::InvalidFieldType {
                field,
                expected,
                actual,
            } => {
                write!(
                    f,
                    "Field '{}' expected type '{}' but got '{}'",
                    field, expected, actual
                )
            }
            ValidationError::MissingRequiredField { field } => {
                write!(f, "Required field '{}' is missing", field)
            }
            ValidationError::InvalidFieldValue {
                field,
                value,
                constraint,
            } => {
                write!(
                    f,
                    "Field '{}' has invalid value '{}' (constraint: {})",
                    field, value, constraint
                )
            }
            ValidationError::DuplicateId { id, location } => {
                write!(f, "Duplicate ID '{}' found in {}", id, location)
            }
            ValidationError::InvalidReference {
                field,
                reference,
                target_type,
            } => {
                write!(
                    f,
                    "Field '{}' references unknown {} '{}'",
                    field, target_type, reference
                )
            }
            ValidationError::SchemaStructure { message } => {
                write!(f, "Schema structure error: {}", message)
            }
            ValidationError::JsonSchemaValidation { field, message } => {
                write!(
                    f,
                    "JSON Schema validation error in '{}': {}",
                    field, message
                )
            }
            ValidationError::DeprecationWarning { field, message } => {
                write!(f, "Deprecation warning for '{}': {}", field, message)
            }
        }
    }
}

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

/// Schema validation result
pub type ValidationResult = Result<(), Vec<ValidationError>>;

/// Central schema validator for BoxMux configurations
pub struct SchemaValidator {
    errors: Vec<ValidationError>,
    warnings: Vec<ValidationError>,
    muxbox_ids: HashSet<String>,
    layout_ids: HashSet<String>,
}

impl SchemaValidator {
    pub fn new() -> Self {
        Self {
            errors: Vec::new(),
            warnings: Vec::new(),
            muxbox_ids: HashSet::new(),
            layout_ids: HashSet::new(),
        }
    }

    /// Validate a complete BoxMux application configuration
    pub fn validate_app(&mut self, app: &App) -> ValidationResult {
        self.clear();

        // Collect all IDs first for reference validation
        self.collect_ids(app);

        // Validate application structure
        if app.layouts.is_empty() {
            self.add_error(ValidationError::MissingRequiredField {
                field: "layouts".to_string(),
            });
        }

        // Validate each layout
        for (idx, layout) in app.layouts.iter().enumerate() {
            let _ = self.validate_layout(layout, &format!("layouts[{}]", idx));
        }

        // Validate root layout constraints
        self.validate_root_layout_constraints(app);

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

    /// Validate a single layout
    pub fn validate_layout(&mut self, layout: &Layout, path: &str) -> ValidationResult {
        // Validate required fields
        if layout.id.is_empty() {
            self.add_error(ValidationError::MissingRequiredField {
                field: format!("{}.id", path),
            });
        }

        // Validate muxboxes if present
        if let Some(muxboxes) = &layout.children {
            for (idx, muxbox) in muxboxes.iter().enumerate() {
                let _ = self.validate_muxbox(muxbox, &format!("{}.children[{}]", path, idx));
            }
        }

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

    /// Validate a single muxbox
    pub fn validate_muxbox(&mut self, muxbox: &MuxBox, path: &str) -> ValidationResult {
        // Validate required fields
        if muxbox.id.is_empty() {
            self.add_error(ValidationError::MissingRequiredField {
                field: format!("{}.id", path),
            });
        }

        // Validate position bounds
        self.validate_input_bounds_schema(&muxbox.position, &format!("{}.position", path));

        // Validate child muxboxes recursively
        if let Some(children) = &muxbox.children {
            for (idx, child) in children.iter().enumerate() {
                let _ = self.validate_muxbox(child, &format!("{}.children[{}]", path, idx));
            }
        }

        // Validate script commands if present
        if let Some(scripts) = &muxbox.script {
            for (idx, script) in scripts.iter().enumerate() {
                if script.trim().is_empty() {
                    self.add_error(ValidationError::InvalidFieldValue {
                        field: format!("{}.script[{}]", path, idx),
                        value: "empty".to_string(),
                        constraint: "script commands cannot be empty".to_string(),
                    });
                }
            }
        }

        // Validate ExecutionMode integration and deprecation warnings
        self.validate_execution_mode_fields(
            &muxbox.execution_mode,
            &format!("{}.execution_mode", path),
        );

        // Validate choices if present
        if let Some(choices) = &muxbox.choices {
            for (idx, choice) in choices.iter().enumerate() {
                let _ = self.validate_choice(choice, &format!("{}.choices[{}]", path, idx));
            }
        }

        // Return both errors and warnings for comprehensive validation
        let mut all_issues = self.errors.clone();
        all_issues.extend(self.warnings.clone());

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

    /// Validate configuration schema
    pub fn validate_config(&mut self, config: &Config) -> ValidationResult {
        self.clear();

        if config.frame_delay == 0 {
            self.add_error(ValidationError::InvalidFieldValue {
                field: "frame_delay".to_string(),
                value: "0".to_string(),
                constraint: "frame_delay must be greater than 0".to_string(),
            });
        }

        if config.frame_delay > 1000 {
            self.add_error(ValidationError::InvalidFieldValue {
                field: "frame_delay".to_string(),
                value: config.frame_delay.to_string(),
                constraint: "frame_delay should not exceed 1000ms for usability".to_string(),
            });
        }

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

    /// Validate YAML content against the app JSON schema embedded in the binary.
    ///
    /// The schema is compiled in via `include_str!`, so validation never depends
    /// on the current working directory or where the binary is installed.
    pub fn validate_app_yaml(&mut self, yaml_content: &str) -> ValidationResult {
        self.clear();

        // Parse YAML content to JSON
        let yaml_value: Value = match serde_yaml::from_str(yaml_content) {
            Ok(value) => value,
            Err(e) => {
                self.add_error(ValidationError::SchemaStructure {
                    message: format!("Invalid YAML syntax: {}", e),
                });
                return Err(self.errors.clone());
            }
        };

        // Validate against the pre-compiled embedded schema (compiled once).
        if let Err(errors) = APP_SCHEMA_COMPILED.validate(&yaml_value) {
            for error in errors {
                let error_path = if error.instance_path.to_string().is_empty() {
                    "app".to_string()
                } else {
                    format!("app.{}", error.instance_path)
                };
                self.add_error(ValidationError::JsonSchemaValidation {
                    field: error_path,
                    message: error.to_string(),
                });
            }
        }

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

    /// Validate a JSON value against schema source text.
    fn validate_against_schema_content(
        &mut self,
        value: &Value,
        schema_content: &str,
        schema_label: &str,
        field_name: &str,
    ) -> ValidationResult {
        // Parse schema
        let schema_json: Value = match serde_json::from_str(schema_content) {
            Ok(schema) => schema,
            Err(e) => {
                self.add_error(ValidationError::SchemaStructure {
                    message: format!("Invalid JSON schema in '{}': {}", schema_label, e),
                });
                return Err(self.errors.clone());
            }
        };

        // Compile and validate schema
        let compiled_schema = match JSONSchema::compile(&schema_json) {
            Ok(schema) => schema,
            Err(e) => {
                self.add_error(ValidationError::SchemaStructure {
                    message: format!("Failed to compile schema '{}': {}", schema_label, e),
                });
                return Err(self.errors.clone());
            }
        };

        // Validate the value against the schema
        if let Err(errors) = compiled_schema.validate(value) {
            for error in errors {
                let error_path = if error.instance_path.to_string().is_empty() {
                    field_name.to_string()
                } else {
                    format!("{}.{}", field_name, error.instance_path)
                };

                self.add_error(ValidationError::JsonSchemaValidation {
                    field: error_path,
                    message: error.to_string(),
                });
            }
            return Err(self.errors.clone());
        }

        Ok(())
    }

    /// Validate JSON configuration against schema
    pub fn validate_json_config(&mut self, config: &Value) -> ValidationResult {
        self.clear();

        if !config.is_object() {
            self.add_error(ValidationError::SchemaStructure {
                message: "Configuration must be a JSON object".to_string(),
            });
            return Err(self.errors.clone());
        }

        let obj = config.as_object().unwrap();

        // Validate required top-level fields
        if !obj.contains_key("layouts") {
            self.add_error(ValidationError::MissingRequiredField {
                field: "layouts".to_string(),
            });
        } else if !obj["layouts"].is_array() {
            self.add_error(ValidationError::InvalidFieldType {
                field: "layouts".to_string(),
                expected: "array".to_string(),
                actual: self.get_json_type(&obj["layouts"]),
            });
        }

        // Validate optional config section
        if let Some(config_section) = obj.get("config") {
            if !config_section.is_object() {
                self.add_error(ValidationError::InvalidFieldType {
                    field: "config".to_string(),
                    expected: "object".to_string(),
                    actual: self.get_json_type(config_section),
                });
            } else {
                self.validate_json_config_section(config_section.as_object().unwrap());
            }
        }

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

    /// Validate a single choice
    pub fn validate_choice(
        &mut self,
        choice: &crate::model::choice::Choice,
        path: &str,
    ) -> ValidationResult {
        // Validate required fields
        if choice.id.is_empty() {
            self.add_error(ValidationError::MissingRequiredField {
                field: format!("{}.id", path),
            });
        }

        // Validate ExecutionMode integration and deprecation warnings
        self.validate_execution_mode_fields(
            &choice.execution_mode,
            &format!("{}.execution_mode", path),
        );

        // Return both errors and warnings for comprehensive validation
        let mut all_issues = self.errors.clone();
        all_issues.extend(self.warnings.clone());

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

    /// Validate ExecutionMode field consistency and provide deprecation warnings
    fn validate_execution_mode_fields(
        &mut self,
        execution_mode: &crate::model::common::ExecutionMode,
        _path: &str,
    ) {
        use crate::model::common::ExecutionMode;

        // T0330: Legacy thread/pty fields removed - no more deprecation warnings needed

        // Validate ExecutionMode enum values
        match execution_mode {
            ExecutionMode::Immediate | ExecutionMode::Thread | ExecutionMode::Pty => {
                // Valid enum values
            }
        }

        // T0330: Legacy field conflict checking removed - no more legacy fields exist
    }

    /// Helper methods
    fn clear(&mut self) {
        self.errors.clear();
        self.warnings.clear();
        self.muxbox_ids.clear();
        self.layout_ids.clear();
    }

    fn add_error(&mut self, error: ValidationError) {
        match error {
            ValidationError::DeprecationWarning { .. } => {
                self.warnings.push(error);
            }
            _ => {
                self.errors.push(error);
            }
        }
    }

    /// Get warnings (non-fatal validation issues)
    pub fn get_warnings(&self) -> &Vec<ValidationError> {
        &self.warnings
    }

    fn collect_ids(&mut self, app: &App) {
        for layout in &app.layouts {
            if !self.layout_ids.insert(layout.id.clone()) {
                self.add_error(ValidationError::DuplicateId {
                    id: layout.id.clone(),
                    location: "layouts".to_string(),
                });
            }
            self.collect_muxbox_ids_recursive(&layout.children, "muxboxes");
        }
    }

    fn collect_muxbox_ids_recursive(&mut self, muxboxes: &Option<Vec<MuxBox>>, location: &str) {
        if let Some(muxbox_list) = muxboxes {
            for muxbox in muxbox_list {
                if !self.muxbox_ids.insert(muxbox.id.clone()) {
                    self.add_error(ValidationError::DuplicateId {
                        id: muxbox.id.clone(),
                        location: location.to_string(),
                    });
                }
                self.collect_muxbox_ids_recursive(&muxbox.children, location);

                // Check choice IDs if they exist
                if let Some(choices) = &muxbox.choices {
                    for choice in choices {
                        if !self.muxbox_ids.insert(choice.id.clone()) {
                            self.add_error(ValidationError::DuplicateId {
                                id: choice.id.clone(),
                                location: "choices".to_string(),
                            });
                        }
                    }
                }
            }
        }
    }

    fn validate_root_layout_constraints(&mut self, app: &App) {
        let mut root_count = 0;
        for layout in &app.layouts {
            if layout.root == Some(true) {
                root_count += 1;
            }
        }

        if root_count > 1 {
            self.add_error(ValidationError::SchemaStructure {
                message:
                    "Multiple root layouts detected. Only one layout can be marked as 'root: true'."
                        .to_string(),
            });
        }
    }

    fn validate_input_bounds_schema(
        &mut self,
        bounds: &crate::model::common::InputBounds,
        path: &str,
    ) {
        // Validate that bounds strings are not empty
        if bounds.x1.trim().is_empty() {
            self.add_error(ValidationError::InvalidFieldValue {
                field: format!("{}.x1", path),
                value: "empty".to_string(),
                constraint: "bounds coordinates cannot be empty".to_string(),
            });
        }

        if bounds.y1.trim().is_empty() {
            self.add_error(ValidationError::InvalidFieldValue {
                field: format!("{}.y1", path),
                value: "empty".to_string(),
                constraint: "bounds coordinates cannot be empty".to_string(),
            });
        }

        if bounds.x2.trim().is_empty() {
            self.add_error(ValidationError::InvalidFieldValue {
                field: format!("{}.x2", path),
                value: "empty".to_string(),
                constraint: "bounds coordinates cannot be empty".to_string(),
            });
        }

        if bounds.y2.trim().is_empty() {
            self.add_error(ValidationError::InvalidFieldValue {
                field: format!("{}.y2", path),
                value: "empty".to_string(),
                constraint: "bounds coordinates cannot be empty".to_string(),
            });
        }
    }

    fn validate_json_config_section(&mut self, config: &Map<String, Value>) {
        if let Some(frame_delay) = config.get("frame_delay") {
            if let Some(delay) = frame_delay.as_u64() {
                if delay == 0 {
                    self.add_error(ValidationError::InvalidFieldValue {
                        field: "config.frame_delay".to_string(),
                        value: "0".to_string(),
                        constraint: "frame_delay must be greater than 0".to_string(),
                    });
                }
            } else {
                self.add_error(ValidationError::InvalidFieldType {
                    field: "config.frame_delay".to_string(),
                    expected: "number".to_string(),
                    actual: self.get_json_type(frame_delay),
                });
            }
        }
    }

    fn get_json_type(&self, value: &Value) -> String {
        match value {
            Value::Null => "null".to_string(),
            Value::Bool(_) => "boolean".to_string(),
            Value::Number(_) => "number".to_string(),
            Value::String(_) => "string".to_string(),
            Value::Array(_) => "array".to_string(),
            Value::Object(_) => "object".to_string(),
        }
    }
}

impl Default for SchemaValidator {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::common::{Config, InputBounds};
    use crate::{App, Layout, MuxBox};

    fn create_test_muxbox(id: &str) -> MuxBox {
        MuxBox {
            id: id.to_string(),
            position: InputBounds {
                x1: "10".to_string(),
                y1: "20".to_string(),
                x2: "90".to_string(),
                y2: "80".to_string(),
            },
            ..Default::default()
        }
    }

    fn create_test_layout(id: &str) -> Layout {
        Layout {
            id: id.to_string(),
            children: Some(vec![create_test_muxbox("muxbox1")]),
            ..Default::default()
        }
    }

    fn create_test_app() -> App {
        let mut app = App::new();
        app.layouts = vec![create_test_layout("layout1")];
        app
    }

    #[test]
    fn test_validate_app_success() {
        let mut validator = SchemaValidator::new();
        let app = create_test_app();

        let result = validator.validate_app(&app);
        assert!(result.is_ok());
    }

    #[test]
    fn test_validate_app_no_layouts() {
        let mut validator = SchemaValidator::new();
        let app = App::new();

        let result = validator.validate_app(&app);
        assert!(result.is_err());

        let errors = result.unwrap_err();
        assert_eq!(errors.len(), 1);
        assert!(matches!(
            errors[0],
            ValidationError::MissingRequiredField { .. }
        ));
    }

    #[test]
    fn test_validate_config_success() {
        let mut validator = SchemaValidator::new();
        let config = Config::new(60);

        let result = validator.validate_config(&config);
        assert!(result.is_ok());
    }

    #[test]
    fn test_validate_config_zero_frame_delay() {
        let mut validator = SchemaValidator::new();
        let config = Config {
            frame_delay: 0,
            locked: false,
            calibrate: false,
        };

        let result = validator.validate_config(&config);
        assert!(result.is_err());

        let errors = result.unwrap_err();
        assert_eq!(errors.len(), 1);
        assert!(matches!(
            errors[0],
            ValidationError::InvalidFieldValue { .. }
        ));
    }

    #[test]
    fn test_validate_config_excessive_frame_delay() {
        let mut validator = SchemaValidator::new();
        let config = Config {
            frame_delay: 2000,
            locked: false,
            calibrate: false,
        };

        let result = validator.validate_config(&config);
        assert!(result.is_err());

        let errors = result.unwrap_err();
        assert_eq!(errors.len(), 1);
        assert!(matches!(
            errors[0],
            ValidationError::InvalidFieldValue { .. }
        ));
    }

    #[test]
    fn test_validate_json_config_success() {
        let mut validator = SchemaValidator::new();
        let config = serde_json::json!({
            "layouts": [
                {
                    "id": "layout1",
                    "children": [
                        {
                            "id": "muxbox1",
                            "bounds": {
                                "x1": "10",
                                "y1": "20",
                                "x2": "90",
                                "y2": "80"
                            }
                        }
                    ]
                }
            ],
            "config": {
                "frame_delay": 60
            }
        });

        let result = validator.validate_json_config(&config);
        assert!(result.is_ok());
    }

    #[test]
    fn test_validate_json_config_missing_layouts() {
        let mut validator = SchemaValidator::new();
        let config = serde_json::json!({
            "config": {
                "frame_delay": 60
            }
        });

        let result = validator.validate_json_config(&config);
        assert!(result.is_err());

        let errors = result.unwrap_err();
        assert_eq!(errors.len(), 1);
        assert!(matches!(
            errors[0],
            ValidationError::MissingRequiredField { .. }
        ));
    }

    #[test]
    fn test_validate_empty_bounds() {
        let mut validator = SchemaValidator::new();
        let muxbox = MuxBox {
            id: "test_muxbox".to_string(),
            position: InputBounds {
                x1: "".to_string(), // Empty bound
                y1: "20".to_string(),
                x2: "90".to_string(),
                y2: "80".to_string(),
            },
            ..Default::default()
        };

        let result = validator.validate_muxbox(&muxbox, "test_muxbox");
        assert!(result.is_err());

        let errors = result.unwrap_err();
        assert!(errors
            .iter()
            .any(|e| matches!(e, ValidationError::InvalidFieldValue { .. })));
    }

    #[test]
    fn test_validation_error_formatting() {
        // Test that ValidationError instances format correctly for user display
        let duplicate_error = ValidationError::DuplicateId {
            id: "muxbox1".to_string(),
            location: "muxboxes".to_string(),
        };
        assert_eq!(
            duplicate_error.to_string(),
            "Duplicate ID 'muxbox1' found in muxboxes"
        );

        let missing_field_error = ValidationError::MissingRequiredField {
            field: "layouts".to_string(),
        };
        assert_eq!(
            missing_field_error.to_string(),
            "Required field 'layouts' is missing"
        );

        let schema_error = ValidationError::SchemaStructure {
            message:
                "Multiple root layouts detected. Only one layout can be marked as 'root: true'."
                    .to_string(),
        };
        assert_eq!(schema_error.to_string(), "Schema structure error: Multiple root layouts detected. Only one layout can be marked as 'root: true'.");
    }

    #[test]
    fn test_json_schema_validation_success() {
        let mut validator = SchemaValidator::new();
        let yaml_content = r#"
app:
  layouts:
    - id: 'test_layout'
      title: 'Test Layout'
      children:
        - id: 'muxbox1'
          position:
            x1: "0%"
            y1: "0%"
            x2: "100%"
            y2: "100%"
          content: 'Test content'
          tab_order: 1
"#;

        let result = validator.validate_app_yaml(yaml_content);

        // This should pass if schema files exist and are valid
        match result {
            Ok(_) => {
                // Schema validation passed - verify it actually validated something
                // This is acceptable - schema validation completed successfully
            }
            Err(errors) => {
                // If schemas don't exist, that's expected - just verify the error is about missing schema files
                let error_messages: Vec<String> = errors.iter().map(|e| e.to_string()).collect();
                let combined = error_messages.join("; ");
                assert!(
                    combined.contains("Failed to load schema file")
                        || combined.contains("No such file")
                );
            }
        }
    }

    #[test]
    fn test_json_schema_validation_invalid_yaml() {
        let mut validator = SchemaValidator::new();
        let invalid_yaml = r#"
app:
  layouts:
    - id: 'test'
      children:
        - id: 'muxbox1'
          position:
            x1: "0%"
            y1: "0%"
            x2: "100%"
            # Missing y2 - should cause validation error
          border_color: 'invalid_color'  # Invalid color
"#;

        let result = validator.validate_app_yaml(invalid_yaml);

        match result {
            Ok(_) => {
                // If schemas don't exist, the validation will skip JSON schema validation
                // and this is expected behavior - no assertion needed
            }
            Err(errors) => {
                // Should contain validation errors or schema loading errors
                assert!(!errors.is_empty());
                let error_messages: Vec<String> = errors.iter().map(|e| e.to_string()).collect();
                let combined = error_messages.join("; ");
                // Either schema validation errors or schema file missing
                assert!(
                    combined.contains("JSON Schema validation error")
                        || combined.contains("Failed to load schema file")
                        || combined.contains("No such file")
                );
            }
        }
    }

    #[test]
    fn test_json_schema_validation_malformed_yaml() {
        let mut validator = SchemaValidator::new();
        let malformed_yaml = r#"
app:
  layouts:
    - id: 'test'
      children:
        - id: 'muxbox1'
          position:
            x1: "0%"
            y1: "0%"
            x2: "100%"
            y2: "100%"
          invalid_field_that_should_not_exist: 'invalid'
          border_color: 123  # Wrong type - should be string
"#;

        let result = validator.validate_app_yaml(malformed_yaml);

        match result {
            Ok(_) => {
                // If schemas don't exist, validation is skipped
                // This is acceptable behavior - no assertion needed
            }
            Err(errors) => {
                assert!(!errors.is_empty());
                // Verify we get meaningful error reporting
                for error in &errors {
                    match error {
                        ValidationError::JsonSchemaValidation { field, message } => {
                            assert!(!field.is_empty());
                            assert!(!message.is_empty());
                        }
                        ValidationError::SchemaStructure { message } => {
                            assert!(!message.is_empty());
                        }
                        _ => {} // Other error types are acceptable
                    }
                }
            }
        }
    }

    #[test]
    fn test_json_schema_validation_error_formatting() {
        let json_schema_error = ValidationError::JsonSchemaValidation {
            field: "app.layouts[0].children[0].border_color".to_string(),
            message: "invalid_color is not one of the allowed values".to_string(),
        };

        let formatted = json_schema_error.to_string();
        assert!(formatted.contains("JSON Schema validation error"));
        assert!(formatted.contains("app.layouts[0].children[0].border_color"));
        assert!(formatted.contains("invalid_color is not one of the allowed values"));
    }

    #[test]
    fn test_validate_against_schema_content_rejects_malformed_schema() {
        let mut validator = SchemaValidator::new();
        let test_value = serde_json::json!({
            "test": "value"
        });

        let result = validator.validate_against_schema_content(
            &test_value,
            "{ this is not valid json",
            "broken schema",
            "test",
        );

        assert!(result.is_err());
        let errors = result.unwrap_err();
        assert_eq!(errors.len(), 1);
        assert!(matches!(errors[0], ValidationError::SchemaStructure { .. }));
        assert!(errors[0].to_string().contains("Invalid JSON schema"));
    }

    #[test]
    fn test_embedded_app_schema_compiles_and_validates() {
        // The embedded schema must be valid JSON Schema so production validation
        // never fails for schema-loading reasons regardless of working directory.
        let mut validator = SchemaValidator::new();
        let minimal_app = r#"
app:
  layouts:
    - id: 'main'
      root: true
      children:
        - id: 'box1'
          position:
            x1: '0%'
            y1: '0%'
            x2: '100%'
            y2: '100%'
"#;
        assert!(
            validator.validate_app_yaml(minimal_app).is_ok(),
            "embedded schema must accept a minimal valid app"
        );
    }

    #[test]
    fn test_comprehensive_validation_with_multiple_errors() {
        let mut validator = SchemaValidator::new();

        // Create an app with multiple validation errors
        let mut app = App::new();

        // Error 1: Multiple root layouts
        let mut layout1 = create_test_layout("layout1");
        layout1.root = Some(true);
        let mut layout2 = create_test_layout("layout2");
        layout2.root = Some(true); // Second root - should cause error

        // Error 2: Duplicate muxbox IDs
        let muxbox1 = create_test_muxbox("muxbox1");
        let muxbox1_dup = create_test_muxbox("muxbox1"); // Duplicate ID
        layout1.children = Some(vec![muxbox1]);
        layout2.children = Some(vec![muxbox1_dup]);

        app.layouts = vec![layout1, layout2];

        let result = validator.validate_app(&app);
        assert!(result.is_err());

        let errors = result.unwrap_err();
        assert!(
            errors.len() >= 2,
            "Should have at least 2 validation errors"
        );

        // Check for multiple root layouts error
        assert!(errors
            .iter()
            .any(|e| matches!(e, ValidationError::SchemaStructure { .. })));

        // Check for duplicate ID error
        assert!(errors
            .iter()
            .any(|e| matches!(e, ValidationError::DuplicateId { .. })));
    }
}