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
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
//! Build pipeline orchestration.
//!
//! The pipeline coordinates the execution of build targets in the correct order.

use crate::atlas::{pack_atlas, AtlasBox, AtlasConfig as PackerConfig, SpriteInput};
use crate::build::{BuildContext, BuildPlan, BuildResult, BuildTarget, TargetKind, TargetResult};
use crate::models::TtpObject;
use crate::parser::parse_stream;
use crate::registry::{PaletteRegistry, ResolvedSprite, SpriteRegistry};
use crate::renderer::{render_resolved, render_sprite};
use rayon::prelude::*;
use std::collections::HashMap;
use std::fs::{self, File};
use std::io::BufReader;
use std::path::PathBuf;
use std::time::Instant;

/// Error during build execution.
#[derive(Debug, thiserror::Error)]
pub enum BuildError {
    /// Discovery error
    #[error("Discovery error: {0}")]
    Discovery(#[from] crate::build::DiscoveryError),
    /// Build order error (circular dependencies)
    #[error("Build order error: {0}")]
    BuildOrder(#[from] crate::build::target::BuildOrderError),
    /// IO error
    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),
    /// Generic build error
    #[error("Build error: {0}")]
    Build(String),
}

/// Build pipeline for executing builds.
pub struct BuildPipeline {
    /// Build context
    context: BuildContext,
    /// Whether to stop on first error
    fail_fast: bool,
    /// Whether to do a dry run (don't actually build)
    dry_run: bool,
}

impl BuildPipeline {
    /// Create a new build pipeline.
    pub fn new(context: BuildContext) -> Self {
        Self { context, fail_fast: false, dry_run: false }
    }

    /// Set fail-fast mode (stop on first error).
    pub fn with_fail_fast(mut self, fail_fast: bool) -> Self {
        self.fail_fast = fail_fast;
        self
    }

    /// Set dry-run mode (don't actually build).
    pub fn with_dry_run(mut self, dry_run: bool) -> Self {
        self.dry_run = dry_run;
        self
    }

    /// Run the build pipeline.
    ///
    /// Discovers sources, creates a build plan, and executes it.
    pub fn build(&self) -> Result<BuildResult, BuildError> {
        let start = Instant::now();

        // Create build plan from config
        let plan = crate::build::create_build_plan(&self.context)?;

        // Apply target filter if specified
        let plan = if let Some(filter) = self.context.target_filter() {
            plan.filter(filter)
        } else {
            plan
        };

        // Execute the plan
        let mut result = self.execute_plan(&plan)?;
        result.total_duration = start.elapsed();

        Ok(result)
    }

    /// Run the build pipeline with a pre-created plan.
    pub fn build_plan(&self, plan: &BuildPlan) -> Result<BuildResult, BuildError> {
        let start = Instant::now();
        let mut result = self.execute_plan(plan)?;
        result.total_duration = start.elapsed();
        Ok(result)
    }

    /// Execute a build plan.
    fn execute_plan(&self, plan: &BuildPlan) -> Result<BuildResult, BuildError> {
        let mut result = BuildResult::new();

        // Get targets in build order
        let ordered = plan.build_order()?;

        if self.context.is_verbose() {
            println!("Build plan: {} targets", ordered.len());
            for target in &ordered {
                println!("  - {} ({})", target.id, target.kind);
            }
        }

        // Ensure output directory exists
        if !self.dry_run {
            fs::create_dir_all(self.context.out_dir())?;
        }

        // Execute each target
        for target in ordered {
            let target_result = self.execute_target(target);

            if target_result.status.is_failure() && self.fail_fast {
                result.add_result(target_result);
                return Ok(result);
            }

            result.add_result(target_result);
        }

        Ok(result)
    }

    /// Execute a single build target.
    fn execute_target(&self, target: &BuildTarget) -> TargetResult {
        let start = Instant::now();

        if self.context.is_verbose() {
            println!("Building: {} ...", target.id);
        }

        if self.dry_run {
            return TargetResult::skipped(target.id.clone());
        }

        // Ensure parent directory exists for output
        if let Some(parent) = target.output.parent() {
            if let Err(e) = fs::create_dir_all(parent) {
                return TargetResult::failed(
                    target.id.clone(),
                    format!("Failed to create output directory: {}", e),
                    start.elapsed(),
                );
            }
        }

        // Execute based on target kind
        let build_result = match target.kind {
            TargetKind::Sprite => self.build_sprite(target),
            TargetKind::Atlas => self.build_atlas(target),
            TargetKind::Animation => self.build_animation(target),
            TargetKind::AnimationPreview => self.build_animation_preview(target),
            TargetKind::Export => self.build_export(target),
        };

        let duration = start.elapsed();

        match build_result {
            Ok(outputs) => {
                if self.context.is_verbose() {
                    println!("  Done in {:?}", duration);
                }
                TargetResult::success(target.id.clone(), outputs, duration)
            }
            Err(e) => {
                if self.context.is_verbose() {
                    println!("  Failed: {}", e);
                }
                TargetResult::failed(target.id.clone(), e, duration)
            }
        }
    }

    /// Build a sprite target.
    ///
    /// Parses the source .pxl file, resolves palettes, renders the sprite,
    /// and saves it as a PNG file.
    fn build_sprite(&self, target: &BuildTarget) -> Result<Vec<PathBuf>, String> {
        // Validate sources exist
        for source in &target.sources {
            if !source.exists() {
                return Err(format!("Source file not found: {}", source.display()));
            }
        }

        // Get the source file (sprites have exactly one source)
        let source = target
            .sources
            .first()
            .ok_or_else(|| "No source file specified for sprite target".to_string())?;

        // Parse the source file
        let file = File::open(source)
            .map_err(|e| format!("Failed to open {}: {}", source.display(), e))?;
        let reader = BufReader::new(file);
        let parse_result = parse_stream(reader);

        // Check for parse warnings (these may indicate problems)
        if !parse_result.warnings.is_empty() && self.context.is_strict() {
            let warnings: Vec<String> =
                parse_result.warnings.iter().map(|w| w.message.clone()).collect();
            return Err(format!("Parse warnings in {}: {}", source.display(), warnings.join("; ")));
        }

        // Build palette and sprite registries from parsed objects
        let mut palette_registry = PaletteRegistry::new();
        let mut sprite_registry = SpriteRegistry::new();
        let mut sprites = Vec::new();
        for obj in parse_result.objects {
            match obj {
                TtpObject::Palette(p) => {
                    palette_registry.register(p);
                }
                TtpObject::Sprite(s) => {
                    sprites.push(s);
                }
                _ => {
                    // Ignore other object types for now (animations, compositions, etc.)
                }
            }
        }

        // Register all sprites (needed for source resolution)
        for sprite in &sprites {
            sprite_registry.register_sprite(sprite.clone());
        }

        // Find the sprite to render (use the target name or first sprite)
        let sprite_name = if sprites.len() == 1 {
            sprites[0].name.clone()
        } else {
            // Try to find sprite by target name
            sprites.iter().find(|s| s.name == target.name).map(|s| s.name.clone()).ok_or_else(
                || format!("Sprite '{}' not found in {}", target.name, source.display()),
            )?
        };

        let sprite = sprite_registry
            .get_sprite(&sprite_name)
            .ok_or_else(|| format!("Sprite '{}' not found in registry", sprite_name))?;

        // Determine if we need transform resolution (has source reference or transforms)
        let needs_transform_resolution = sprite.source.is_some() || sprite.transform.is_some();

        // Render the sprite (with or without transforms)
        let (image, render_warnings) = if needs_transform_resolution {
            // Use SpriteRegistry to resolve source references and apply transforms
            let resolved = sprite_registry
                .resolve(&sprite_name, &palette_registry, self.context.is_strict())
                .map_err(|e| format!("Failed to resolve sprite '{}': {}", sprite_name, e))?;

            // Log any resolution warnings
            if self.context.is_verbose() {
                for warning in &resolved.warnings {
                    eprintln!("Warning: sprite '{}': {}", sprite_name, warning.message);
                }
            }

            render_resolved(&resolved)
        } else {
            // No transforms - use direct rendering with palette resolution
            let resolved_palette = if self.context.is_strict() {
                palette_registry.resolve_strict(sprite).map_err(|e| {
                    format!("Failed to resolve palette for '{}': {}", sprite.name, e)
                })?
            } else {
                let result = palette_registry.resolve_lenient(sprite);
                if let Some(warning) = result.warning {
                    if self.context.is_verbose() {
                        eprintln!("Warning: {}", warning.message);
                    }
                }
                result.palette
            };

            render_sprite(sprite, &resolved_palette.colors)
        };

        // Handle render warnings
        if !render_warnings.is_empty() {
            if self.context.is_strict() {
                let warnings: Vec<String> =
                    render_warnings.iter().map(|w| w.message.clone()).collect();
                return Err(format!(
                    "Render warnings for '{}': {}",
                    sprite.name,
                    warnings.join("; ")
                ));
            } else if self.context.is_verbose() {
                for warning in &render_warnings {
                    eprintln!("Warning: sprite '{}': {}", sprite.name, warning.message);
                }
            }
        }

        // Apply scale if configured
        let scale = self.context.default_scale();
        let final_image = if scale > 1 {
            image::imageops::resize(
                &image,
                image.width() * scale,
                image.height() * scale,
                image::imageops::FilterType::Nearest,
            )
        } else {
            image
        };

        // Save the PNG
        final_image
            .save(&target.output)
            .map_err(|e| format!("Failed to save {}: {}", target.output.display(), e))?;

        Ok(vec![target.output.clone()])
    }

    /// Build an atlas target.
    ///
    /// Parses all source files, renders sprites in parallel, packs them into a
    /// texture atlas, and saves the atlas image and metadata JSON.
    fn build_atlas(&self, target: &BuildTarget) -> Result<Vec<std::path::PathBuf>, String> {
        // Validate sources exist
        for source in &target.sources {
            if !source.exists() {
                return Err(format!("Source file not found: {}", source.display()));
            }
        }

        // Look up the atlas configuration
        let atlas_config = self
            .context
            .config()
            .atlases
            .get(&target.name)
            .ok_or_else(|| format!("Atlas config '{}' not found", target.name))?;

        // Create packer config from atlas config
        let padding = self.context.config().effective_padding(atlas_config);
        let packer_config = PackerConfig {
            max_size: (atlas_config.max_size[0], atlas_config.max_size[1]),
            padding,
            power_of_two: atlas_config.power_of_two,
        };

        let scale = self.context.default_scale();
        let is_strict = self.context.is_strict();
        let is_verbose = self.context.is_verbose();
        let multi_source = target.sources.len() > 1;

        // Phase 1: Parse all source files and collect render tasks
        // Each render task contains resolved sprite data ready for rendering
        struct RenderTask {
            /// Resolved grid (with transforms applied if any)
            grid: Vec<String>,
            /// Resolved palette colors
            colors: HashMap<String, String>,
            /// The original sprite (for metadata)
            sprite: crate::models::Sprite,
            /// Qualified name for the atlas
            qualified_name: String,
        }

        let mut render_tasks: Vec<RenderTask> = Vec::new();

        for source in &target.sources {
            // Parse the source file
            let file = File::open(source)
                .map_err(|e| format!("Failed to open {}: {}", source.display(), e))?;
            let reader = BufReader::new(file);
            let parse_result = parse_stream(reader);

            // Build palette and sprite registries
            let mut palette_registry = PaletteRegistry::new();
            let mut sprite_registry = SpriteRegistry::new();
            let mut sprites = Vec::new();

            for obj in parse_result.objects {
                match obj {
                    TtpObject::Palette(p) => {
                        palette_registry.register(p);
                    }
                    TtpObject::Sprite(s) => {
                        sprites.push(s);
                    }
                    _ => {
                        // Ignore animations, compositions, etc. for atlas building
                    }
                }
            }

            // Register all sprites (needed for source resolution)
            for sprite in &sprites {
                sprite_registry.register_sprite(sprite.clone());
            }

            // Create render tasks for each sprite
            let file_stem = source.file_stem().and_then(|s| s.to_str()).unwrap_or("unknown");

            for sprite in sprites {
                let qualified_name = if multi_source {
                    format!("{}:{}", file_stem, sprite.name)
                } else {
                    sprite.name.clone()
                };

                // Determine if we need transform resolution
                let needs_transform_resolution =
                    sprite.source.is_some() || sprite.transform.is_some();

                let (grid, colors) = if needs_transform_resolution {
                    // Use SpriteRegistry to resolve source references and apply transforms
                    let resolved = sprite_registry
                        .resolve(&sprite.name, &palette_registry, is_strict)
                        .map_err(|e| {
                            format!(
                                "Failed to resolve sprite '{}' in {}: {}",
                                sprite.name,
                                source.display(),
                                e
                            )
                        })?;

                    // Log any resolution warnings
                    if is_verbose {
                        for warning in &resolved.warnings {
                            eprintln!("Warning: sprite '{}': {}", sprite.name, warning.message);
                        }
                    }

                    (resolved.grid, resolved.palette)
                } else {
                    // No transforms - use direct palette resolution
                    let resolved_palette = if is_strict {
                        palette_registry.resolve_strict(&sprite).map_err(|e| {
                            format!(
                                "Failed to resolve palette for '{}' in {}: {}",
                                sprite.name,
                                source.display(),
                                e
                            )
                        })?
                    } else {
                        let result = palette_registry.resolve_lenient(&sprite);
                        if let Some(warning) = result.warning {
                            if is_verbose {
                                eprintln!("Warning: {}", warning.message);
                            }
                        }
                        result.palette
                    };

                    (sprite.grid.clone(), resolved_palette.colors)
                };

                render_tasks.push(RenderTask { grid, colors, sprite, qualified_name });
            }
        }

        // Phase 2: Render sprites in parallel using Rayon
        let render_results: Vec<Result<SpriteInput, String>> = render_tasks
            .into_par_iter()
            .map(|task| {
                // Render the sprite using resolved grid and colors
                let resolved = ResolvedSprite {
                    name: task.sprite.name.clone(),
                    size: task.sprite.size,
                    grid: task.grid,
                    palette: task.colors,
                    warnings: vec![],
                    nine_slice: task.sprite.nine_slice.clone(),
                };
                let (image, render_warnings) = render_resolved(&resolved);

                // Handle render warnings
                if !render_warnings.is_empty() {
                    if is_strict {
                        let warnings: Vec<String> =
                            render_warnings.iter().map(|w| w.message.clone()).collect();
                        return Err(format!(
                            "Render warnings for '{}': {}",
                            task.sprite.name,
                            warnings.join("; ")
                        ));
                    } else if is_verbose {
                        for warning in &render_warnings {
                            eprintln!(
                                "Warning: sprite '{}': {}",
                                task.sprite.name, warning.message
                            );
                        }
                    }
                }

                // Apply scale if configured
                let final_image = if scale > 1 {
                    image::imageops::resize(
                        &image,
                        image.width() * scale,
                        image.height() * scale,
                        image::imageops::FilterType::Nearest,
                    )
                } else {
                    image
                };

                // Extract metadata (origin and boxes)
                let origin = task.sprite.metadata.as_ref().and_then(|m| m.origin);
                let boxes = task.sprite.metadata.as_ref().and_then(|m| {
                    m.boxes.as_ref().map(|b| {
                        b.iter()
                            .map(|(name, cb)| {
                                (name.clone(), AtlasBox { x: cb.x, y: cb.y, w: cb.w, h: cb.h })
                            })
                            .collect::<HashMap<_, _>>()
                    })
                });

                Ok(SpriteInput { name: task.qualified_name, image: final_image, origin, boxes })
            })
            .collect();

        // Collect results, propagating any errors
        let sprite_inputs: Vec<SpriteInput> =
            render_results.into_iter().collect::<Result<Vec<_>, _>>()?;

        if sprite_inputs.is_empty() {
            return Err(format!("No sprites found in source files for atlas '{}'", target.name));
        }

        // Pack sprites into atlas
        let base_name = target.output.file_stem().and_then(|s| s.to_str()).unwrap_or(&target.name);
        let result = pack_atlas(&sprite_inputs, &packer_config, base_name);

        if result.atlases.is_empty() {
            return Err("Failed to pack any sprites into atlas".to_string());
        }

        // Save atlas images and metadata
        let mut outputs = Vec::new();
        let out_dir = target.output.parent().unwrap_or_else(|| std::path::Path::new("."));

        for (image, metadata) in &result.atlases {
            // Save the PNG
            let png_path = out_dir.join(&metadata.image);
            image
                .save(&png_path)
                .map_err(|e| format!("Failed to save atlas PNG {}: {}", png_path.display(), e))?;
            outputs.push(png_path);

            // Save the JSON metadata
            let json_name = metadata.image.replace(".png", ".json");
            let json_path = out_dir.join(&json_name);
            let json_content = serde_json::to_string_pretty(&metadata)
                .map_err(|e| format!("Failed to serialize atlas metadata: {}", e))?;
            fs::write(&json_path, json_content).map_err(|e| {
                format!("Failed to write atlas JSON {}: {}", json_path.display(), e)
            })?;
            outputs.push(json_path);
        }

        Ok(outputs)
    }

    /// Build an animation target.
    fn build_animation(&self, target: &BuildTarget) -> Result<Vec<std::path::PathBuf>, String> {
        // Animation building will be implemented by downstream tasks
        for source in &target.sources {
            if !source.exists() {
                return Err(format!("Source file not found: {}", source.display()));
            }
        }
        Ok(vec![target.output.clone()])
    }

    /// Build an animation preview target.
    fn build_animation_preview(
        &self,
        target: &BuildTarget,
    ) -> Result<Vec<std::path::PathBuf>, String> {
        // Preview building will be implemented by downstream tasks
        for source in &target.sources {
            if !source.exists() {
                return Err(format!("Source file not found: {}", source.display()));
            }
        }
        Ok(vec![target.output.clone()])
    }

    /// Build an export target.
    ///
    /// Export targets transform atlas metadata into game engine-specific formats.
    /// The target ID format is "export:{format}:{atlas_name}".
    fn build_export(&self, target: &BuildTarget) -> Result<Vec<std::path::PathBuf>, String> {
        use crate::atlas::AtlasMetadata;
        use crate::export::{
            godot::{GodotExportOptions, GodotExporter},
            libgdx::{LibGdxExportOptions, LibGdxExporter},
            unity::{UnityExportOptions, UnityExporter, UnityFilterMode},
        };

        // Parse format from target ID (export:format:name)
        let parts: Vec<&str> = target.id.split(':').collect();
        if parts.len() < 3 {
            return Err(format!("Invalid export target ID: {}", target.id));
        }
        let format = parts[1];
        let atlas_name = parts[2];

        // Find the atlas JSON metadata file
        let atlas_json_path = self.context.out_dir().join(format!("{}.json", atlas_name));
        if !atlas_json_path.exists() {
            return Err(format!(
                "Atlas metadata not found: {}. Build the atlas first.",
                atlas_json_path.display()
            ));
        }

        // Load the atlas metadata
        let json_content = fs::read_to_string(&atlas_json_path)
            .map_err(|e| format!("Failed to read atlas metadata: {}", e))?;
        let metadata: AtlasMetadata = serde_json::from_str(&json_content)
            .map_err(|e| format!("Failed to parse atlas metadata: {}", e))?;

        // Ensure output directory exists
        if let Some(parent) = target.output.parent() {
            fs::create_dir_all(parent)
                .map_err(|e| format!("Failed to create output directory: {}", e))?;
        }

        // Export based on format
        let outputs = match format {
            "godot" => {
                let config = &self.context.config().exports.godot;
                let exporter = GodotExporter::new()
                    .with_resource_path(&config.resource_path)
                    .with_sprite_frames(config.sprite_frames)
                    .with_animation_player(config.animation_player);

                let options = GodotExportOptions {
                    resource_path: config.resource_path.clone(),
                    sprite_frames: config.sprite_frames,
                    animation_player: config.animation_player,
                    atlas_textures: true,
                    ..Default::default()
                };

                // Godot exports to a directory, not a single file
                let output_dir =
                    target.output.parent().unwrap_or_else(|| std::path::Path::new("."));

                exporter
                    .export_godot(&metadata, output_dir, &options)
                    .map_err(|e| format!("Godot export failed: {}", e))?
            }
            "unity" => {
                let config = &self.context.config().exports.unity;
                let filter_mode = UnityFilterMode::from_config(&config.filter_mode);
                let exporter = UnityExporter::new()
                    .with_pixels_per_unit(config.pixels_per_unit)
                    .with_filter_mode(filter_mode);

                let options = UnityExportOptions {
                    pixels_per_unit: config.pixels_per_unit,
                    filter_mode,
                    ..Default::default()
                };

                exporter
                    .export_unity(&metadata, &target.output, &options)
                    .map_err(|e| format!("Unity export failed: {}", e))?;

                vec![target.output.clone()]
            }
            "libgdx" => {
                let exporter = LibGdxExporter::new();
                let options = LibGdxExportOptions::default();

                exporter
                    .export_libgdx(&metadata, &target.output, &options)
                    .map_err(|e| format!("libGDX export failed: {}", e))?;

                vec![target.output.clone()]
            }
            _ => {
                return Err(format!("Unknown export format: {}", format));
            }
        };

        Ok(outputs)
    }
}

/// Builder for configuring and running builds.
pub struct Build {
    context: Option<BuildContext>,
    fail_fast: bool,
    dry_run: bool,
    verbose: bool,
    strict: bool,
    filter: Option<Vec<String>>,
}

impl Build {
    /// Create a new build builder.
    pub fn new() -> Self {
        Self {
            context: None,
            fail_fast: false,
            dry_run: false,
            verbose: false,
            strict: false,
            filter: None,
        }
    }

    /// Set the build context.
    pub fn context(mut self, context: BuildContext) -> Self {
        self.context = Some(context);
        self
    }

    /// Set fail-fast mode.
    pub fn fail_fast(mut self, fail_fast: bool) -> Self {
        self.fail_fast = fail_fast;
        self
    }

    /// Set dry-run mode.
    pub fn dry_run(mut self, dry_run: bool) -> Self {
        self.dry_run = dry_run;
        self
    }

    /// Set verbose mode.
    pub fn verbose(mut self, verbose: bool) -> Self {
        self.verbose = verbose;
        self
    }

    /// Set strict mode.
    pub fn strict(mut self, strict: bool) -> Self {
        self.strict = strict;
        self
    }

    /// Set target filter.
    pub fn filter(mut self, targets: Vec<String>) -> Self {
        self.filter = Some(targets);
        self
    }

    /// Run the build.
    pub fn run(self) -> Result<BuildResult, BuildError> {
        let mut context = self
            .context
            .ok_or_else(|| BuildError::Build("No build context provided".to_string()))?;

        context = context.with_verbose(self.verbose).with_strict(self.strict);

        if let Some(filter) = self.filter {
            context = context.with_filter(filter);
        }

        BuildPipeline::new(context)
            .with_fail_fast(self.fail_fast)
            .with_dry_run(self.dry_run)
            .build()
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::default_config;
    use std::fs::File;
    use std::io::Write;
    use tempfile::TempDir;

    fn create_test_context() -> (TempDir, BuildContext) {
        let temp = TempDir::new().unwrap();
        let config = default_config();
        let ctx = BuildContext::new(config, temp.path().to_path_buf());

        // Create source directory
        let src_dir = temp.path().join("src/pxl");
        fs::create_dir_all(&src_dir).unwrap();

        (temp, ctx)
    }

    #[test]
    fn test_build_pipeline_new() {
        let (_temp, ctx) = create_test_context();
        let pipeline = BuildPipeline::new(ctx);
        assert!(!pipeline.fail_fast);
        assert!(!pipeline.dry_run);
    }

    #[test]
    fn test_build_pipeline_with_options() {
        let (_temp, ctx) = create_test_context();
        let pipeline = BuildPipeline::new(ctx).with_fail_fast(true).with_dry_run(true);

        assert!(pipeline.fail_fast);
        assert!(pipeline.dry_run);
    }

    #[test]
    fn test_build_pipeline_empty_build() {
        let (_temp, ctx) = create_test_context();
        let pipeline = BuildPipeline::new(ctx);

        let result = pipeline.build().unwrap();
        assert!(result.is_success());
        assert_eq!(result.targets.len(), 0);
    }

    #[test]
    fn test_build_pipeline_dry_run() {
        let (temp, ctx) = create_test_context();

        // Create a source file
        let src_dir = temp.path().join("src/pxl");
        let sprite_file = src_dir.join("test.pxl");
        File::create(&sprite_file).unwrap().write_all(b"{}").unwrap();

        let pipeline = BuildPipeline::new(ctx).with_dry_run(true);
        let result = pipeline.build().unwrap();
        assert!(result.is_success());
    }

    #[test]
    fn test_build_builder() {
        let (_temp, ctx) = create_test_context();

        let result = Build::new().context(ctx).dry_run(true).verbose(false).run().unwrap();

        assert!(result.is_success());
    }

    #[test]
    fn test_execute_target_missing_source() {
        let (_temp, ctx) = create_test_context();
        let pipeline = BuildPipeline::new(ctx);

        let target = BuildTarget::sprite(
            "missing".to_string(),
            std::path::PathBuf::from("/nonexistent/file.pxl"),
            std::path::PathBuf::from("/output/missing.png"),
        );

        let result = pipeline.execute_target(&target);
        assert!(result.status.is_failure());
    }

    #[test]
    fn test_build_sprite_renders_png() {
        let (temp, ctx) = create_test_context();

        // Create a valid sprite file with inline palette
        let src_dir = temp.path().join("src/pxl");
        let sprite_file = src_dir.join("red_dot.pxl");
        let sprite_content = r##"{"type": "sprite", "name": "red_dot", "palette": {"{r}": "#FF0000"}, "grid": ["{r}"]}"##;
        File::create(&sprite_file).unwrap().write_all(sprite_content.as_bytes()).unwrap();

        // Create output directory
        let out_dir = temp.path().join("build");
        fs::create_dir_all(&out_dir).unwrap();
        let output_file = out_dir.join("red_dot.png");

        let pipeline = BuildPipeline::new(ctx);

        let target = BuildTarget::sprite("red_dot".to_string(), sprite_file, output_file.clone());

        let result = pipeline.execute_target(&target);
        assert!(result.status.is_success(), "Expected success, got: {:?}", result.status);
        assert!(output_file.exists(), "Output PNG file should exist");

        // Verify the PNG was created and has valid content
        let img = image::open(&output_file).expect("Should open as valid PNG");
        assert_eq!(img.width(), 1);
        assert_eq!(img.height(), 1);
    }

    #[test]
    fn test_build_sprite_with_named_palette() {
        let (temp, ctx) = create_test_context();

        // Create a sprite file with a named palette reference
        let src_dir = temp.path().join("src/pxl");
        let sprite_file = src_dir.join("green_pixel.pxl");
        let sprite_content = r##"{"type": "palette", "name": "colors", "colors": {"{g}": "#00FF00"}}
{"type": "sprite", "name": "green_pixel", "palette": "colors", "grid": ["{g}"]}"##;
        File::create(&sprite_file).unwrap().write_all(sprite_content.as_bytes()).unwrap();

        // Create output directory
        let out_dir = temp.path().join("build");
        fs::create_dir_all(&out_dir).unwrap();
        let output_file = out_dir.join("green_pixel.png");

        let pipeline = BuildPipeline::new(ctx);

        let target =
            BuildTarget::sprite("green_pixel".to_string(), sprite_file, output_file.clone());

        let result = pipeline.execute_target(&target);
        assert!(result.status.is_success(), "Expected success, got: {:?}", result.status);
        assert!(output_file.exists(), "Output PNG file should exist");

        // Verify the PNG was created with correct color
        let img = image::open(&output_file).expect("Should open as valid PNG").to_rgba8();
        let pixel = img.get_pixel(0, 0);
        assert_eq!(pixel[0], 0, "Red channel should be 0");
        assert_eq!(pixel[1], 255, "Green channel should be 255");
        assert_eq!(pixel[2], 0, "Blue channel should be 0");
    }

    #[test]
    fn test_build_sprite_2x2_grid() {
        let (temp, ctx) = create_test_context();

        // Create a 2x2 sprite
        let src_dir = temp.path().join("src/pxl");
        let sprite_file = src_dir.join("checkerboard.pxl");
        let sprite_content = r##"{"type": "sprite", "name": "checkerboard", "palette": {"{b}": "#000000", "{w}": "#FFFFFF"}, "grid": ["{b}{w}", "{w}{b}"]}"##;
        File::create(&sprite_file).unwrap().write_all(sprite_content.as_bytes()).unwrap();

        // Create output directory
        let out_dir = temp.path().join("build");
        fs::create_dir_all(&out_dir).unwrap();
        let output_file = out_dir.join("checkerboard.png");

        let pipeline = BuildPipeline::new(ctx);

        let target =
            BuildTarget::sprite("checkerboard".to_string(), sprite_file, output_file.clone());

        let result = pipeline.execute_target(&target);
        assert!(result.status.is_success(), "Expected success, got: {:?}", result.status);

        // Verify the dimensions
        let img = image::open(&output_file).expect("Should open as valid PNG");
        assert_eq!(img.width(), 2);
        assert_eq!(img.height(), 2);
    }

    #[test]
    fn test_build_sprite_with_source_and_transform() {
        let (temp, ctx) = create_test_context();

        // Create a sprite file with base sprite and derived sprite with transforms
        let src_dir = temp.path().join("src/pxl");
        let sprite_file = src_dir.join("arrows.pxl");
        // Base sprite is an arrow pointing right: {r}.. -> {r}
        // Derived sprite mirrors it horizontally to point left
        let sprite_content = r##"{"type": "palette", "name": "colors", "colors": {"{r}": "#FF0000", "{ }": "#00000000"}}
{"type": "sprite", "name": "arrow_right", "palette": "colors", "grid": ["{ }{r}", "{r}{r}", "{ }{r}"]}
{"type": "sprite", "name": "arrow_left", "palette": "colors", "source": "arrow_right", "transform": ["mirror-h"]}"##;
        File::create(&sprite_file).unwrap().write_all(sprite_content.as_bytes()).unwrap();

        // Create output directory
        let out_dir = temp.path().join("build");
        fs::create_dir_all(&out_dir).unwrap();
        let output_file = out_dir.join("arrow_left.png");

        let pipeline = BuildPipeline::new(ctx);

        let target =
            BuildTarget::sprite("arrow_left".to_string(), sprite_file, output_file.clone());

        let result = pipeline.execute_target(&target);
        assert!(result.status.is_success(), "Expected success, got: {:?}", result.status);
        assert!(output_file.exists(), "Output PNG file should exist");

        // Verify the PNG was created with correct mirrored content
        let img = image::open(&output_file).expect("Should open as valid PNG").to_rgba8();
        assert_eq!(img.width(), 2);
        assert_eq!(img.height(), 3);

        // After mirror-h, the pattern should be:
        // Original: { }{r}  ->  Mirrored: {r}{ }
        //           {r}{r}              {r}{r}
        //           { }{r}              {r}{ }
        // So top-left (0,0) should be red, top-right (1,0) should be transparent
        let top_left = img.get_pixel(0, 0);
        let top_right = img.get_pixel(1, 0);
        assert_eq!(top_left[0], 255, "Top-left red channel should be 255 (mirrored)");
        assert_eq!(top_left[3], 255, "Top-left alpha should be 255 (opaque red)");
        assert_eq!(top_right[3], 0, "Top-right alpha should be 0 (transparent)");
    }

    #[test]
    fn test_build_sprite_with_rotate_transform() {
        let (temp, ctx) = create_test_context();

        // Create a sprite file with a sprite and rotate transform
        let src_dir = temp.path().join("src/pxl");
        let sprite_file = src_dir.join("rotated.pxl");
        // Base sprite is 2x1 (red, green), rotated 90 degrees becomes 1x2
        let sprite_content = r##"{"type": "sprite", "name": "bar", "palette": {"{r}": "#FF0000", "{g}": "#00FF00"}, "grid": ["{r}{g}"]}
{"type": "sprite", "name": "rotated", "palette": {"{r}": "#FF0000", "{g}": "#00FF00"}, "source": "bar", "transform": ["rotate:90"]}"##;
        File::create(&sprite_file).unwrap().write_all(sprite_content.as_bytes()).unwrap();

        // Create output directory
        let out_dir = temp.path().join("build");
        fs::create_dir_all(&out_dir).unwrap();
        let output_file = out_dir.join("rotated.png");

        let pipeline = BuildPipeline::new(ctx);

        let target = BuildTarget::sprite("rotated".to_string(), sprite_file, output_file.clone());

        let result = pipeline.execute_target(&target);
        assert!(result.status.is_success(), "Expected success, got: {:?}", result.status);

        // After 90 degree rotation, 2x1 becomes 1x2
        let img = image::open(&output_file).expect("Should open as valid PNG").to_rgba8();
        assert_eq!(img.width(), 1, "Width should be 1 after 90 degree rotation");
        assert_eq!(img.height(), 2, "Height should be 2 after 90 degree rotation");
    }

    #[test]
    fn test_build_sprite_with_direct_transform() {
        let (temp, ctx) = create_test_context();

        // Create a sprite file with transform applied directly (no source)
        let src_dir = temp.path().join("src/pxl");
        let sprite_file = src_dir.join("tiled.pxl");
        // Base sprite is 1x1 red, tiled 2x2 becomes 2x2
        let sprite_content = r##"{"type": "sprite", "name": "tiled", "palette": {"{r}": "#FF0000"}, "grid": ["{r}"], "transform": [{"op": "tile", "w": 2, "h": 2}]}"##;
        File::create(&sprite_file).unwrap().write_all(sprite_content.as_bytes()).unwrap();

        // Create output directory
        let out_dir = temp.path().join("build");
        fs::create_dir_all(&out_dir).unwrap();
        let output_file = out_dir.join("tiled.png");

        let pipeline = BuildPipeline::new(ctx);

        let target = BuildTarget::sprite("tiled".to_string(), sprite_file, output_file.clone());

        let result = pipeline.execute_target(&target);
        assert!(result.status.is_success(), "Expected success, got: {:?}", result.status);

        // After 2x2 tiling, 1x1 becomes 2x2
        let img = image::open(&output_file).expect("Should open as valid PNG").to_rgba8();
        assert_eq!(img.width(), 2, "Width should be 2 after 2x2 tiling");
        assert_eq!(img.height(), 2, "Height should be 2 after 2x2 tiling");

        // All pixels should be red
        for y in 0..2 {
            for x in 0..2 {
                let pixel = img.get_pixel(x, y);
                assert_eq!(pixel[0], 255, "Red channel should be 255");
                assert_eq!(pixel[1], 0, "Green channel should be 0");
                assert_eq!(pixel[2], 0, "Blue channel should be 0");
            }
        }
    }

    fn create_atlas_test_context(atlas_name: &str, sources: Vec<&str>) -> (TempDir, BuildContext) {
        use crate::config::{AtlasConfig as ConfigAtlas, ProjectConfig, PxlConfig};

        let temp = TempDir::new().unwrap();

        // Create a config with an atlas definition
        let mut atlases = std::collections::HashMap::new();
        atlases.insert(
            atlas_name.to_string(),
            ConfigAtlas {
                sources: sources.into_iter().map(String::from).collect(),
                max_size: [1024, 1024],
                padding: Some(0),
                power_of_two: false,
                nine_slice: false,
            },
        );

        let config = PxlConfig {
            project: ProjectConfig {
                name: "test".to_string(),
                version: "0.1.0".to_string(),
                src: std::path::PathBuf::from("src/pxl"),
                out: std::path::PathBuf::from("build"),
            },
            atlases,
            ..default_config()
        };

        let ctx = BuildContext::new(config, temp.path().to_path_buf());

        // Create source directory
        let src_dir = temp.path().join("src/pxl");
        fs::create_dir_all(&src_dir).unwrap();

        (temp, ctx)
    }

    #[test]
    fn test_build_atlas_single_sprite() {
        let (temp, ctx) = create_atlas_test_context("test_atlas", vec!["sprites/*.pxl"]);

        // Create source directory and sprite file
        let src_dir = temp.path().join("src/pxl/sprites");
        fs::create_dir_all(&src_dir).unwrap();

        let sprite_file = src_dir.join("red.pxl");
        let sprite_content = r##"{"type": "sprite", "name": "red", "palette": {"{r}": "#FF0000"}, "grid": ["{r}{r}", "{r}{r}"]}"##;
        File::create(&sprite_file).unwrap().write_all(sprite_content.as_bytes()).unwrap();

        // Create output directory
        let out_dir = temp.path().join("build");
        fs::create_dir_all(&out_dir).unwrap();
        let output_file = out_dir.join("test_atlas.png");

        let pipeline = BuildPipeline::new(ctx);

        let target =
            BuildTarget::atlas("test_atlas".to_string(), vec![sprite_file], output_file.clone());

        let result = pipeline.execute_target(&target);
        assert!(result.status.is_success(), "Expected success, got: {:?}", result.status);

        // Verify PNG was created
        let png_path = out_dir.join("test_atlas.png");
        assert!(png_path.exists(), "Atlas PNG should exist");

        let img = image::open(&png_path).expect("Should open as valid PNG");
        assert_eq!(img.width(), 2);
        assert_eq!(img.height(), 2);

        // Verify JSON metadata was created
        let json_path = out_dir.join("test_atlas.json");
        assert!(json_path.exists(), "Atlas JSON should exist");

        let json_content = fs::read_to_string(&json_path).expect("Should read JSON");
        assert!(json_content.contains("\"red\""), "JSON should contain sprite name");
        assert!(json_content.contains("\"frames\""), "JSON should contain frames");
    }

    #[test]
    fn test_build_atlas_multiple_sprites() {
        let (temp, ctx) = create_atlas_test_context("chars", vec!["**/*.pxl"]);

        // Create source files
        let src_dir = temp.path().join("src/pxl");

        let red_file = src_dir.join("red.pxl");
        let red_content = r##"{"type": "sprite", "name": "red", "palette": {"{r}": "#FF0000"}, "grid": ["{r}"]}"##;
        File::create(&red_file).unwrap().write_all(red_content.as_bytes()).unwrap();

        let green_file = src_dir.join("green.pxl");
        let green_content = r##"{"type": "sprite", "name": "green", "palette": {"{g}": "#00FF00"}, "grid": ["{g}"]}"##;
        File::create(&green_file).unwrap().write_all(green_content.as_bytes()).unwrap();

        // Create output directory
        let out_dir = temp.path().join("build");
        fs::create_dir_all(&out_dir).unwrap();
        let output_file = out_dir.join("chars.png");

        let pipeline = BuildPipeline::new(ctx);

        let target = BuildTarget::atlas(
            "chars".to_string(),
            vec![red_file, green_file],
            output_file.clone(),
        );

        let result = pipeline.execute_target(&target);
        assert!(result.status.is_success(), "Expected success, got: {:?}", result.status);

        // Verify PNG was created
        let png_path = out_dir.join("chars.png");
        assert!(png_path.exists(), "Atlas PNG should exist");

        // Verify JSON contains both sprites
        let json_path = out_dir.join("chars.json");
        assert!(json_path.exists(), "Atlas JSON should exist");

        let json_content = fs::read_to_string(&json_path).expect("Should read JSON");
        // With multiple source files, names are qualified
        assert!(json_content.contains("red"), "JSON should contain red sprite");
        assert!(json_content.contains("green"), "JSON should contain green sprite");
    }

    #[test]
    fn test_build_atlas_with_metadata() {
        let (temp, ctx) = create_atlas_test_context("player", vec!["*.pxl"]);

        // Create source file with metadata
        let src_dir = temp.path().join("src/pxl");
        let sprite_file = src_dir.join("player.pxl");
        let sprite_content = r##"{"type": "sprite", "name": "player", "palette": {"{r}": "#FF0000"}, "grid": ["{r}{r}{r}{r}", "{r}{r}{r}{r}", "{r}{r}{r}{r}", "{r}{r}{r}{r}"], "metadata": {"origin": [2, 4], "boxes": {"hurt": {"x": 0, "y": 0, "w": 4, "h": 4}}}}"##;
        File::create(&sprite_file).unwrap().write_all(sprite_content.as_bytes()).unwrap();

        // Create output directory
        let out_dir = temp.path().join("build");
        fs::create_dir_all(&out_dir).unwrap();
        let output_file = out_dir.join("player.png");

        let pipeline = BuildPipeline::new(ctx);

        let target =
            BuildTarget::atlas("player".to_string(), vec![sprite_file], output_file.clone());

        let result = pipeline.execute_target(&target);
        assert!(result.status.is_success(), "Expected success, got: {:?}", result.status);

        // Verify JSON contains metadata
        let json_path = out_dir.join("player.json");
        let json_content = fs::read_to_string(&json_path).expect("Should read JSON");

        assert!(json_content.contains("\"origin\""), "JSON should contain origin");
        assert!(json_content.contains("\"boxes\""), "JSON should contain boxes");
        assert!(json_content.contains("\"hurt\""), "JSON should contain hurt box");
    }

    #[test]
    fn test_build_atlas_no_sprites_error() {
        let (temp, ctx) = create_atlas_test_context("empty", vec!["*.pxl"]);

        // Create source file with only a palette (no sprites)
        let src_dir = temp.path().join("src/pxl");
        let palette_file = src_dir.join("colors.pxl");
        let palette_content =
            r##"{"type": "palette", "name": "colors", "colors": {"{r}": "#FF0000"}}"##;
        File::create(&palette_file).unwrap().write_all(palette_content.as_bytes()).unwrap();

        // Create output directory
        let out_dir = temp.path().join("build");
        fs::create_dir_all(&out_dir).unwrap();
        let output_file = out_dir.join("empty.png");

        let pipeline = BuildPipeline::new(ctx);

        let target =
            BuildTarget::atlas("empty".to_string(), vec![palette_file], output_file.clone());

        let result = pipeline.execute_target(&target);
        assert!(result.status.is_failure(), "Should fail when no sprites found");
    }

    #[test]
    fn test_build_atlas_power_of_two() {
        use crate::config::{AtlasConfig as ConfigAtlas, ProjectConfig, PxlConfig};

        let temp = TempDir::new().unwrap();

        // Create a config with power_of_two enabled
        let mut atlases = std::collections::HashMap::new();
        atlases.insert(
            "pot".to_string(),
            ConfigAtlas {
                sources: vec!["*.pxl".to_string()],
                max_size: [1024, 1024],
                padding: Some(0),
                power_of_two: true,
                nine_slice: false,
            },
        );

        let config = PxlConfig {
            project: ProjectConfig {
                name: "test".to_string(),
                version: "0.1.0".to_string(),
                src: std::path::PathBuf::from("src/pxl"),
                out: std::path::PathBuf::from("build"),
            },
            atlases,
            ..default_config()
        };

        let ctx = BuildContext::new(config, temp.path().to_path_buf());

        // Create source file (3x3 sprite, should become 4x4 with PoT)
        let src_dir = temp.path().join("src/pxl");
        fs::create_dir_all(&src_dir).unwrap();

        let sprite_file = src_dir.join("small.pxl");
        let sprite_content = r##"{"type": "sprite", "name": "small", "palette": {"{r}": "#FF0000"}, "grid": ["{r}{r}{r}", "{r}{r}{r}", "{r}{r}{r}"]}"##;
        File::create(&sprite_file).unwrap().write_all(sprite_content.as_bytes()).unwrap();

        // Create output directory
        let out_dir = temp.path().join("build");
        fs::create_dir_all(&out_dir).unwrap();
        let output_file = out_dir.join("pot.png");

        let pipeline = BuildPipeline::new(ctx);

        let target = BuildTarget::atlas("pot".to_string(), vec![sprite_file], output_file.clone());

        let result = pipeline.execute_target(&target);
        assert!(result.status.is_success(), "Expected success, got: {:?}", result.status);

        // Verify PNG has power-of-two dimensions
        let png_path = out_dir.join("pot.png");
        let img = image::open(&png_path).expect("Should open as valid PNG");
        assert_eq!(img.width(), 4, "Width should be power of 2 (4)");
        assert_eq!(img.height(), 4, "Height should be power of 2 (4)");
    }

    #[test]
    fn test_build_atlas_with_transforms() {
        let (temp, ctx) = create_atlas_test_context("transformed", vec!["*.pxl"]);

        // Create source file with base and transformed sprites
        let src_dir = temp.path().join("src/pxl");
        let sprite_file = src_dir.join("shapes.pxl");
        // Base: 2x1 horizontal bar, Transform: tiled 1x2 to become 2x2
        let sprite_content = r##"{"type": "sprite", "name": "bar", "palette": {"{r}": "#FF0000"}, "grid": ["{r}{r}"]}
{"type": "sprite", "name": "block", "palette": {"{r}": "#FF0000"}, "source": "bar", "transform": [{"op": "tile", "w": 1, "h": 2}]}"##;
        File::create(&sprite_file).unwrap().write_all(sprite_content.as_bytes()).unwrap();

        // Create output directory
        let out_dir = temp.path().join("build");
        fs::create_dir_all(&out_dir).unwrap();
        let output_file = out_dir.join("transformed.png");

        let pipeline = BuildPipeline::new(ctx);

        let target =
            BuildTarget::atlas("transformed".to_string(), vec![sprite_file], output_file.clone());

        let result = pipeline.execute_target(&target);
        assert!(result.status.is_success(), "Expected success, got: {:?}", result.status);

        // Verify JSON metadata shows correct dimensions for transformed sprite
        let json_path = out_dir.join("transformed.json");
        let json_content = fs::read_to_string(&json_path).expect("Should read JSON");

        // Both sprites should be in the atlas
        assert!(json_content.contains("\"bar\""), "Atlas should contain original bar sprite");
        assert!(
            json_content.contains("\"block\""),
            "Atlas should contain transformed block sprite"
        );

        // Verify the atlas contains the correct frames with transformed dimensions
        // bar: 2x1, block: 2x2 (tiled 1x2)
        let metadata: serde_json::Value = serde_json::from_str(&json_content).unwrap();
        let frames = metadata.get("frames").expect("Should have frames");

        // Find the block frame and verify its dimensions (frame properties are direct, not nested)
        let block_frame = frames.get("block").expect("Should have block frame");
        assert_eq!(
            block_frame.get("w").and_then(|v| v.as_u64()),
            Some(2),
            "Block width should be 2"
        );
        assert_eq!(
            block_frame.get("h").and_then(|v| v.as_u64()),
            Some(2),
            "Block height should be 2 (tiled)"
        );
    }
}