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
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
//! Watch mode for automatic rebuilds on file changes
//!
//! Provides file system watching with debouncing for the `pxl build --watch` command.

use notify::RecursiveMode;
use notify_debouncer_mini::{new_debouncer, DebouncedEventKind};
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::sync::mpsc::channel;
use std::time::{Duration, Instant};
use thiserror::Error;

use crate::build::{BuildContext, BuildPipeline, BuildStatus, IncrementalBuild, IncrementalStats};
use crate::config::schema::WatchConfig;

/// Error during watch mode
#[derive(Debug, Error)]
pub enum WatchError {
    /// Failed to initialize file watcher
    #[error("Failed to initialize file watcher: {0}")]
    WatcherInit(notify::Error),
    /// Failed to add watch path
    #[error("Failed to watch path: {0}")]
    WatchPath(notify::Error),
    /// Channel receive error
    #[error("Watch channel error: {0}")]
    ChannelError(String),
    /// Build failed (non-fatal, continues watching)
    #[error("Build failed: {0}")]
    BuildFailed(String),
    /// Source directory not found
    #[error("Source directory not found: {}", .0.display())]
    SourceNotFound(PathBuf),
}

/// A detailed build error with file location information
#[derive(Debug, Clone)]
pub struct BuildError {
    /// Path to the file containing the error
    pub file: PathBuf,
    /// Line number (1-indexed, None if unknown)
    pub line: Option<usize>,
    /// Column number (1-indexed, None if unknown)
    pub column: Option<usize>,
    /// Error message
    pub message: String,
}

impl BuildError {
    /// Create a new build error with file and message
    pub fn new(file: impl Into<PathBuf>, message: impl Into<String>) -> Self {
        Self { file: file.into(), line: None, column: None, message: message.into() }
    }

    /// Create a build error with line information
    pub fn with_line(file: impl Into<PathBuf>, line: usize, message: impl Into<String>) -> Self {
        Self { file: file.into(), line: Some(line), column: None, message: message.into() }
    }

    /// Create a build error with full location information
    pub fn with_location(
        file: impl Into<PathBuf>,
        line: usize,
        column: usize,
        message: impl Into<String>,
    ) -> Self {
        Self { file: file.into(), line: Some(line), column: Some(column), message: message.into() }
    }
}

impl std::fmt::Display for BuildError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Error in {}", self.file.display())?;
        if let Some(line) = self.line {
            write!(f, ":{}", line)?;
            if let Some(col) = self.column {
                write!(f, ":{}", col)?;
            }
        }
        write!(f, ": {}", self.message)
    }
}

/// Tracks files with errors across build iterations for recovery detection
#[derive(Debug, Default)]
pub struct ErrorTracker {
    /// Files that had errors in the previous build
    files_with_errors: HashSet<PathBuf>,
}

impl ErrorTracker {
    /// Create a new error tracker
    pub fn new() -> Self {
        Self::default()
    }

    /// Update tracker with new build result, returns list of fixed files
    pub fn update(&mut self, result: &BuildResult) -> Vec<PathBuf> {
        let current_error_files: HashSet<PathBuf> =
            result.build_errors.iter().map(|e| e.file.clone()).collect();

        // Find files that had errors before but don't now
        let fixed: Vec<PathBuf> =
            self.files_with_errors.difference(&current_error_files).cloned().collect();

        // Update the tracked error files
        self.files_with_errors = current_error_files;

        fixed
    }

    /// Check if there are any tracked errors
    pub fn has_errors(&self) -> bool {
        !self.files_with_errors.is_empty()
    }

    /// Get the number of files with errors
    pub fn error_count(&self) -> usize {
        self.files_with_errors.len()
    }
}

/// Options for watch mode
#[derive(Debug, Clone)]
pub struct WatchOptions {
    /// Source directory to watch
    pub src_dir: PathBuf,
    /// Output directory for builds
    pub out_dir: PathBuf,
    /// Watch configuration (debounce, clear screen)
    pub config: WatchConfig,
    /// Verbose output
    pub verbose: bool,
}

impl Default for WatchOptions {
    fn default() -> Self {
        Self {
            src_dir: PathBuf::from("src/pxl"),
            out_dir: PathBuf::from("build"),
            config: WatchConfig::default(),
            verbose: false,
        }
    }
}

/// Result of a single build attempt
#[derive(Debug)]
pub struct BuildResult {
    /// Number of files processed
    pub files_processed: usize,
    /// Number of sprites rendered
    pub sprites_rendered: usize,
    /// Simple error messages (legacy field, prefer build_errors)
    pub errors: Vec<String>,
    /// Detailed build errors with file/line information
    pub build_errors: Vec<BuildError>,
    /// Number of warnings
    pub warnings: Vec<String>,
    /// Build duration
    pub duration: Duration,
}

impl BuildResult {
    /// Create a new empty build result
    pub fn new() -> Self {
        Self {
            files_processed: 0,
            sprites_rendered: 0,
            errors: vec![],
            build_errors: vec![],
            warnings: vec![],
            duration: Duration::ZERO,
        }
    }

    /// Check if build succeeded (no errors)
    pub fn success(&self) -> bool {
        self.errors.is_empty() && self.build_errors.is_empty()
    }

    /// Add a detailed build error
    pub fn add_error(&mut self, error: BuildError) {
        self.build_errors.push(error);
    }

    /// Total number of errors (both legacy and detailed)
    pub fn error_count(&self) -> usize {
        self.errors.len() + self.build_errors.len()
    }
}

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

/// Clear the terminal screen
fn clear_screen() {
    // ANSI escape code to clear screen and move cursor to top-left
    print!("\x1B[2J\x1B[1;1H");
}

/// Format duration for display
fn format_duration(duration: Duration) -> String {
    let millis = duration.as_millis();
    if millis < 1000 {
        format!("{}ms", millis)
    } else {
        format!("{:.2}s", duration.as_secs_f64())
    }
}

/// Extract a readable file name from a target ID.
/// Converts "sprite:player" to "player.pxl", "atlas:main" to "atlas:main", etc.
fn target_id_to_display_name(target_id: &str) -> String {
    if let Some((kind, name)) = target_id.split_once(':') {
        match kind {
            "sprite" | "animation" | "preview" => format!("{}.pxl", name),
            _ => target_id.to_string(),
        }
    } else {
        target_id.to_string()
    }
}

/// Try to extract a line number from an error message.
/// Looks for patterns like "line 5", "Line 5:", "at line 5", etc.
fn extract_line_number(message: &str) -> Option<usize> {
    // Common patterns for line numbers in error messages
    let patterns = [
        r"[Ll]ine\s+(\d+)",
        r"at line\s+(\d+)",
        r":(\d+):", // file:line:col format
        r":(\d+)$", // file:line format at end
    ];

    for pattern in patterns {
        if let Ok(re) = regex::Regex::new(pattern) {
            if let Some(caps) = re.captures(message) {
                if let Some(m) = caps.get(1) {
                    if let Ok(line) = m.as_str().parse::<usize>() {
                        return Some(line);
                    }
                }
            }
        }
    }
    None
}

/// Format an error message for display, optionally extracting line info.
fn format_error_display(target_id: &str, error_msg: &str) -> String {
    let display_name = target_id_to_display_name(target_id);
    let line_num = extract_line_number(error_msg);

    // Clean up the error message - remove "failed: " prefix if present
    let clean_msg = error_msg.strip_prefix("failed: ").unwrap_or(error_msg);

    if let Some(line) = line_num {
        format!("Error in {}:\n          Line {}: {}", display_name, line, clean_msg)
    } else {
        format!("Error in {}: {}", display_name, clean_msg)
    }
}

/// Get current timestamp for logging
fn timestamp() -> String {
    use std::time::SystemTime;
    let now = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap_or_default();
    let secs = now.as_secs() % 86400; // seconds since midnight
    let hours = (secs / 3600) % 24;
    let minutes = (secs / 60) % 60;
    let seconds = secs % 60;
    format!("{:02}:{:02}:{:02}", hours, minutes, seconds)
}

/// Perform a single build iteration.
///
/// This function discovers .pxl files, parses them, and renders sprites.
/// In watch mode, this is called on startup and after each file change.
pub fn do_build<F>(options: &WatchOptions, build_fn: F) -> BuildResult
where
    F: FnOnce(&Path, &Path) -> BuildResult,
{
    let start = Instant::now();
    let mut result = build_fn(&options.src_dir, &options.out_dir);
    result.duration = start.elapsed();
    result
}

/// Simple build function that discovers and counts files.
///
/// This is a placeholder that will be replaced by the full build pipeline
/// when BST-3 is complete. For now, it demonstrates the watch infrastructure.
pub fn simple_build(src_dir: &Path, _out_dir: &Path) -> BuildResult {
    use glob::glob;

    let mut result = BuildResult::new();

    // Find all .pxl and .jsonl files
    let pattern = format!("{}/**/*.pxl", src_dir.display());
    if let Ok(entries) = glob(&pattern) {
        for entry in entries.flatten() {
            result.files_processed += 1;
            if let Ok(content) = std::fs::read_to_string(&entry) {
                // Count sprites (very basic)
                result.sprites_rendered += content.matches("\"type\": \"sprite\"").count();
                result.sprites_rendered += content.matches("\"type\":\"sprite\"").count();
            }
        }
    }

    let pattern_jsonl = format!("{}/**/*.jsonl", src_dir.display());
    if let Ok(entries) = glob(&pattern_jsonl) {
        for entry in entries.flatten() {
            result.files_processed += 1;
            if let Ok(content) = std::fs::read_to_string(&entry) {
                result.sprites_rendered += content.matches("\"type\": \"sprite\"").count();
                result.sprites_rendered += content.matches("\"type\":\"sprite\"").count();
            }
        }
    }

    result
}

/// Watch for file changes and rebuild automatically.
///
/// This function blocks and runs until interrupted (Ctrl+C).
///
/// # Arguments
/// * `options` - Watch mode configuration
///
/// # Returns
/// * `Ok(())` if watch mode exits cleanly (shouldn't happen normally)
/// * `Err(WatchError)` if watch setup fails
///
/// # Example
/// ```ignore
/// let options = WatchOptions {
///     src_dir: PathBuf::from("src/pxl"),
///     out_dir: PathBuf::from("build"),
///     config: WatchConfig::default(),
///     verbose: false,
/// };
/// watch_and_rebuild(options)?;
/// ```
pub fn watch_and_rebuild(options: WatchOptions) -> Result<(), WatchError> {
    // Verify source directory exists
    if !options.src_dir.exists() {
        return Err(WatchError::SourceNotFound(options.src_dir.clone()));
    }

    // Create output directory if needed
    if !options.out_dir.exists() {
        std::fs::create_dir_all(&options.out_dir).ok();
    }

    // Create channel for debounced events
    let (tx, rx) = channel();

    // Create debounced watcher
    let debounce_duration = Duration::from_millis(options.config.debounce_ms as u64);
    let mut debouncer = new_debouncer(debounce_duration, tx).map_err(WatchError::WatcherInit)?;

    // Start watching the source directory
    debouncer
        .watcher()
        .watch(&options.src_dir, RecursiveMode::Recursive)
        .map_err(WatchError::WatchPath)?;

    // Error tracker for detecting fixed files
    let mut error_tracker = ErrorTracker::new();

    // Initial build
    if options.config.clear_screen {
        clear_screen();
    }
    println!("[{}] Building...", timestamp());
    let result = do_build(&options, simple_build);
    print_build_result(&result, &[]);
    error_tracker.update(&result);
    println!("[{}] Watching {} for changes...", timestamp(), options.src_dir.display());

    // Watch loop
    loop {
        match rx.recv() {
            Ok(Ok(events)) => {
                // Filter for relevant file changes
                let relevant_changes: Vec<_> = events
                    .iter()
                    .filter(|e| {
                        matches!(e.kind, DebouncedEventKind::Any) && is_relevant_file(&e.path)
                    })
                    .collect();

                if !relevant_changes.is_empty() {
                    // Log changed files
                    for event in &relevant_changes {
                        if let Some(name) = event.path.file_name() {
                            println!("[{}] Changed: {}", timestamp(), name.to_string_lossy());
                        }
                    }

                    // Clear screen if configured
                    if options.config.clear_screen {
                        clear_screen();
                    }

                    // Rebuild
                    println!("[{}] Building...", timestamp());
                    let result = do_build(&options, simple_build);

                    // Track fixed files before updating error tracker
                    let fixed_files = error_tracker.update(&result);
                    print_build_result(&result, &fixed_files);

                    println!(
                        "[{}] Watching {} for changes...",
                        timestamp(),
                        options.src_dir.display()
                    );
                }
            }
            Ok(Err(error)) => {
                // Watch error (non-fatal) - log but continue watching
                eprintln!("[{}] Watch error: {:?}", timestamp(), error);
                eprintln!("[{}] Continuing to watch...", timestamp());
            }
            Err(e) => {
                return Err(WatchError::ChannelError(e.to_string()));
            }
        }
    }
}

/// Check if a file is relevant for rebuilding
fn is_relevant_file(path: &Path) -> bool {
    if let Some(ext) = path.extension() {
        let ext = ext.to_string_lossy().to_lowercase();
        matches!(ext.as_str(), "pxl" | "jsonl" | "json")
    } else {
        false
    }
}

/// Watch for file changes and rebuild using the build pipeline.
///
/// This function blocks and runs until interrupted (Ctrl+C).
///
/// # Arguments
/// * `context` - Build context with config and project root
/// * `watch_config` - Watch mode configuration
///
/// # Returns
/// * `Ok(())` if watch mode exits cleanly (shouldn't happen normally)
/// * `Err(WatchError)` if watch setup fails
pub fn watch_with_pipeline(
    context: BuildContext,
    watch_config: WatchConfig,
) -> Result<(), WatchError> {
    let src_dir = context.src_dir().to_path_buf();
    let verbose = context.is_verbose();

    // Verify source directory exists
    if !src_dir.exists() {
        return Err(WatchError::SourceNotFound(src_dir));
    }

    // Create output directory if needed
    let out_dir = context.out_dir();
    if !out_dir.exists() {
        std::fs::create_dir_all(out_dir).ok();
    }

    // Create channel for debounced events
    let (tx, rx) = channel();

    // Create debounced watcher
    let debounce_duration = Duration::from_millis(watch_config.debounce_ms as u64);
    let mut debouncer = new_debouncer(debounce_duration, tx).map_err(WatchError::WatcherInit)?;

    // Start watching the source directory
    debouncer.watcher().watch(&src_dir, RecursiveMode::Recursive).map_err(WatchError::WatchPath)?;

    // Error tracker for detecting fixed files
    let mut error_tracker = ErrorTracker::new();

    // Create the pipeline
    let pipeline = BuildPipeline::new(context);

    // Initial build
    if watch_config.clear_screen {
        clear_screen();
    }
    println!("[{}] Building...", timestamp());
    let pipeline_result = pipeline.build();
    let result = convert_pipeline_result(&pipeline_result);
    let fixed_files = error_tracker.update(&result);
    print_pipeline_result(&pipeline_result, &fixed_files, verbose);
    println!("[{}] Watching {} for changes...", timestamp(), src_dir.display());

    // Watch loop
    loop {
        match rx.recv() {
            Ok(Ok(events)) => {
                // Filter for relevant file changes
                let relevant_changes: Vec<_> = events
                    .iter()
                    .filter(|e| {
                        matches!(e.kind, DebouncedEventKind::Any) && is_relevant_file(&e.path)
                    })
                    .collect();

                if !relevant_changes.is_empty() {
                    // Log changed files
                    for event in &relevant_changes {
                        if let Some(name) = event.path.file_name() {
                            println!("[{}] Changed: {}", timestamp(), name.to_string_lossy());
                        }
                    }

                    // Clear screen if configured
                    if watch_config.clear_screen {
                        clear_screen();
                    }

                    // Rebuild using pipeline
                    println!("[{}] Building...", timestamp());
                    let pipeline_result = pipeline.build();
                    let result = convert_pipeline_result(&pipeline_result);

                    // Track fixed files before updating error tracker
                    let fixed_files = error_tracker.update(&result);
                    print_pipeline_result(&pipeline_result, &fixed_files, verbose);

                    println!("[{}] Watching {} for changes...", timestamp(), src_dir.display());
                }
            }
            Ok(Err(error)) => {
                // Watch error (non-fatal) - log but continue watching
                eprintln!("[{}] Watch error: {:?}", timestamp(), error);
                eprintln!("[{}] Continuing to watch...", timestamp());
            }
            Err(e) => {
                return Err(WatchError::ChannelError(e.to_string()));
            }
        }
    }
}

/// Watch for file changes and rebuild using incremental builds.
///
/// This function blocks and runs until interrupted (Ctrl+C).
/// Uses the incremental build system to skip unchanged targets.
///
/// # Arguments
/// * `context` - Build context with config and project root
/// * `watch_config` - Watch mode configuration
/// * `force` - If true, bypass caching and rebuild all targets
///
/// # Returns
/// * `Ok(())` if watch mode exits cleanly (shouldn't happen normally)
/// * `Err(WatchError)` if watch setup fails
pub fn watch_with_incremental(
    context: BuildContext,
    watch_config: WatchConfig,
    force: bool,
) -> Result<(), WatchError> {
    let src_dir = context.src_dir().to_path_buf();
    let verbose = context.is_verbose();

    // Verify source directory exists
    if !src_dir.exists() {
        return Err(WatchError::SourceNotFound(src_dir));
    }

    // Create output directory if needed
    let out_dir = context.out_dir();
    if !out_dir.exists() {
        std::fs::create_dir_all(out_dir).ok();
    }

    // Create channel for debounced events
    let (tx, rx) = channel();

    // Create debounced watcher
    let debounce_duration = Duration::from_millis(watch_config.debounce_ms as u64);
    let mut debouncer = new_debouncer(debounce_duration, tx).map_err(WatchError::WatcherInit)?;

    // Start watching the source directory
    debouncer.watcher().watch(&src_dir, RecursiveMode::Recursive).map_err(WatchError::WatchPath)?;

    // Error tracker for detecting fixed files
    let mut error_tracker = ErrorTracker::new();

    // Create the incremental build
    let mut incremental = IncrementalBuild::new(context).with_force(force);

    // Initial build
    if watch_config.clear_screen {
        clear_screen();
    }
    println!("[{}] Building...", timestamp());
    let build_result = incremental.run();
    let result = convert_pipeline_result(&build_result);
    let fixed_files = error_tracker.update(&result);
    print_incremental_result(&build_result, &fixed_files, verbose, force);
    println!("[{}] Watching {} for changes...", timestamp(), src_dir.display());

    // Watch loop
    loop {
        match rx.recv() {
            Ok(Ok(events)) => {
                // Filter for relevant file changes
                let relevant_changes: Vec<_> = events
                    .iter()
                    .filter(|e| {
                        matches!(e.kind, DebouncedEventKind::Any) && is_relevant_file(&e.path)
                    })
                    .collect();

                if !relevant_changes.is_empty() {
                    // Log changed files
                    for event in &relevant_changes {
                        if let Some(name) = event.path.file_name() {
                            println!("[{}] Changed: {}", timestamp(), name.to_string_lossy());
                        }
                    }

                    // Clear screen if configured
                    if watch_config.clear_screen {
                        clear_screen();
                    }

                    // Rebuild using incremental build
                    println!("[{}] Building...", timestamp());
                    let build_result = incremental.run();
                    let result = convert_pipeline_result(&build_result);

                    // Track fixed files before updating error tracker
                    let fixed_files = error_tracker.update(&result);
                    print_incremental_result(&build_result, &fixed_files, verbose, force);

                    println!("[{}] Watching {} for changes...", timestamp(), src_dir.display());
                }
            }
            Ok(Err(error)) => {
                // Watch error (non-fatal) - log but continue watching
                eprintln!("[{}] Watch error: {:?}", timestamp(), error);
                eprintln!("[{}] Continuing to watch...", timestamp());
            }
            Err(e) => {
                return Err(WatchError::ChannelError(e.to_string()));
            }
        }
    }
}

/// Print incremental build result to console
fn print_incremental_result(
    build_result: &Result<crate::build::BuildResult, crate::build::pipeline::BuildError>,
    fixed_files: &[PathBuf],
    verbose: bool,
    force: bool,
) {
    // Report fixed files first
    for fixed in fixed_files {
        println!("[{}] Fixed: {}", timestamp(), fixed.display());
    }

    match build_result {
        Ok(result) => {
            let stats = IncrementalStats::from_result(result);
            if result.is_success() {
                if stats.had_skips() && !force {
                    println!(
                        "[{}] Build complete ({:?}) - {} built, {} skipped (unchanged)",
                        timestamp(),
                        result.total_duration,
                        stats.built,
                        stats.skipped
                    );
                } else {
                    println!(
                        "[{}] Build complete ({:?}) - {} built",
                        timestamp(),
                        result.total_duration,
                        stats.built
                    );
                }
            } else {
                let failed = stats.failed;
                println!(
                    "[{}] Build failed ({:?}) - {} error{}",
                    timestamp(),
                    result.total_duration,
                    failed,
                    if failed == 1 { "" } else { "s" }
                );

                // Print failures with improved formatting
                for target in result.failures() {
                    let error_msg = format!("{}", target.status);
                    let formatted = format_error_display(&target.target_id, &error_msg);
                    eprintln!("[{}] {}", timestamp(), formatted);
                }
            }

            // Print warnings if verbose
            if verbose {
                for warning in result.all_warnings() {
                    eprintln!("[{}] Warning: {}", timestamp(), warning);
                }
            }
        }
        Err(e) => {
            eprintln!("[{}] Build error: {}", timestamp(), e);
        }
    }
}

/// Convert pipeline BuildResult to watch module's BuildResult for error tracking
fn convert_pipeline_result(
    pipeline_result: &Result<crate::build::BuildResult, crate::build::pipeline::BuildError>,
) -> BuildResult {
    let mut result = BuildResult::new();

    match pipeline_result {
        Ok(build_result) => {
            result.files_processed = build_result.targets.len();
            result.sprites_rendered = build_result.success_count();
            result.duration = build_result.total_duration;

            // Convert failures to BuildErrors
            for target in &build_result.targets {
                if let BuildStatus::Failed(msg) = &target.status {
                    // Try to extract file path from target_id (format: "kind:name")
                    result
                        .add_error(BuildError::new(PathBuf::from(&target.target_id), msg.clone()));
                }
            }

            // Collect warnings
            result.warnings = build_result.all_warnings().into_iter().cloned().collect();
        }
        Err(e) => {
            result.errors.push(e.to_string());
        }
    }

    result
}

/// Print pipeline build result to console
fn print_pipeline_result(
    pipeline_result: &Result<crate::build::BuildResult, crate::build::pipeline::BuildError>,
    fixed_files: &[PathBuf],
    verbose: bool,
) {
    // Report fixed files first
    for fixed in fixed_files {
        println!("[{}] Fixed: {}", timestamp(), fixed.display());
    }

    match pipeline_result {
        Ok(build_result) => {
            if build_result.is_success() {
                println!(
                    "[{}] Build complete ({:?}) - {} built, {} skipped",
                    timestamp(),
                    build_result.total_duration,
                    build_result.success_count(),
                    build_result.skipped_count()
                );
            } else {
                let failed = build_result.failed_count();
                println!(
                    "[{}] Build failed ({:?}) - {} error{}",
                    timestamp(),
                    build_result.total_duration,
                    failed,
                    if failed == 1 { "" } else { "s" }
                );

                // Print failures with improved formatting
                for target in build_result.failures() {
                    let error_msg = format!("{}", target.status);
                    let formatted = format_error_display(&target.target_id, &error_msg);
                    eprintln!("[{}] {}", timestamp(), formatted);
                }
            }

            // Print warnings if verbose
            if verbose {
                for warning in build_result.all_warnings() {
                    eprintln!("[{}] Warning: {}", timestamp(), warning);
                }
            }
        }
        Err(e) => {
            eprintln!("[{}] Build error: {}", timestamp(), e);
        }
    }
}

/// Print build result to console with fixed file notifications
fn print_build_result(result: &BuildResult, fixed_files: &[PathBuf]) {
    // Report fixed files first (before showing new errors)
    for fixed in fixed_files {
        if let Some(name) = fixed.file_name() {
            println!("[{}] Fixed: {}", timestamp(), name.to_string_lossy());
        }
    }

    if result.success() {
        println!(
            "[{}] Build complete ({}) - Files: {} | Sprites: {}",
            timestamp(),
            format_duration(result.duration),
            result.files_processed,
            result.sprites_rendered
        );
    } else {
        let error_count = result.error_count();
        println!(
            "[{}] Build failed ({}) - {} error{}",
            timestamp(),
            format_duration(result.duration),
            error_count,
            if error_count == 1 { "" } else { "s" }
        );

        // Print detailed build errors with file/line info
        for error in &result.build_errors {
            if let Some(name) = error.file.file_name() {
                eprint!("[{}] Error in {}:", timestamp(), name.to_string_lossy());
                if let Some(line) = error.line {
                    eprint!("\n          Line {}: ", line);
                } else {
                    eprint!(" ");
                }
                eprintln!("{}", error.message);
            } else {
                eprintln!("[{}] Error: {}", timestamp(), error);
            }
        }

        // Print legacy simple errors
        for error in &result.errors {
            eprintln!("[{}] Error: {}", timestamp(), error);
        }
    }

    // Print warnings
    for warning in &result.warnings {
        eprintln!("[{}] Warning: {}", timestamp(), warning);
    }
}

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

    #[test]
    fn test_watch_options_default() {
        let options = WatchOptions::default();
        assert_eq!(options.src_dir, PathBuf::from("src/pxl"));
        assert_eq!(options.out_dir, PathBuf::from("build"));
        assert_eq!(options.config.debounce_ms, 100);
        assert!(options.config.clear_screen);
    }

    #[test]
    fn test_build_result_new() {
        let result = BuildResult::new();
        assert_eq!(result.files_processed, 0);
        assert_eq!(result.sprites_rendered, 0);
        assert!(result.errors.is_empty());
        assert!(result.warnings.is_empty());
        assert!(result.success());
    }

    #[test]
    fn test_build_result_with_errors() {
        let mut result = BuildResult::new();
        result.errors.push("Test error".to_string());
        assert!(!result.success());
    }

    #[test]
    fn test_is_relevant_file() {
        assert!(is_relevant_file(Path::new("sprite.pxl")));
        assert!(is_relevant_file(Path::new("sprites.jsonl")));
        assert!(is_relevant_file(Path::new("data.json")));
        assert!(!is_relevant_file(Path::new("readme.md")));
        assert!(!is_relevant_file(Path::new("image.png")));
        assert!(!is_relevant_file(Path::new("noextension")));
    }

    #[test]
    fn test_format_duration() {
        assert_eq!(format_duration(Duration::from_millis(50)), "50ms");
        assert_eq!(format_duration(Duration::from_millis(999)), "999ms");
        assert_eq!(format_duration(Duration::from_millis(1000)), "1.00s");
        assert_eq!(format_duration(Duration::from_millis(1500)), "1.50s");
    }

    #[test]
    fn test_simple_build_empty_dir() {
        let temp = TempDir::new().unwrap();
        let src = temp.path().join("src");
        std::fs::create_dir_all(&src).unwrap();

        let result = simple_build(&src, temp.path());
        assert_eq!(result.files_processed, 0);
        assert_eq!(result.sprites_rendered, 0);
        assert!(result.success());
    }

    #[test]
    fn test_simple_build_with_files() {
        let temp = TempDir::new().unwrap();
        let src = temp.path().join("src");
        std::fs::create_dir_all(&src).unwrap();

        // Create a test .pxl file with sprites
        let content = r#"{"type": "sprite", "name": "test1"}
{"type": "sprite", "name": "test2"}"#;
        std::fs::write(src.join("test.jsonl"), content).unwrap();

        let result = simple_build(&src, temp.path());
        assert_eq!(result.files_processed, 1);
        assert_eq!(result.sprites_rendered, 2);
        assert!(result.success());
    }

    #[test]
    fn test_watch_error_source_not_found() {
        let options =
            WatchOptions { src_dir: PathBuf::from("/nonexistent/path"), ..Default::default() };

        let result = watch_and_rebuild(options);
        assert!(matches!(result, Err(WatchError::SourceNotFound(_))));
    }

    #[test]
    fn test_do_build_with_custom_function() {
        let temp = TempDir::new().unwrap();
        let src = temp.path().join("src");
        std::fs::create_dir_all(&src).unwrap();

        let options =
            WatchOptions { src_dir: src, out_dir: temp.path().to_path_buf(), ..Default::default() };

        let result = do_build(&options, |_src, _out| {
            let mut r = BuildResult::new();
            r.files_processed = 5;
            r.sprites_rendered = 10;
            r
        });

        assert_eq!(result.files_processed, 5);
        assert_eq!(result.sprites_rendered, 10);
        assert!(result.duration >= Duration::ZERO);
    }

    // Error recovery tests

    #[test]
    fn test_build_error_new() {
        let error = BuildError::new("test.pxl", "Invalid syntax");
        assert_eq!(error.file, PathBuf::from("test.pxl"));
        assert_eq!(error.line, None);
        assert_eq!(error.column, None);
        assert_eq!(error.message, "Invalid syntax");
    }

    #[test]
    fn test_build_error_with_line() {
        let error = BuildError::with_line("test.pxl", 5, "Invalid color");
        assert_eq!(error.file, PathBuf::from("test.pxl"));
        assert_eq!(error.line, Some(5));
        assert_eq!(error.column, None);
        assert_eq!(error.message, "Invalid color");
    }

    #[test]
    fn test_build_error_with_location() {
        let error = BuildError::with_location("test.pxl", 5, 10, "Unexpected token");
        assert_eq!(error.file, PathBuf::from("test.pxl"));
        assert_eq!(error.line, Some(5));
        assert_eq!(error.column, Some(10));
        assert_eq!(error.message, "Unexpected token");
    }

    #[test]
    fn test_build_error_display() {
        let error = BuildError::with_line("sprites/broken.pxl", 5, "Invalid color format \"#GGG\"");
        let display = format!("{}", error);
        assert!(display.contains("sprites/broken.pxl"));
        assert!(display.contains("5"));
        assert!(display.contains("Invalid color format"));
    }

    #[test]
    fn test_error_tracker_new() {
        let tracker = ErrorTracker::new();
        assert!(!tracker.has_errors());
        assert_eq!(tracker.error_count(), 0);
    }

    #[test]
    fn test_error_tracker_tracks_errors() {
        let mut tracker = ErrorTracker::new();

        // First build has errors
        let mut result = BuildResult::new();
        result.add_error(BuildError::new("file1.pxl", "Error 1"));
        result.add_error(BuildError::new("file2.pxl", "Error 2"));

        let fixed = tracker.update(&result);
        assert!(fixed.is_empty()); // No fixed files on first build
        assert!(tracker.has_errors());
        assert_eq!(tracker.error_count(), 2);
    }

    #[test]
    fn test_error_tracker_detects_fixed_files() {
        let mut tracker = ErrorTracker::new();

        // First build has errors in file1 and file2
        let mut result1 = BuildResult::new();
        result1.add_error(BuildError::new("file1.pxl", "Error 1"));
        result1.add_error(BuildError::new("file2.pxl", "Error 2"));
        tracker.update(&result1);

        // Second build: file1 is fixed, file2 still has error
        let mut result2 = BuildResult::new();
        result2.add_error(BuildError::new("file2.pxl", "Error 2"));
        let fixed = tracker.update(&result2);

        assert_eq!(fixed.len(), 1);
        assert_eq!(fixed[0], PathBuf::from("file1.pxl"));
        assert!(tracker.has_errors());
        assert_eq!(tracker.error_count(), 1);
    }

    #[test]
    fn test_error_tracker_all_fixed() {
        let mut tracker = ErrorTracker::new();

        // First build has errors
        let mut result1 = BuildResult::new();
        result1.add_error(BuildError::new("file1.pxl", "Error 1"));
        tracker.update(&result1);

        // Second build: all fixed
        let result2 = BuildResult::new();
        let fixed = tracker.update(&result2);

        assert_eq!(fixed.len(), 1);
        assert_eq!(fixed[0], PathBuf::from("file1.pxl"));
        assert!(!tracker.has_errors());
        assert_eq!(tracker.error_count(), 0);
    }

    #[test]
    fn test_build_result_with_build_errors() {
        let mut result = BuildResult::new();
        assert!(result.success());
        assert_eq!(result.error_count(), 0);

        result.add_error(BuildError::new("test.pxl", "Error"));
        assert!(!result.success());
        assert_eq!(result.error_count(), 1);
    }

    #[test]
    fn test_build_result_mixed_errors() {
        let mut result = BuildResult::new();

        // Add both legacy and detailed errors
        result.errors.push("Legacy error".to_string());
        result.add_error(BuildError::new("test.pxl", "Detailed error"));

        assert!(!result.success());
        assert_eq!(result.error_count(), 2);
    }

    // Pipeline integration tests

    #[test]
    fn test_convert_pipeline_result_success() {
        use crate::build::{BuildResult as PipelineBuildResult, TargetResult};

        let mut pipeline_result = PipelineBuildResult::new();
        pipeline_result.add_result(TargetResult::success(
            "sprite:test".to_string(),
            vec![PathBuf::from("test.png")],
            Duration::from_millis(50),
        ));
        pipeline_result.total_duration = Duration::from_millis(100);

        let watch_result = convert_pipeline_result(&Ok(pipeline_result));
        assert!(watch_result.success());
        assert_eq!(watch_result.files_processed, 1);
        assert_eq!(watch_result.sprites_rendered, 1);
    }

    #[test]
    fn test_convert_pipeline_result_with_failures() {
        use crate::build::{BuildResult as PipelineBuildResult, TargetResult};

        let mut pipeline_result = PipelineBuildResult::new();
        pipeline_result.add_result(TargetResult::success(
            "sprite:good".to_string(),
            vec![],
            Duration::from_millis(50),
        ));
        pipeline_result.add_result(TargetResult::failed(
            "sprite:bad".to_string(),
            "Invalid syntax".to_string(),
            Duration::from_millis(10),
        ));

        let watch_result = convert_pipeline_result(&Ok(pipeline_result));
        assert!(!watch_result.success());
        assert_eq!(watch_result.files_processed, 2);
        assert_eq!(watch_result.sprites_rendered, 1); // Only successful ones
        assert_eq!(watch_result.build_errors.len(), 1);
    }

    #[test]
    fn test_convert_pipeline_result_error() {
        use crate::build::pipeline::BuildError as PipelineBuildError;

        let pipeline_error = PipelineBuildError::Build("Config error".to_string());
        let watch_result = convert_pipeline_result(&Err(pipeline_error));

        assert!(!watch_result.success());
        assert_eq!(watch_result.errors.len(), 1);
        assert!(watch_result.errors[0].contains("Config error"));
    }

    #[test]
    fn test_watch_with_pipeline_source_not_found() {
        use crate::config::default_config;

        let config = default_config();
        let context = BuildContext::new(config, PathBuf::from("/nonexistent/path"));
        let watch_config = WatchConfig::default();

        let result = watch_with_pipeline(context, watch_config);
        assert!(matches!(result, Err(WatchError::SourceNotFound(_))));
    }

    #[test]
    fn test_watch_with_incremental_source_not_found() {
        use crate::config::default_config;

        let config = default_config();
        let context = BuildContext::new(config, PathBuf::from("/nonexistent/path"));
        let watch_config = WatchConfig::default();

        let result = watch_with_incremental(context, watch_config, false);
        assert!(matches!(result, Err(WatchError::SourceNotFound(_))));
    }

    #[test]
    fn test_watch_with_incremental_force_mode() {
        use crate::config::default_config;

        let config = default_config();
        let context = BuildContext::new(config, PathBuf::from("/nonexistent/path"));
        let watch_config = WatchConfig::default();

        // Force mode should still fail if source doesn't exist
        let result = watch_with_incremental(context, watch_config, true);
        assert!(matches!(result, Err(WatchError::SourceNotFound(_))));
    }

    // Error display formatting tests

    #[test]
    fn test_target_id_to_display_name_sprite() {
        assert_eq!(target_id_to_display_name("sprite:player"), "player.pxl");
        assert_eq!(target_id_to_display_name("sprite:enemy_boss"), "enemy_boss.pxl");
    }

    #[test]
    fn test_target_id_to_display_name_animation() {
        assert_eq!(target_id_to_display_name("animation:walk"), "walk.pxl");
        assert_eq!(target_id_to_display_name("preview:idle"), "idle.pxl");
    }

    #[test]
    fn test_target_id_to_display_name_atlas() {
        // Atlas targets keep their original format
        assert_eq!(target_id_to_display_name("atlas:main"), "atlas:main");
        assert_eq!(target_id_to_display_name("export:godot"), "export:godot");
    }

    #[test]
    fn test_target_id_to_display_name_no_colon() {
        assert_eq!(target_id_to_display_name("something"), "something");
    }

    #[test]
    fn test_extract_line_number_basic() {
        assert_eq!(extract_line_number("error at line 5"), Some(5));
        assert_eq!(extract_line_number("Line 10: syntax error"), Some(10));
        assert_eq!(extract_line_number("invalid JSON at line 42"), Some(42));
    }

    #[test]
    fn test_extract_line_number_colon_format() {
        assert_eq!(extract_line_number("file.pxl:15:3: error"), Some(15));
        assert_eq!(extract_line_number("path/to/file.pxl:99"), Some(99));
    }

    #[test]
    fn test_extract_line_number_none() {
        assert_eq!(extract_line_number("no line number here"), None);
        assert_eq!(extract_line_number("error: something went wrong"), None);
    }

    #[test]
    fn test_format_error_display_with_line() {
        let formatted = format_error_display("sprite:player", "failed: Parse error at line 5");
        assert!(formatted.contains("Error in player.pxl:"));
        assert!(formatted.contains("Line 5:"));
        assert!(formatted.contains("Parse error"));
    }

    #[test]
    fn test_format_error_display_without_line() {
        let formatted = format_error_display("sprite:enemy", "File not found");
        assert!(formatted.contains("Error in enemy.pxl:"));
        assert!(formatted.contains("File not found"));
        // Should NOT have multi-line format when no line number
        assert!(!formatted.contains("\n          Line"));
    }

    #[test]
    fn test_format_error_display_strips_failed_prefix() {
        let formatted = format_error_display("sprite:test", "failed: Some error");
        // Should not have "failed:" in the output
        assert!(!formatted.contains("failed:"));
        assert!(formatted.contains("Some error"));
    }
}