pixelsrc 0.2.0

Pixelsrc - GenAI-native pixel art format and compiler
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
//! Validation logic for Pixelsrc files
//!
//! Provides semantic validation beyond basic JSON parsing, checking for
//! common mistakes like undefined tokens, row mismatches, and invalid colors.

use crate::color::parse_color;
use crate::models::{PaletteRef, Particle, TtpObject};
use crate::tokenizer::tokenize;
use serde_json::Value;
use std::collections::{HashMap, HashSet};
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::path::Path;

/// Severity of a validation issue
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Severity {
    Error,
    Warning,
}

impl std::fmt::Display for Severity {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Severity::Error => write!(f, "ERROR"),
            Severity::Warning => write!(f, "WARNING"),
        }
    }
}

/// Type of validation issue
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum IssueType {
    /// Invalid JSON syntax on a line
    JsonSyntax,
    /// Line is valid JSON but missing the "type" field
    MissingType,
    /// Line has a "type" field but value is not recognized
    UnknownType,
    /// Token used in grid but not defined in palette
    UndefinedToken,
    /// Rows in a sprite have different token counts
    RowLengthMismatch,
    /// Sprite references a palette that doesn't exist
    MissingPalette,
    /// Color value is not valid hex format
    InvalidColor,
    /// Grid dimensions don't match declared size
    SizeMismatch,
    /// Sprite has no grid rows
    EmptyGrid,
    /// Multiple objects with the same name
    DuplicateName,
}

impl std::fmt::Display for IssueType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            IssueType::JsonSyntax => write!(f, "json_syntax"),
            IssueType::MissingType => write!(f, "missing_type"),
            IssueType::UnknownType => write!(f, "unknown_type"),
            IssueType::UndefinedToken => write!(f, "undefined_token"),
            IssueType::RowLengthMismatch => write!(f, "row_length"),
            IssueType::MissingPalette => write!(f, "missing_palette"),
            IssueType::InvalidColor => write!(f, "invalid_color"),
            IssueType::SizeMismatch => write!(f, "size_mismatch"),
            IssueType::EmptyGrid => write!(f, "empty_grid"),
            IssueType::DuplicateName => write!(f, "duplicate_name"),
        }
    }
}

/// A validation issue found in the input
#[derive(Debug, Clone)]
pub struct ValidationIssue {
    /// Line number (1-indexed) where the issue was found
    pub line: usize,
    /// Severity of the issue
    pub severity: Severity,
    /// Type of issue
    pub issue_type: IssueType,
    /// Human-readable message describing the issue
    pub message: String,
    /// Optional suggestion for fixing the issue (e.g., "did you mean?")
    pub suggestion: Option<String>,
    /// Additional context (e.g., sprite name, palette name)
    pub context: Option<String>,
}

impl ValidationIssue {
    /// Create a new error
    pub fn error(line: usize, issue_type: IssueType, message: impl Into<String>) -> Self {
        Self {
            line,
            severity: Severity::Error,
            issue_type,
            message: message.into(),
            suggestion: None,
            context: None,
        }
    }

    /// Create a new warning
    pub fn warning(line: usize, issue_type: IssueType, message: impl Into<String>) -> Self {
        Self {
            line,
            severity: Severity::Warning,
            issue_type,
            message: message.into(),
            suggestion: None,
            context: None,
        }
    }

    /// Add a suggestion to this issue
    pub fn with_suggestion(mut self, suggestion: impl Into<String>) -> Self {
        self.suggestion = Some(suggestion.into());
        self
    }

    /// Add context to this issue
    pub fn with_context(mut self, context: impl Into<String>) -> Self {
        self.context = Some(context.into());
        self
    }
}

/// Validator for Pixelsrc files
pub struct Validator {
    /// Collected validation issues
    issues: Vec<ValidationIssue>,
    /// Known palette names -> set of defined tokens
    palettes: HashMap<String, HashSet<String>>,
    /// Built-in palette names
    builtin_palettes: HashSet<String>,
    /// Known sprite names (for duplicate detection)
    sprite_names: HashSet<String>,
    /// Known animation names
    animation_names: HashSet<String>,
    /// Known composition names
    composition_names: HashSet<String>,
    /// Known variant names
    variant_names: HashSet<String>,
    /// Known palette names (for duplicate detection)
    palette_names: HashSet<String>,
}

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

impl Validator {
    /// Create a new validator
    pub fn new() -> Self {
        // Initialize with built-in palette names
        let builtin_palettes: HashSet<String> =
            crate::palettes::list_builtins().into_iter().map(|s| format!("@{}", s)).collect();

        Self {
            issues: Vec::new(),
            palettes: HashMap::new(),
            builtin_palettes,
            sprite_names: HashSet::new(),
            animation_names: HashSet::new(),
            composition_names: HashSet::new(),
            variant_names: HashSet::new(),
            palette_names: HashSet::new(),
        }
    }

    /// Validate a single line of input
    pub fn validate_line(&mut self, line_number: usize, content: &str) {
        // Skip empty lines
        if content.trim().is_empty() {
            return;
        }

        // Check 1: JSON syntax
        let json_value: Value = match serde_json::from_str(content) {
            Ok(v) => v,
            Err(e) => {
                self.issues.push(ValidationIssue::error(
                    line_number,
                    IssueType::JsonSyntax,
                    format!("Invalid JSON: {}", e),
                ));
                return;
            }
        };

        // Check 2: Missing type field
        let obj = match json_value.as_object() {
            Some(obj) => obj,
            None => {
                self.issues.push(ValidationIssue::error(
                    line_number,
                    IssueType::JsonSyntax,
                    "Line must be a JSON object",
                ));
                return;
            }
        };

        let type_value = match obj.get("type") {
            Some(t) => t,
            None => {
                self.issues.push(ValidationIssue::error(
                    line_number,
                    IssueType::MissingType,
                    "Missing required \"type\" field",
                ));
                return;
            }
        };

        let type_str = match type_value.as_str() {
            Some(s) => s,
            None => {
                self.issues.push(ValidationIssue::error(
                    line_number,
                    IssueType::MissingType,
                    "\"type\" field must be a string",
                ));
                return;
            }
        };

        // Check 3: Unknown type
        let valid_types = ["palette", "sprite", "animation", "composition", "variant"];
        if !valid_types.contains(&type_str) {
            self.issues.push(
                ValidationIssue::warning(
                    line_number,
                    IssueType::UnknownType,
                    format!("Unknown type \"{}\"", type_str),
                )
                .with_suggestion(format!("Valid types are: {}", valid_types.join(", "))),
            );
            return;
        }

        // Now parse as TtpObject for semantic validation
        let ttp_obj: TtpObject = match serde_json::from_str(content) {
            Ok(obj) => obj,
            Err(e) => {
                // This shouldn't happen if type is valid, but handle gracefully
                self.issues.push(ValidationIssue::error(
                    line_number,
                    IssueType::JsonSyntax,
                    format!("Failed to parse {}: {}", type_str, e),
                ));
                return;
            }
        };

        // Validate based on object type
        match ttp_obj {
            TtpObject::Palette(palette) => {
                self.validate_palette(line_number, &palette.name, &palette.colors);
            }
            TtpObject::Sprite(sprite) => {
                self.validate_sprite(line_number, &sprite);
            }
            TtpObject::Animation(animation) => {
                self.validate_animation(line_number, &animation.name);
            }
            TtpObject::Composition(composition) => {
                self.validate_composition(line_number, &composition.name);
            }
            TtpObject::Variant(variant) => {
                self.validate_variant(line_number, &variant.name, &variant.palette);
            }
            TtpObject::Particle(particle) => {
                self.validate_particle(line_number, &particle);
            }
            TtpObject::Transform(transform) => {
                self.validate_transform(line_number, &transform);
            }
        }
    }

    /// Validate a user-defined transform
    fn validate_transform(&mut self, line_number: usize, transform: &crate::models::TransformDef) {
        // Check for duplicate name - transforms share namespace with other named objects
        if !self.sprite_names.insert(transform.name.clone()) {
            self.issues.push(
                ValidationIssue::warning(
                    line_number,
                    IssueType::DuplicateName,
                    format!("Duplicate transform name \"{}\"", transform.name),
                )
                .with_context(format!("transform \"{}\"", transform.name)),
            );
        }

        // Validate keyframe frames if animation
        if let Some(frames) = transform.frames {
            if frames == 0 {
                self.issues.push(
                    ValidationIssue::warning(
                        line_number,
                        IssueType::EmptyGrid,
                        "Transform has 0 frames".to_string(),
                    )
                    .with_context(format!("transform \"{}\"", transform.name)),
                );
            }
        }
    }

    /// Validate a palette definition
    fn validate_palette(
        &mut self,
        line_number: usize,
        name: &str,
        colors: &HashMap<String, String>,
    ) {
        // Check for duplicate name
        if !self.palette_names.insert(name.to_string()) {
            self.issues.push(
                ValidationIssue::warning(
                    line_number,
                    IssueType::DuplicateName,
                    format!("Duplicate palette name \"{}\"", name),
                )
                .with_context(format!("palette \"{}\"", name)),
            );
        }

        // Validate each color
        let mut defined_tokens = HashSet::new();
        for (token, color) in colors {
            defined_tokens.insert(token.clone());

            // Check color format
            if let Err(e) = parse_color(color) {
                self.issues.push(
                    ValidationIssue::error(
                        line_number,
                        IssueType::InvalidColor,
                        format!("Invalid color \"{}\" for token {}: {}", color, token, e),
                    )
                    .with_context(format!("palette \"{}\"", name)),
                );
            }
        }

        // Register palette tokens
        self.palettes.insert(name.to_string(), defined_tokens);
    }

    /// Validate a sprite definition
    fn validate_sprite(&mut self, line_number: usize, sprite: &crate::models::Sprite) {
        let name = &sprite.name;

        // Check for duplicate name
        if !self.sprite_names.insert(name.to_string()) {
            self.issues.push(
                ValidationIssue::warning(
                    line_number,
                    IssueType::DuplicateName,
                    format!("Duplicate sprite name \"{}\"", name),
                )
                .with_context(format!("sprite \"{}\"", name)),
            );
        }

        // Check for empty grid
        if sprite.grid.is_empty() {
            self.issues.push(
                ValidationIssue::warning(
                    line_number,
                    IssueType::EmptyGrid,
                    format!("Sprite \"{}\" has no grid rows", name),
                )
                .with_context(format!("sprite \"{}\"", name)),
            );
            return;
        }

        // Get palette tokens
        let palette_tokens = self.get_palette_tokens(&sprite.palette, line_number, name);

        // Validate grid rows
        let mut first_row_count: Option<usize> = None;
        let mut all_tokens_used: HashSet<String> = HashSet::new();

        for (row_idx, row) in sprite.grid.iter().enumerate() {
            let (tokens, _warnings) = tokenize(row);

            // Check row length consistency
            match first_row_count {
                None => first_row_count = Some(tokens.len()),
                Some(expected) if tokens.len() != expected => {
                    let actual = tokens.len();
                    let message = format!(
                        "Row {} length mismatch: expected {} tokens, found {}",
                        row_idx + 1,
                        expected,
                        actual
                    );

                    let mut issue = ValidationIssue::warning(
                        line_number,
                        IssueType::RowLengthMismatch,
                        message,
                    )
                    .with_context(format!("sprite \"{}\"", name));

                    // Add padding suggestion for short rows
                    if actual < expected {
                        let padding_needed = expected - actual;
                        let padding = "{_}".repeat(padding_needed);
                        issue = issue.with_suggestion(format!(
                            "add {} padding token{}: {}",
                            padding_needed,
                            if padding_needed == 1 { "" } else { "s" },
                            padding
                        ));
                    }

                    self.issues.push(issue);
                }
                _ => {}
            }

            // Collect all tokens used
            for token in tokens {
                all_tokens_used.insert(token);
            }
        }

        // Check size mismatch
        if let Some(declared_size) = sprite.size {
            let actual_width = first_row_count.unwrap_or(0) as u32;
            let actual_height = sprite.grid.len() as u32;

            if declared_size[0] != actual_width || declared_size[1] != actual_height {
                self.issues.push(
                    ValidationIssue::warning(
                        line_number,
                        IssueType::SizeMismatch,
                        format!(
                            "Declared size [{}x{}] doesn't match grid [{}x{}]",
                            declared_size[0], declared_size[1], actual_width, actual_height
                        ),
                    )
                    .with_context(format!("sprite \"{}\"", name)),
                );
            }
        }

        // Check for undefined tokens (only if we have palette info)
        if let Some(ref defined_tokens) = palette_tokens {
            for token in &all_tokens_used {
                if !defined_tokens.contains(token) {
                    let mut issue = ValidationIssue::warning(
                        line_number,
                        IssueType::UndefinedToken,
                        format!("Undefined token {}", token),
                    )
                    .with_context(format!("sprite \"{}\"", name));

                    // Try to suggest a correction
                    let known: Vec<&str> = defined_tokens.iter().map(|s| s.as_str()).collect();
                    if let Some(suggestion) = suggest_token(token, &known) {
                        issue = issue.with_suggestion(format!("did you mean {}?", suggestion));
                    }

                    self.issues.push(issue);
                }
            }
        }
    }

    /// Get tokens defined in a palette reference
    fn get_palette_tokens(
        &mut self,
        palette_ref: &PaletteRef,
        line_number: usize,
        sprite_name: &str,
    ) -> Option<HashSet<String>> {
        match palette_ref {
            PaletteRef::Named(name) => {
                // Check for @include: syntax
                if name.starts_with("@include:") {
                    // Include files are not validated here
                    return None;
                }

                // Check for built-in palettes
                if self.builtin_palettes.contains(name) {
                    // Get tokens from built-in palette
                    let palette_name = name.strip_prefix('@').unwrap_or(name);
                    if let Some(palette) = crate::palettes::get_builtin(palette_name) {
                        return Some(palette.colors.keys().cloned().collect());
                    }
                    return None;
                }

                // Check if palette is defined
                if let Some(tokens) = self.palettes.get(name) {
                    return Some(tokens.clone());
                }

                // Palette not found
                self.issues.push(
                    ValidationIssue::warning(
                        line_number,
                        IssueType::MissingPalette,
                        format!("Palette \"{}\" not defined", name),
                    )
                    .with_context(format!("sprite \"{}\"", sprite_name)),
                );
                None
            }
            PaletteRef::Inline(colors) => {
                // Validate inline palette colors
                for (token, color) in colors {
                    if let Err(e) = parse_color(color) {
                        self.issues.push(
                            ValidationIssue::error(
                                line_number,
                                IssueType::InvalidColor,
                                format!("Invalid color \"{}\" for token {}: {}", color, token, e),
                            )
                            .with_context(format!("sprite \"{}\" inline palette", sprite_name)),
                        );
                    }
                }
                Some(colors.keys().cloned().collect())
            }
        }
    }

    /// Validate an animation definition
    fn validate_animation(&mut self, line_number: usize, name: &str) {
        // Check for duplicate name
        if !self.animation_names.insert(name.to_string()) {
            self.issues.push(
                ValidationIssue::warning(
                    line_number,
                    IssueType::DuplicateName,
                    format!("Duplicate animation name \"{}\"", name),
                )
                .with_context(format!("animation \"{}\"", name)),
            );
        }
    }

    /// Validate a composition definition
    fn validate_composition(&mut self, line_number: usize, name: &str) {
        // Check for duplicate name
        if !self.composition_names.insert(name.to_string()) {
            self.issues.push(
                ValidationIssue::warning(
                    line_number,
                    IssueType::DuplicateName,
                    format!("Duplicate composition name \"{}\"", name),
                )
                .with_context(format!("composition \"{}\"", name)),
            );
        }
    }

    /// Validate a variant definition
    fn validate_variant(
        &mut self,
        line_number: usize,
        name: &str,
        palette: &HashMap<String, String>,
    ) {
        // Check for duplicate name
        if !self.variant_names.insert(name.to_string()) {
            self.issues.push(
                ValidationIssue::warning(
                    line_number,
                    IssueType::DuplicateName,
                    format!("Duplicate variant name \"{}\"", name),
                )
                .with_context(format!("variant \"{}\"", name)),
            );
        }

        // Validate palette override colors
        for (token, color) in palette {
            if let Err(e) = parse_color(color) {
                self.issues.push(
                    ValidationIssue::error(
                        line_number,
                        IssueType::InvalidColor,
                        format!("Invalid color \"{}\" for token {}: {}", color, token, e),
                    )
                    .with_context(format!("variant \"{}\"", name)),
                );
            }
        }
    }

    /// Validate a particle system definition
    fn validate_particle(&mut self, line_number: usize, particle: &Particle) {
        // Check for empty name
        if particle.name.is_empty() {
            self.issues.push(
                ValidationIssue::error(
                    line_number,
                    IssueType::DuplicateName, // Reusing for empty name validation
                    "Particle system has empty name".to_string(),
                )
                .with_context("particle".to_string()),
            );
        }

        // Check for empty sprite reference
        if particle.sprite.is_empty() {
            self.issues.push(
                ValidationIssue::error(
                    line_number,
                    IssueType::MissingPalette, // Reusing for missing sprite reference
                    "Particle system has empty sprite reference".to_string(),
                )
                .with_context(format!("particle \"{}\"", particle.name)),
            );
        }

        // Validate emitter lifetime range
        if particle.emitter.lifetime[0] > particle.emitter.lifetime[1] {
            self.issues.push(
                ValidationIssue::warning(
                    line_number,
                    IssueType::SizeMismatch, // Reusing for range validation
                    format!(
                        "Particle lifetime min ({}) > max ({})",
                        particle.emitter.lifetime[0], particle.emitter.lifetime[1]
                    ),
                )
                .with_context(format!("particle \"{}\"", particle.name)),
            );
        }
    }

    /// Validate a file
    pub fn validate_file(&mut self, path: &Path) -> Result<(), std::io::Error> {
        let file = File::open(path)?;
        let reader = BufReader::new(file);

        for (line_idx, line_result) in reader.lines().enumerate() {
            let line_number = line_idx + 1;
            match line_result {
                Ok(line) => self.validate_line(line_number, &line),
                Err(e) => {
                    self.issues.push(ValidationIssue::error(
                        line_number,
                        IssueType::JsonSyntax,
                        format!("IO error reading line: {}", e),
                    ));
                }
            }
        }

        Ok(())
    }

    /// Get all collected issues
    pub fn issues(&self) -> &[ValidationIssue] {
        &self.issues
    }

    /// Consume the validator and return all issues
    pub fn into_issues(self) -> Vec<ValidationIssue> {
        self.issues
    }

    /// Check if there are any errors
    pub fn has_errors(&self) -> bool {
        self.issues.iter().any(|i| matches!(i.severity, Severity::Error))
    }

    /// Check if there are any warnings
    pub fn has_warnings(&self) -> bool {
        self.issues.iter().any(|i| matches!(i.severity, Severity::Warning))
    }

    /// Count errors
    pub fn error_count(&self) -> usize {
        self.issues.iter().filter(|i| matches!(i.severity, Severity::Error)).count()
    }

    /// Count warnings
    pub fn warning_count(&self) -> usize {
        self.issues.iter().filter(|i| matches!(i.severity, Severity::Warning)).count()
    }
}

/// Suggest a similar token using Levenshtein distance
pub fn suggest_token(unknown: &str, known: &[&str]) -> Option<String> {
    // Only consider tokens with distance <= 2
    const MAX_DISTANCE: usize = 2;

    let mut best_match: Option<(&str, usize)> = None;

    for candidate in known {
        let distance = levenshtein_distance(unknown, candidate);
        if distance <= MAX_DISTANCE {
            match best_match {
                None => best_match = Some((candidate, distance)),
                Some((_, best_dist)) if distance < best_dist => {
                    best_match = Some((candidate, distance))
                }
                _ => {}
            }
        }
    }

    best_match.map(|(s, _)| s.to_string())
}

/// Calculate Levenshtein distance between two strings
fn levenshtein_distance(a: &str, b: &str) -> usize {
    let a_chars: Vec<char> = a.chars().collect();
    let b_chars: Vec<char> = b.chars().collect();
    let a_len = a_chars.len();
    let b_len = b_chars.len();

    // Quick checks
    if a_len == 0 {
        return b_len;
    }
    if b_len == 0 {
        return a_len;
    }

    // DP table
    let mut dp = vec![vec![0usize; b_len + 1]; a_len + 1];

    // Initialize base cases
    for i in 0..=a_len {
        dp[i][0] = i;
    }
    for j in 0..=b_len {
        dp[0][j] = j;
    }

    // Fill table
    for i in 1..=a_len {
        for j in 1..=b_len {
            let cost = if a_chars[i - 1] == b_chars[j - 1] { 0 } else { 1 };
            dp[i][j] = (dp[i - 1][j] + 1) // deletion
                .min(dp[i][j - 1] + 1) // insertion
                .min(dp[i - 1][j - 1] + cost); // substitution
        }
    }

    dp[a_len][b_len]
}

#[cfg(test)]
mod tests {
    use super::*;
    use serial_test::serial;

    #[test]
    fn test_levenshtein_identical() {
        assert_eq!(levenshtein_distance("test", "test"), 0);
        assert_eq!(levenshtein_distance("{skin}", "{skin}"), 0);
    }

    #[test]
    fn test_levenshtein_one_char_diff() {
        assert_eq!(levenshtein_distance("{skni}", "{skin}"), 2); // transposition = 2 ops
        assert_eq!(levenshtein_distance("{hiar}", "{hair}"), 2); // transposition = 2 ops
        assert_eq!(levenshtein_distance("{skinx}", "{skin}"), 1); // deletion
        assert_eq!(levenshtein_distance("{skin}", "{skinx}"), 1); // insertion
    }

    #[test]
    fn test_levenshtein_distant() {
        assert!(levenshtein_distance("{xyz}", "{abc}") > 2);
        assert!(levenshtein_distance("{completely}", "{different}") > 2);
    }

    #[test]
    fn test_suggest_token_typo() {
        let known = vec!["{skin}", "{hair}", "{outline}"];
        assert_eq!(suggest_token("{skni}", &known), Some("{skin}".to_string()));
        assert_eq!(suggest_token("{hiar}", &known), Some("{hair}".to_string()));
    }

    #[test]
    fn test_suggest_token_no_match() {
        let known = vec!["{skin}", "{hair}"];
        assert_eq!(suggest_token("{xyz123456}", &known), None);
    }

    #[test]
    fn test_validate_valid_json() {
        let mut validator = Validator::new();
        validator.validate_line(
            1,
            r##"{"type": "palette", "name": "test", "colors": {"{a}": "#FF0000"}}"##,
        );
        assert!(validator.issues().is_empty());
    }

    #[test]
    fn test_validate_invalid_json() {
        let mut validator = Validator::new();
        validator.validate_line(1, "{not valid json}");
        assert_eq!(validator.issues().len(), 1);
        assert_eq!(validator.issues()[0].issue_type, IssueType::JsonSyntax);
        assert!(validator.has_errors());
    }

    #[test]
    fn test_validate_missing_type() {
        let mut validator = Validator::new();
        validator.validate_line(1, r#"{"name": "test"}"#);
        assert_eq!(validator.issues().len(), 1);
        assert_eq!(validator.issues()[0].issue_type, IssueType::MissingType);
    }

    #[test]
    fn test_validate_unknown_type() {
        let mut validator = Validator::new();
        validator.validate_line(1, r#"{"type": "unknown", "name": "test"}"#);
        assert_eq!(validator.issues().len(), 1);
        assert_eq!(validator.issues()[0].issue_type, IssueType::UnknownType);
        assert!(validator.has_warnings());
    }

    #[test]
    fn test_validate_invalid_color() {
        let mut validator = Validator::new();
        validator.validate_line(
            1,
            r##"{"type": "palette", "name": "test", "colors": {"{a}": "#GGG"}}"##,
        );
        assert_eq!(validator.issues().len(), 1);
        assert_eq!(validator.issues()[0].issue_type, IssueType::InvalidColor);
    }

    #[test]
    fn test_validate_undefined_token() {
        let mut validator = Validator::new();
        // First define a palette
        validator.validate_line(
            1,
            r##"{"type": "palette", "name": "test", "colors": {"{a}": "#FF0000"}}"##,
        );
        // Then a sprite using undefined token
        validator.validate_line(
            2,
            r#"{"type": "sprite", "name": "test", "palette": "test", "grid": ["{a}{b}"]}"#,
        );
        assert_eq!(validator.issues().len(), 1);
        assert_eq!(validator.issues()[0].issue_type, IssueType::UndefinedToken);
        assert_eq!(validator.issues()[0].line, 2);
    }

    #[test]
    fn test_validate_row_length_mismatch() {
        let mut validator = Validator::new();
        validator.validate_line(
            1,
            r##"{"type": "palette", "name": "test", "colors": {"{a}": "#FF0000"}}"##,
        );
        validator.validate_line(
            2,
            r#"{"type": "sprite", "name": "test", "palette": "test", "grid": ["{a}{a}{a}{a}", "{a}{a}{a}"]}"#,
        );

        let row_mismatch_issues: Vec<_> = validator
            .issues()
            .iter()
            .filter(|i| i.issue_type == IssueType::RowLengthMismatch)
            .collect();
        assert_eq!(row_mismatch_issues.len(), 1);
    }

    #[test]
    fn test_row_length_message_format() {
        let mut validator = Validator::new();
        validator.validate_line(
            1,
            r##"{"type": "palette", "name": "test", "colors": {"{a}": "#FF0000"}}"##,
        );
        validator.validate_line(
            2,
            r#"{"type": "sprite", "name": "test", "palette": "test", "grid": ["{a}{a}{a}{a}", "{a}{a}"]}"#,
        );

        let row_mismatch_issues: Vec<_> = validator
            .issues()
            .iter()
            .filter(|i| i.issue_type == IssueType::RowLengthMismatch)
            .collect();
        assert_eq!(row_mismatch_issues.len(), 1);

        let issue = row_mismatch_issues[0];
        // Check message format: "Row X length mismatch: expected Y tokens, found Z"
        assert!(
            issue.message.contains("expected 4 tokens"),
            "Message should contain 'expected 4 tokens': {}",
            issue.message
        );
        assert!(
            issue.message.contains("found 2"),
            "Message should contain 'found 2': {}",
            issue.message
        );
    }

    #[test]
    fn test_row_length_padding_suggestion() {
        let mut validator = Validator::new();
        validator.validate_line(
            1,
            r##"{"type": "palette", "name": "test", "colors": {"{a}": "#FF0000"}}"##,
        );
        validator.validate_line(
            2,
            r#"{"type": "sprite", "name": "test", "palette": "test", "grid": ["{a}{a}{a}{a}", "{a}"]}"#,
        );

        let row_mismatch_issues: Vec<_> = validator
            .issues()
            .iter()
            .filter(|i| i.issue_type == IssueType::RowLengthMismatch)
            .collect();
        assert_eq!(row_mismatch_issues.len(), 1);

        let issue = row_mismatch_issues[0];
        // Check padding suggestion for short row (1 token vs expected 4)
        assert!(issue.suggestion.is_some(), "Short row should have padding suggestion");
        let suggestion = issue.suggestion.as_ref().unwrap();
        assert!(
            suggestion.contains("{_}{_}{_}"),
            "Should suggest 3 padding tokens: {}",
            suggestion
        );
        assert!(
            suggestion.contains("add 3 padding tokens"),
            "Should mention adding 3 tokens: {}",
            suggestion
        );
    }

    #[test]
    fn test_row_length_single_padding_suggestion() {
        let mut validator = Validator::new();
        validator.validate_line(
            1,
            r##"{"type": "palette", "name": "test", "colors": {"{a}": "#FF0000"}}"##,
        );
        validator.validate_line(
            2,
            r#"{"type": "sprite", "name": "test", "palette": "test", "grid": ["{a}{a}", "{a}"]}"#,
        );

        let row_mismatch_issues: Vec<_> = validator
            .issues()
            .iter()
            .filter(|i| i.issue_type == IssueType::RowLengthMismatch)
            .collect();
        assert_eq!(row_mismatch_issues.len(), 1);

        let issue = row_mismatch_issues[0];
        let suggestion = issue.suggestion.as_ref().unwrap();
        // Should say "token" (singular) not "tokens"
        assert!(
            suggestion.contains("add 1 padding token:"),
            "Should use singular 'token': {}",
            suggestion
        );
    }

    #[test]
    fn test_row_length_no_padding_for_long_rows() {
        let mut validator = Validator::new();
        validator.validate_line(
            1,
            r##"{"type": "palette", "name": "test", "colors": {"{a}": "#FF0000"}}"##,
        );
        // Row 2 is LONGER than row 1 (5 tokens vs 3)
        validator.validate_line(
            2,
            r#"{"type": "sprite", "name": "test", "palette": "test", "grid": ["{a}{a}{a}", "{a}{a}{a}{a}{a}"]}"#,
        );

        let row_mismatch_issues: Vec<_> = validator
            .issues()
            .iter()
            .filter(|i| i.issue_type == IssueType::RowLengthMismatch)
            .collect();
        assert_eq!(row_mismatch_issues.len(), 1);

        let issue = row_mismatch_issues[0];
        // Long rows should NOT have padding suggestion (can't "pad" to make shorter)
        assert!(
            issue.suggestion.is_none(),
            "Long rows should not have padding suggestion, but got: {:?}",
            issue.suggestion
        );
    }

    #[test]
    fn test_validate_size_mismatch() {
        let mut validator = Validator::new();
        validator.validate_line(
            1,
            r##"{"type": "palette", "name": "test", "colors": {"{a}": "#FF0000"}}"##,
        );
        validator.validate_line(
            2,
            r#"{"type": "sprite", "name": "test", "size": [10, 10], "palette": "test", "grid": ["{a}{a}"]}"#,
        );

        let size_mismatch_issues: Vec<_> =
            validator.issues().iter().filter(|i| i.issue_type == IssueType::SizeMismatch).collect();
        assert_eq!(size_mismatch_issues.len(), 1);
    }

    #[test]
    fn test_validate_empty_grid() {
        let mut validator = Validator::new();
        validator.validate_line(
            1,
            r##"{"type": "palette", "name": "test", "colors": {"{a}": "#FF0000"}}"##,
        );
        validator.validate_line(
            2,
            r#"{"type": "sprite", "name": "test", "palette": "test", "grid": []}"#,
        );

        let empty_grid_issues: Vec<_> =
            validator.issues().iter().filter(|i| i.issue_type == IssueType::EmptyGrid).collect();
        assert_eq!(empty_grid_issues.len(), 1);
    }

    #[test]
    fn test_validate_duplicate_name() {
        let mut validator = Validator::new();
        validator.validate_line(
            1,
            r##"{"type": "palette", "name": "test", "colors": {"{a}": "#FF0000"}}"##,
        );
        validator.validate_line(
            2,
            r##"{"type": "palette", "name": "test", "colors": {"{b}": "#00FF00"}}"##,
        );

        let duplicate_issues: Vec<_> = validator
            .issues()
            .iter()
            .filter(|i| i.issue_type == IssueType::DuplicateName)
            .collect();
        assert_eq!(duplicate_issues.len(), 1);
    }

    #[test]
    fn test_validate_missing_palette() {
        let mut validator = Validator::new();
        validator.validate_line(
            1,
            r#"{"type": "sprite", "name": "test", "palette": "nonexistent", "grid": ["{a}"]}"#,
        );

        let missing_palette_issues: Vec<_> = validator
            .issues()
            .iter()
            .filter(|i| i.issue_type == IssueType::MissingPalette)
            .collect();
        assert_eq!(missing_palette_issues.len(), 1);
    }

    #[test]
    fn test_validate_inline_palette() {
        let mut validator = Validator::new();
        validator.validate_line(
            1,
            r##"{"type": "sprite", "name": "test", "palette": {"{a}": "#FF0000"}, "grid": ["{a}"]}"##,
        );
        assert!(validator.issues().is_empty());
    }

    #[test]
    fn test_validate_inline_palette_invalid_color() {
        let mut validator = Validator::new();
        validator.validate_line(
            1,
            r##"{"type": "sprite", "name": "test", "palette": {"{a}": "#INVALID"}, "grid": ["{a}"]}"##,
        );
        assert_eq!(validator.issues().len(), 1);
        assert_eq!(validator.issues()[0].issue_type, IssueType::InvalidColor);
    }

    #[test]
    #[serial]
    fn test_validate_file_errors() {
        use std::path::Path;

        let fixture_path = Path::new("tests/fixtures/invalid/validate_errors.jsonl");
        if !fixture_path.exists() {
            return; // Skip if fixture not available
        }

        let mut validator = Validator::new();
        validator.validate_file(fixture_path).unwrap();

        // Should have warnings for undefined token {b} and row length mismatch
        let undefined_token_issues: Vec<_> = validator
            .issues()
            .iter()
            .filter(|i| i.issue_type == IssueType::UndefinedToken)
            .collect();
        assert!(!undefined_token_issues.is_empty(), "Expected undefined token warning for {{b}}");

        let row_mismatch_issues: Vec<_> = validator
            .issues()
            .iter()
            .filter(|i| i.issue_type == IssueType::RowLengthMismatch)
            .collect();
        assert!(!row_mismatch_issues.is_empty(), "Expected row length mismatch warning");
    }

    #[test]
    #[serial]
    fn test_validate_file_typos() {
        use std::path::Path;

        let fixture_path = Path::new("tests/fixtures/invalid/validate_typo.jsonl");
        if !fixture_path.exists() {
            return; // Skip if fixture not available
        }

        let mut validator = Validator::new();
        validator.validate_file(fixture_path).unwrap();

        // Should have warnings for undefined tokens with suggestions
        let undefined_token_issues: Vec<_> = validator
            .issues()
            .iter()
            .filter(|i| i.issue_type == IssueType::UndefinedToken)
            .collect();

        // Should find {skni} and {hiar} as undefined
        assert_eq!(undefined_token_issues.len(), 2, "Expected 2 undefined token warnings");

        // Check that suggestions are provided
        let has_skin_suggestion = undefined_token_issues
            .iter()
            .any(|i| i.suggestion.as_ref().is_some_and(|s| s.contains("{skin}")));
        let has_hair_suggestion = undefined_token_issues
            .iter()
            .any(|i| i.suggestion.as_ref().is_some_and(|s| s.contains("{hair}")));

        assert!(has_skin_suggestion, "Expected suggestion for {{skin}}");
        assert!(has_hair_suggestion, "Expected suggestion for {{hair}}");
    }
}