windjammer 0.48.0

A simple language inspired by Go, Ruby, and Elixir that transpiles to Rust - 80% of Rust's power with 20% of the complexity
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
/// Error Mapper: Translates Rust compiler errors back to Windjammer source locations
///
/// This module intercepts rustc JSON output, maps errors using source maps,
/// and provides a world-class error experience for Windjammer developers.
#[cfg(feature = "cli")]
use crate::error::suggest_fix;
use crate::error_codes;
use crate::fuzzy_matcher::levenshtein_distance;
use crate::source_map::{Location, SourceMap};
use crate::syntax_highlighter::SyntaxHighlighter;
use serde::{Deserialize, Serialize};
use std::path::PathBuf;

// ============================================================================
// CARGO JSON OUTPUT STRUCTURES
// ============================================================================

/// Cargo message wrapper (from --message-format=json)
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct CargoMessage {
    /// Message reason (e.g., "compiler-message", "compiler-artifact")
    pub reason: String,
    /// Compiler diagnostic (if reason is "compiler-message")
    pub message: Option<RustcDiagnostic>,
}

// ============================================================================
// RUSTC JSON OUTPUT STRUCTURES
// ============================================================================

/// Rustc diagnostic message (from --error-format=json)
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct RustcDiagnostic {
    /// Error message text
    pub message: String,
    /// Severity level (error, warning, note, help)
    pub level: String,
    /// Primary code span (file, line, column)
    pub spans: Vec<RustcSpan>,
    /// Error code (e.g., "E0308")
    pub code: Option<RustcCode>,
    /// Child diagnostics (notes, help messages)
    pub children: Vec<RustcDiagnostic>,
    /// Rendered text (for fallback display)
    pub rendered: Option<String>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct RustcSpan {
    /// File path
    pub file_name: String,
    /// Line number (1-indexed)
    pub line_start: usize,
    pub line_end: usize,
    /// Column number (1-indexed)
    pub column_start: usize,
    pub column_end: usize,
    /// Whether this is the primary span
    pub is_primary: bool,
    /// Label text for this span
    pub label: Option<String>,
    /// Suggested replacement (for fix suggestions)
    pub suggested_replacement: Option<String>,
    /// Text content of the span (lines of source code)
    pub text: Option<Vec<RustcSpanText>>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct RustcSpanText {
    /// Text content
    pub text: String,
    /// Whether this line is highlighted
    pub highlight_start: usize,
    pub highlight_end: usize,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct RustcCode {
    /// Error code (e.g., "E0308")
    pub code: String,
    /// Explanation text
    pub explanation: Option<String>,
}

// ============================================================================
// WINDJAMMER DIAGNOSTIC STRUCTURES
// ============================================================================

/// Windjammer diagnostic message (mapped from Rust)
#[derive(Debug, Clone)]
pub struct WindjammerDiagnostic {
    /// Error message (translated to Windjammer terminology)
    pub message: String,
    /// Severity level
    pub level: DiagnosticLevel,
    /// Primary location in Windjammer source
    pub location: Location,
    /// Additional spans (for multi-location errors)
    pub spans: Vec<DiagnosticSpan>,
    /// Error code (if applicable)
    pub code: Option<String>,
    /// Help messages
    pub help: Vec<String>,
    /// Notes
    pub notes: Vec<String>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DiagnosticLevel {
    Error,
    Warning,
    Note,
    Help,
}

#[derive(Debug, Clone)]
pub struct DiagnosticSpan {
    /// Location in Windjammer source
    pub location: Location,
    /// Label for this span
    pub label: Option<String>,
    /// Whether this is the primary span
    pub is_primary: bool,
}

// ============================================================================
// ERROR MAPPER
// ============================================================================

pub struct ErrorMapper {
    source_map: SourceMap,
}

impl ErrorMapper {
    /// Create a new error mapper with the given source map
    pub fn new(source_map: SourceMap) -> Self {
        Self { source_map }
    }

    /// Parse rustc JSON output and map errors to Windjammer source
    pub fn map_rustc_output(&self, json_output: &str) -> Vec<WindjammerDiagnostic> {
        let mut diagnostics = Vec::new();

        for line in json_output.lines() {
            if line.trim().is_empty() {
                continue;
            }

            // Parse CargoMessage first
            if let Ok(cargo_msg) = serde_json::from_str::<CargoMessage>(line) {
                // Only process compiler messages
                if cargo_msg.reason == "compiler-message" {
                    if let Some(rustc_diag) = cargo_msg.message {
                        // Only process errors and warnings
                        if rustc_diag.level == "error" || rustc_diag.level == "warning" {
                            if let Some(wj_diag) = self.map_diagnostic(&rustc_diag) {
                                diagnostics.push(wj_diag);
                            }
                        }
                    }
                }
            }
        }

        diagnostics
    }

    /// Map a single rustc diagnostic to Windjammer
    fn map_diagnostic(&self, rustc_diag: &RustcDiagnostic) -> Option<WindjammerDiagnostic> {
        // Find the primary span
        let primary_span = rustc_diag.spans.iter().find(|s| s.is_primary)?;

        // Map Rust location to Windjammer location
        let rust_location = Location {
            file: PathBuf::from(&primary_span.file_name),
            line: primary_span.line_start,
            column: primary_span.column_start,
        };

        // Try to map to Windjammer location, fallback to Rust location if no mapping exists
        let wj_location = self
            .source_map
            .map_rust_to_windjammer(&rust_location)
            .unwrap_or_else(|| {
                // No mapping found - use Rust location but try to infer Windjammer file
                // by looking for any mapping from this Rust file
                let wj_file = self
                    .source_map
                    .mappings_for_rust_file(&rust_location.file)
                    .first()
                    .map(|m| m.wj_file.clone())
                    .unwrap_or_else(|| {
                        // Last resort: convert .rs to .wj
                        let mut wj_path = rust_location.file.clone();
                        wj_path.set_extension("wj");
                        wj_path
                    });

                Location {
                    file: wj_file,
                    line: rust_location.line,
                    column: rust_location.column,
                }
            });

        // Translate error message (use span labels for richer context, e.g. type mismatch)
        let message =
            self.translate_message_with_context(&rustc_diag.message, primary_span.label.as_deref());

        // Map additional spans
        let spans = rustc_diag
            .spans
            .iter()
            .filter_map(|span| self.map_span(span))
            .collect();

        // Extract help and notes from children
        let mut help = Vec::new();
        let mut notes = Vec::new();

        for child in &rustc_diag.children {
            match child.level.as_str() {
                "help" => help.push(child.message.clone()),
                "note" => notes.push(child.message.clone()),
                _ => {}
            }
        }

        // Add "did you mean?" for field typos when we have "no field X" and notes list fields
        if message.contains("No field `") && !notes.is_empty() {
            if let Some(field_name) = self.extract_between(&message, "No field `", "`") {
                for note in &notes {
                    if note.contains("has fields") {
                        let fields = Self::parse_struct_fields_from_note(note);
                        if let Some(suggestion) = Self::fuzzy_match_field(&field_name, &fields) {
                            help.push(format!("did you mean `{}`?", suggestion));
                            break;
                        }
                    }
                }
            }
        }

        // Map Rust error code to Windjammer error code
        let wj_code = rustc_diag.code.as_ref().and_then(|c| {
            let registry = error_codes::get_registry();
            registry.map_rust_code(&c.code).map(|wj| wj.code.clone())
        });

        // Add suggestion from suggest_fix when we have an error code but no help
        #[cfg(feature = "cli")]
        if help.is_empty() {
            if let Some(code) = rustc_diag.code.as_ref().map(|c| c.code.as_str()) {
                if let Some(suggestion) = suggest_fix(code, &message) {
                    help.push(suggestion);
                }
            }
        }

        Some(WindjammerDiagnostic {
            message,
            level: match rustc_diag.level.as_str() {
                "error" => DiagnosticLevel::Error,
                "warning" => DiagnosticLevel::Warning,
                "note" => DiagnosticLevel::Note,
                "help" => DiagnosticLevel::Help,
                _ => DiagnosticLevel::Error,
            },
            location: wj_location,
            spans,
            code: wj_code.or_else(|| rustc_diag.code.as_ref().map(|c| c.code.clone())),
            help,
            notes,
        })
    }

    /// Map a rustc span to a Windjammer span
    fn map_span(&self, span: &RustcSpan) -> Option<DiagnosticSpan> {
        let rust_location = Location {
            file: PathBuf::from(&span.file_name),
            line: span.line_start,
            column: span.column_start,
        };

        let wj_location = self.source_map.map_rust_to_windjammer(&rust_location)?;

        Some(DiagnosticSpan {
            location: wj_location,
            label: span.label.clone(),
            is_primary: span.is_primary,
        })
    }

    /// Translate Rust error messages to Windjammer terminology (used by tests)
    #[allow(dead_code)]
    fn translate_message(&self, rust_msg: &str) -> String {
        self.translate_message_with_context(rust_msg, None)
    }

    /// Translate with optional span label context (for richer type/field info)
    fn translate_message_with_context(&self, rust_msg: &str, span_label: Option<&str>) -> String {
        // Pattern matching for common Rust error patterns
        // Translate to Windjammer-friendly terminology

        // Type errors - span label often has "expected X, found Y"
        if rust_msg.contains("mismatched types") {
            let context = span_label.unwrap_or(rust_msg);
            return self.translate_type_mismatch(context);
        }

        if rust_msg.contains("cannot find type") {
            return self.translate_type_not_found(rust_msg);
        }

        if rust_msg.contains("cannot find value") || rust_msg.contains("cannot find function") {
            return self.translate_value_not_found(rust_msg);
        }

        // Struct field errors - "no field X on type Y"
        if rust_msg.contains("no field") && rust_msg.contains("on type") {
            return self.translate_missing_field(rust_msg, span_label);
        }

        // Ownership errors - include value name when available
        if rust_msg.contains("cannot move out of") {
            if let Some(name) = self.extract_between(rust_msg, "cannot move out of `", "`") {
                return format!(
                    "Cannot move `{}` because it is borrowed. Consider using .clone() to create a copy.",
                    name
                );
            }
            return "Ownership error: Cannot move value because it is borrowed. Consider using .clone()".to_string();
        }

        if rust_msg.contains("cannot borrow") && rust_msg.contains("as mutable") {
            return "Cannot modify: This value is not declared as mutable. Add `mut`: let mut x = ...".to_string();
        }

        if rust_msg.contains("use of moved value") {
            if let Some(name) = self.extract_between(rust_msg, "use of moved value: `", "`") {
                return format!(
                    "Cannot use `{}` because it was already moved. Consider cloning before the move: {}.clone()",
                    name, name
                );
            }
            return "Ownership error: This value was already used and cannot be used again. Consider cloning: value.clone()".to_string();
        }

        // Trait errors
        if rust_msg.contains("trait bounds were not satisfied") {
            return self.translate_trait_bounds(rust_msg);
        }

        if rust_msg.contains("the trait") && rust_msg.contains("is not implemented") {
            return self.translate_trait_not_implemented(rust_msg);
        }

        // Lifetime errors
        if rust_msg.contains("lifetime") {
            return self.translate_lifetime_error(rust_msg);
        }

        // Syntax errors
        if rust_msg.contains("expected") && rust_msg.contains("found") {
            return self.translate_syntax_error(rust_msg);
        }

        // Module/import errors
        if rust_msg.contains("unresolved import") {
            return "Import error: Module or item not found".to_string();
        }

        // Default: return original message
        rust_msg.to_string()
    }

    /// Translate type mismatch errors
    fn translate_type_mismatch(&self, rust_msg: &str) -> String {
        // Extract expected and found types
        if let (Some(expected), Some(found)) = (
            self.extract_between(rust_msg, "expected `", "`"),
            self.extract_between(rust_msg, "found `", "`"),
        ) {
            let expected_wj = self.rust_type_to_windjammer(&expected);
            let found_wj = self.rust_type_to_windjammer(&found);
            return format!(
                "Type mismatch: expected {}, found {}",
                expected_wj, found_wj
            );
        }

        "Type mismatch: The types don't match".to_string()
    }

    /// Translate type not found errors
    fn translate_type_not_found(&self, rust_msg: &str) -> String {
        if let Some(type_name) = self.extract_between(rust_msg, "cannot find type `", "`") {
            let wj_type = self.rust_type_to_windjammer(&type_name);
            return format!("Type not found: {}", wj_type);
        }

        "Type not found".to_string()
    }

    /// Translate value/function not found errors
    fn translate_value_not_found(&self, rust_msg: &str) -> String {
        if rust_msg.contains("cannot find function") {
            if let Some(func_name) = self.extract_between(rust_msg, "function `", "`") {
                return format!("Function not found: {}", func_name);
            }
            return "Function not found".to_string();
        }

        if let Some(value_name) = self.extract_between(rust_msg, "value `", "`") {
            return format!("Variable not found: {}", value_name);
        }

        "Value not found".to_string()
    }

    /// Translate trait bounds errors
    fn translate_trait_bounds(&self, _rust_msg: &str) -> String {
        "Trait constraint not satisfied: This type doesn't implement the required trait".to_string()
    }

    /// Translate trait not implemented errors
    fn translate_trait_not_implemented(&self, rust_msg: &str) -> String {
        let trait_name = self.extract_between(rust_msg, "trait `", "`");
        let type_name = self.extract_between(rust_msg, "for `", "`");
        match (trait_name, type_name) {
            (Some(t), Some(ty)) => format!("`{}` doesn't implement `{}`", ty, t),
            (Some(t), None) => format!("Missing trait implementation: {}", t),
            _ => "Missing trait implementation".to_string(),
        }
    }

    /// Translate "no field X on type Y" errors
    fn translate_missing_field(&self, rust_msg: &str, _span_label: Option<&str>) -> String {
        let field_name = self.extract_between(rust_msg, "no field `", "`");
        let type_name = self.extract_between(rust_msg, "on type `", "`");
        match (field_name, type_name) {
            (Some(f), Some(t)) => format!("No field `{}` on struct `{}`", f, t),
            (Some(f), None) => format!("No field `{}` on this type", f),
            _ => "Field not found".to_string(),
        }
    }

    /// Translate lifetime errors
    fn translate_lifetime_error(&self, _rust_msg: &str) -> String {
        "Lifetime error: The value doesn't live long enough".to_string()
    }

    /// Translate syntax errors
    fn translate_syntax_error(&self, rust_msg: &str) -> String {
        if let (Some(expected), Some(found)) = (
            self.extract_between(rust_msg, "expected ", ","),
            self.extract_between(rust_msg, "found ", "\n"),
        ) {
            return format!(
                "Syntax error: expected {}, found {}",
                expected.trim(),
                found.trim()
            );
        }

        "Syntax error".to_string()
    }

    /// Convert Rust type names to Windjammer type names
    fn rust_type_to_windjammer(&self, rust_type: &str) -> String {
        let mapped = crate::type_classification::rust_type_to_windjammer(rust_type);
        if mapped != rust_type {
            return mapped.to_string();
        }
        if let Some(stripped) = rust_type.strip_prefix('&') {
            return format!("&{}", self.rust_type_to_windjammer(stripped));
        }
        if rust_type.starts_with("Option<") {
            if let Some(inner) = self.extract_between(rust_type, "Option<", ">") {
                return format!("{}?", self.rust_type_to_windjammer(&inner));
            }
        }
        if rust_type.starts_with("Vec<") {
            if let Some(inner) = self.extract_between(rust_type, "Vec<", ">") {
                return format!("[{}]", self.rust_type_to_windjammer(&inner));
            }
        }
        rust_type.to_string()
    }

    /// Extract text between two delimiters
    fn extract_between(&self, text: &str, start: &str, end: &str) -> Option<String> {
        let start_idx = text.find(start)? + start.len();
        let remaining = &text[start_idx..];
        let end_idx = remaining.find(end)?;
        Some(remaining[..end_idx].to_string())
    }

    /// Parse field names from rustc note: "struct `User` has fields `username`, `name`, `email`"
    fn parse_struct_fields_from_note(note: &str) -> Vec<String> {
        let after_has_fields = note.split("has fields").nth(1).unwrap_or(note);
        let mut fields = Vec::new();
        let mut remaining = after_has_fields;
        while let Some(start) = remaining.find('`') {
            remaining = &remaining[start + 1..];
            if let Some(end) = remaining.find('`') {
                let field = remaining[..end].trim().to_string();
                if !field.is_empty() && field.chars().all(|c| c.is_alphanumeric() || c == '_') {
                    fields.push(field);
                }
                remaining = &remaining[end + 1..];
            } else {
                break;
            }
        }
        fields
    }

    /// Find best fuzzy match for a field name typo
    fn fuzzy_match_field(typo: &str, fields: &[String]) -> Option<String> {
        let mut best: Option<(String, usize)> = None;
        for field in fields {
            let d = levenshtein_distance(typo, field);
            let max_distance = std::cmp::min(3, std::cmp::max(typo.len(), field.len()) * 3 / 10);
            if d <= max_distance && d > 0 && best.as_ref().map(|(_, bd)| d < *bd).unwrap_or(true) {
                best = Some((field.clone(), d));
            }
        }
        best.map(|(s, _)| s)
    }
}

// ============================================================================
// PRETTY PRINTING
// ============================================================================

impl WindjammerDiagnostic {
    /// Check if this error is automatically fixable
    pub fn is_fixable(&self) -> bool {
        if let Some(code) = &self.code {
            matches!(code.as_str(), "E0384" | "E0308" | "E0425" | "E0596")
        } else {
            false
        }
    }

    /// Get the fix type for this error (if fixable)
    pub fn get_fix(&self) -> Option<crate::auto_fix::FixType> {
        use crate::auto_fix::FixType;

        if !self.is_fixable() {
            return None;
        }

        match self.code.as_ref()?.as_str() {
            "E0384" | "E0596" => {
                // Immutability error - suggest adding mut
                extract_variable_from_message(&self.message).map(|var_name| FixType::AddMut {
                    file: self.location.file.clone(),
                    line: self.location.line,
                    variable_name: var_name,
                })
            }
            "E0308" => {
                // Type mismatch - suggest conversion
                if self.message.contains("expected int") && self.message.contains("found string") {
                    Some(FixType::AddParse {
                        file: self.location.file.clone(),
                        line: self.location.line,
                        column: self.location.column,
                        expression: "value".to_string(),
                    })
                } else if self.message.contains("expected String")
                    && self.message.contains("found &str")
                {
                    Some(FixType::AddToString {
                        file: self.location.file.clone(),
                        line: self.location.line,
                        column: self.location.column,
                        expression: "value".to_string(),
                    })
                } else {
                    None
                }
            }
            _ => None,
        }
    }

    /// Format this diagnostic for display (Rust-style pretty printing with colors)
    pub fn format(&self) -> String {
        use colored::*;

        let mut output = String::new();

        // Level and message (with colors!)
        let level_str = match self.level {
            DiagnosticLevel::Error => "error".red().bold(),
            DiagnosticLevel::Warning => "warning".yellow().bold(),
            DiagnosticLevel::Note => "note".blue().bold(),
            DiagnosticLevel::Help => "help".cyan().bold(),
        };

        if let Some(code) = &self.code {
            // Show Windjammer code prominently if it starts with WJ
            if code.starts_with("WJ") {
                output.push_str(&format!(
                    "{}[{}]: {}\n",
                    level_str,
                    code.cyan().bold(),
                    self.message
                ));
                output.push_str(&format!("  {} wj explain {}\n", "💡".yellow(), code));
            } else {
                output.push_str(&format!("{}[{}]: {}\n", level_str, code, self.message));
            }
        } else {
            output.push_str(&format!("{}: {}\n", level_str, self.message));
        }

        // Location (cyan for visibility)
        output.push_str(&format!(
            "  {} {}:{}:{}\n",
            "-->".cyan(),
            self.location.file.display(),
            self.location.line,
            self.location.column
        ));

        // Source code snippet
        if let Ok(snippet) = self.read_source_snippet() {
            output.push_str(&snippet);
        }

        // Help messages (cyan)
        for help_msg in &self.help {
            output.push_str(&format!("  = {}: {}\n", "help".cyan(), help_msg));
        }

        // Notes (blue)
        for note in &self.notes {
            output.push_str(&format!("  = {}: {}\n", "note".blue(), note));
        }

        // Contextual help (green for suggestions)
        if let Some(contextual_help) = self.get_contextual_help() {
            output.push_str(&format!(
                "  = {}: {}\n",
                "suggestion".green().bold(),
                contextual_help
            ));
        }

        output
    }

    /// Read and format the source code snippet for this error
    fn read_source_snippet(&self) -> Result<String, std::io::Error> {
        use colored::*;
        use std::fs;

        let source = fs::read_to_string(&self.location.file)?;
        let lines: Vec<&str> = source.lines().collect();

        let mut output = String::new();
        output.push_str(&format!("   {}\n", "|".cyan()));

        // Create syntax highlighter
        let highlighter = SyntaxHighlighter::new();

        // Show context: 2 lines before, the error line, and 2 lines after
        let start_line = self.location.line.saturating_sub(2);
        let end_line = (self.location.line + 2).min(lines.len());

        for line_num in start_line..=end_line {
            if line_num == 0 || line_num > lines.len() {
                continue;
            }

            let line = lines[line_num - 1];
            let is_error_line = line_num == self.location.line;

            // Apply syntax highlighting to the line
            let highlighted_line = highlighter.highlight_line(line);

            if is_error_line {
                // Error line with pointer (red for errors, yellow for warnings)
                let pointer_color = match self.level {
                    DiagnosticLevel::Error => "^".red().bold(),
                    DiagnosticLevel::Warning => "^".yellow().bold(),
                    _ => "^".cyan(),
                };

                output.push_str(&format!(
                    "{:>4} {} {}\n",
                    line_num.to_string().cyan(),
                    "|".cyan(),
                    highlighted_line
                ));
                output.push_str(&format!(
                    "   {} {}{}\n",
                    "|".cyan(),
                    " ".repeat(self.location.column.saturating_sub(1)),
                    pointer_color
                ));
            } else {
                // Context line with syntax highlighting
                output.push_str(&format!(
                    "{:>4} {} {}\n",
                    line_num.to_string().cyan(),
                    "|".cyan(),
                    highlighted_line
                ));
            }
        }

        output.push_str(&format!("   {}\n", "|".cyan()));
        Ok(output)
    }

    /// Get Windjammer-specific contextual help based on the error message
    fn get_contextual_help(&self) -> Option<String> {
        let msg = &self.message.to_lowercase();

        // Type mismatch suggestions
        if msg.contains("type mismatch") {
            if msg.contains("expected int") && msg.contains("found string") {
                return Some(
                    "Use .parse() to convert a string to an integer, e.g., \"42\".parse()"
                        .to_string(),
                );
            }
            if msg.contains("expected string") && msg.contains("found int") {
                return Some(
                    "Use .to_string() to convert an integer to a string, e.g., 42.to_string()"
                        .to_string(),
                );
            }
            if msg.contains("expected int") && msg.contains("found float") {
                return Some(
                    "Convert to integer: use `value as int` or `value.round() as int`".to_string(),
                );
            }
            if msg.contains("expected float") && msg.contains("found int") {
                return Some(
                    "Convert to float: add .0 to literal (e.g., 3.0) or use `value as float`"
                        .to_string(),
                );
            }
            if msg.contains("expected &") {
                return Some("Add & before the value to create a reference".to_string());
            }
        }

        // Function not found
        if msg.contains("function not found") {
            return Some(
                "Check the function name spelling and ensure the module is imported".to_string(),
            );
        }

        // Variable not found
        if msg.contains("variable not found") {
            return Some(
                "Check the variable name spelling and ensure it's declared before use".to_string(),
            );
        }

        // Ownership errors - match both old and new message formats
        if msg.contains("ownership error")
            || msg.contains("cannot move")
            || msg.contains("cannot use")
            || msg.contains("already moved")
        {
            return Some(
                "Consider cloning: use value.clone() to create a copy before moving".to_string(),
            );
        }

        // Mutability errors
        if msg.contains("cannot modify") {
            return Some("Declare the variable as mutable: let mut x = ...".to_string());
        }

        // Import errors
        if msg.contains("import error") {
            return Some("Use 'use module::item' to import, or check if the module exists in your project or stdlib".to_string());
        }

        // Trait not implemented - suggest impl block
        if msg.contains("doesn't implement") || msg.contains("trait") && msg.contains("implement") {
            return Some(
                "Implement the trait: add `impl TraitName for YourType { fn required_method(self) -> ReturnType { ... } }`"
                    .to_string(),
            );
        }

        None
    }
}

/// Extract variable name from error message
fn extract_variable_from_message(msg: &str) -> Option<String> {
    // Look for patterns like "cannot assign twice to immutable variable `x`"
    if let Some(start) = msg.find("`") {
        if let Some(end) = msg[start + 1..].find("`") {
            return Some(msg[start + 1..start + 1 + end].to_string());
        }
    }
    None
}

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

    #[test]
    fn test_parse_rustc_json() {
        let json = r#"{"message":"mismatched types","level":"error","spans":[{"file_name":"test.rs","line_start":10,"line_end":10,"column_start":5,"column_end":10,"is_primary":true,"label":"expected i32, found &str","text":null}],"code":{"code":"E0308"},"children":[],"rendered":null}"#;

        let diag: RustcDiagnostic = serde_json::from_str(json).unwrap();
        assert_eq!(diag.message, "mismatched types");
        assert_eq!(diag.level, "error");
        assert_eq!(diag.spans.len(), 1);
        assert_eq!(diag.spans[0].line_start, 10);
    }

    #[test]
    fn test_diagnostic_format() {
        // Disable colors for deterministic test output
        colored::control::set_override(false);

        let diag = WindjammerDiagnostic {
            message: "Type mismatch".to_string(),
            level: DiagnosticLevel::Error,
            location: Location {
                file: PathBuf::from("test.wj"),
                line: 10,
                column: 5,
            },
            spans: vec![],
            code: Some("E0308".to_string()),
            help: vec!["Try using .parse()".to_string()],
            notes: vec![],
        };

        let formatted = diag.format();
        assert!(
            formatted.contains("error[E0308]"),
            "Expected 'error[E0308]' in:\n{}",
            formatted
        );
        assert!(
            formatted.contains("test.wj:10:5"),
            "Expected 'test.wj:10:5' in:\n{}",
            formatted
        );
        assert!(
            formatted.contains("help: Try using .parse()"),
            "Expected 'help: Try using .parse()' in:\n{}",
            formatted
        );

        // Re-enable colors for other tests
        colored::control::unset_override();
    }

    #[test]
    fn test_rust_type_to_windjammer() {
        let mapper = ErrorMapper::new(SourceMap::new());

        assert_eq!(mapper.rust_type_to_windjammer("i32"), "int");
        assert_eq!(mapper.rust_type_to_windjammer("i64"), "int");
        assert_eq!(mapper.rust_type_to_windjammer("&str"), "string");
        assert_eq!(mapper.rust_type_to_windjammer("String"), "string");
        assert_eq!(mapper.rust_type_to_windjammer("bool"), "bool");
        assert_eq!(mapper.rust_type_to_windjammer("f64"), "float");
        assert_eq!(mapper.rust_type_to_windjammer("()"), "void");
    }

    #[test]
    fn test_rust_type_to_windjammer_complex() {
        let mapper = ErrorMapper::new(SourceMap::new());

        assert_eq!(mapper.rust_type_to_windjammer("&i32"), "&int");
        assert_eq!(mapper.rust_type_to_windjammer("Vec<i32>"), "[int]");
        assert_eq!(mapper.rust_type_to_windjammer("Option<String>"), "string?");
    }

    #[test]
    fn test_translate_type_mismatch() {
        let mapper = ErrorMapper::new(SourceMap::new());

        let rust_msg = "mismatched types: expected `i32`, found `&str`";
        let translated = mapper.translate_message(rust_msg);
        assert!(translated.contains("Type mismatch"));
        assert!(translated.contains("int"));
        assert!(translated.contains("string"));
    }

    #[test]
    fn test_translate_function_not_found() {
        let mapper = ErrorMapper::new(SourceMap::new());

        let rust_msg = "cannot find function `foo` in this scope";
        let translated = mapper.translate_message(rust_msg);
        assert!(translated.contains("Function not found"));
        assert!(translated.contains("foo"));
    }

    #[test]
    fn test_translate_ownership_error() {
        let mapper = ErrorMapper::new(SourceMap::new());

        let rust_msg = "use of moved value: `x`";
        let translated = mapper.translate_message(rust_msg);
        assert!(
            translated.contains("moved") || translated.contains("Ownership"),
            "Should explain move/ownership. Got: {}",
            translated
        );
        assert!(translated.contains("x"), "Should mention the value name");
    }

    #[test]
    fn test_contextual_help_type_mismatch() {
        let diag = WindjammerDiagnostic {
            message: "Type mismatch: expected int, found string".to_string(),
            level: DiagnosticLevel::Error,
            location: Location {
                file: PathBuf::from("test.wj"),
                line: 10,
                column: 5,
            },
            spans: vec![],
            code: None,
            help: vec![],
            notes: vec![],
        };

        let help = diag.get_contextual_help();
        assert!(help.is_some());
        assert!(help.unwrap().contains(".parse()"));
    }

    #[test]
    fn test_contextual_help_mutability() {
        let diag = WindjammerDiagnostic {
            message: "Cannot modify: This value is not declared as mutable".to_string(),
            level: DiagnosticLevel::Error,
            location: Location {
                file: PathBuf::from("test.wj"),
                line: 10,
                column: 5,
            },
            spans: vec![],
            code: None,
            help: vec![],
            notes: vec![],
        };

        let help = diag.get_contextual_help();
        assert!(help.is_some());
        assert!(help.unwrap().contains("let mut"));
    }

    #[test]
    fn test_extract_between() {
        let mapper = ErrorMapper::new(SourceMap::new());

        let text = "expected `i32`, found `&str`";
        let expected = mapper.extract_between(text, "expected `", "`");
        assert_eq!(expected, Some("i32".to_string()));

        let found = mapper.extract_between(text, "found `", "`");
        assert_eq!(found, Some("&str".to_string()));
    }
}