warcraft-rs 0.7.0

Unified CLI for World of Warcraft file format parsing, conversion, and validation
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
//! M2 model file command implementations

use anyhow::{Context, Result};
use clap::Subcommand;
use std::path::PathBuf;

use wow_blp::parser::load_blp;
use wow_m2::{
    AnimFile, M2Converter, M2Model, M2Version, SkinFile,
    skin::{OldSkinHeader, SkinG, SkinHeaderT},
};

use crate::utils::{NodeType, TreeNode, TreeOptions, render_tree};

#[derive(Subcommand)]
pub enum M2Commands {
    /// Display information about an M2 model file
    Info {
        /// Path to the M2 file
        file: PathBuf,

        /// Show detailed information
        #[arg(short, long)]
        detailed: bool,
    },

    /// Validate an M2 model file
    Validate {
        /// Path to the M2 file
        file: PathBuf,

        /// Show all warnings (not just errors)
        #[arg(short, long)]
        warnings: bool,
    },

    /// Convert an M2 model to a different version
    Convert {
        /// Input M2 file
        input: PathBuf,

        /// Output M2 file
        output: PathBuf,

        /// Target version (e.g., "3.3.5a", "WotLK", "MoP")
        #[arg(long)]
        version: String,
    },

    /// Display M2 file structure as a tree
    Tree {
        /// Path to the M2 file
        file: PathBuf,

        /// Maximum depth to display
        #[arg(short, long, default_value = "5")]
        depth: usize,

        /// Include size information
        #[arg(short, long)]
        size: bool,

        /// Include references
        #[arg(short, long)]
        refs: bool,
    },

    /// Display information about a Skin file
    SkinInfo {
        /// Path to the Skin file
        file: PathBuf,

        /// Show detailed information
        #[arg(short, long)]
        detailed: bool,

        /// Parse old format
        #[arg(short, long)]
        old_format: bool,
    },

    /// Convert a Skin file to a different version
    SkinConvert {
        /// Input Skin file
        input: PathBuf,

        /// Output Skin file
        output: PathBuf,

        /// Target version (e.g., "3.3.5a", "WotLK", "MoP")
        #[arg(long)]
        version: String,
    },

    /// Display information about an ANIM file
    AnimInfo {
        /// Path to the ANIM file
        file: PathBuf,

        /// Show detailed information
        #[arg(short, long)]
        detailed: bool,
    },

    /// Convert an ANIM file to a different version
    AnimConvert {
        /// Input ANIM file
        input: PathBuf,

        /// Output ANIM file
        output: PathBuf,

        /// Target version (e.g., "3.3.5a", "WotLK", "MoP")
        #[arg(long)]
        version: String,
    },

    /// Display information about a BLP texture file
    BlpInfo {
        /// Path to the BLP file
        file: PathBuf,

        /// Show detailed information
        #[arg(short, long)]
        detailed: bool,
    },
}

pub fn execute(cmd: M2Commands) -> Result<()> {
    match cmd {
        M2Commands::Info { file, detailed } => handle_info(file, detailed),
        M2Commands::Convert {
            input,
            output,
            version,
        } => handle_convert(input, output, version),
        M2Commands::Validate { file, warnings } => handle_validate(file, warnings),
        M2Commands::Tree {
            file,
            depth,
            size,
            refs,
        } => handle_tree(file, depth, size, refs),
        M2Commands::SkinInfo {
            file,
            detailed,
            old_format,
        } => {
            // Use auto-detection by default, with old_format as an override
            handle_skin_info_auto(file, detailed, old_format)
        }
        M2Commands::SkinConvert {
            input,
            output,
            version,
        } => handle_skin_convert(input, output, version),
        M2Commands::AnimInfo { file, detailed } => handle_anim_info(file, detailed),
        M2Commands::AnimConvert {
            input,
            output,
            version,
        } => handle_anim_convert(input, output, version),
        M2Commands::BlpInfo { file, detailed } => handle_blp_info(file, detailed),
    }
}

fn handle_info(path: PathBuf, detailed: bool) -> Result<()> {
    println!("Loading M2 model: {}", path.display());

    let m2_format = M2Model::load(&path)
        .with_context(|| format!("Failed to load M2 model from {}", path.display()))?;

    let model = m2_format.model();
    println!("\n=== M2 Model Information ===");

    // Display version information
    println!("Version: {}", model.header.version);
    if let Some(version) = model.header.version() {
        println!("Expansion: {:?}", version);
        println!(
            "Format: {}",
            if version >= M2Version::Legion {
                "Chunked (MD21)"
            } else {
                "Legacy (MD20)"
            }
        );
    } else {
        println!("Expansion: Unknown");
        println!("Format: Unknown");
    }

    // Display model name if available
    if let Some(ref name) = model.name {
        println!("Model Name: {}", name);
    }

    // Display basic counts
    println!("Vertices: {}", model.header.vertices.count);
    println!("Bones: {}", model.header.bones.count);
    println!("Animations: {}", model.header.animations.count);
    println!("Textures: {}", model.header.textures.count);

    // Display skin information
    if let Some(version) = model.header.version() {
        if version <= M2Version::TBC {
            println!("Skin Format: Embedded (Pre-WotLK)");
            println!("Skin Profiles: {}", model.header.views.count);
        } else {
            println!("Skin Format: External (WotLK+)");
            if let Some(count) = model.header.num_skin_profiles {
                println!("Skin Profiles: {}", count);
            }
        }
    }

    if detailed {
        println!("\n=== Detailed Information ===");
        println!("Global Sequences: {}", model.header.global_sequences.count);
        println!("Color Animations: {}", model.header.color_animations.count);
        println!(
            "Texture Animations: {}",
            model.header.texture_animations.count
        );
        println!("Key Bone Lookups: {}", model.header.key_bone_lookup.count);
        println!("Texture Units: {}", model.header.texture_units.count);

        // Bounding box information
        println!("\n--- Bounding Information ---");
        let bbox_min = model.header.bounding_box_min;
        let bbox_max = model.header.bounding_box_max;
        println!(
            "Bounding Box: [{:.2}, {:.2}, {:.2}] to [{:.2}, {:.2}, {:.2}]",
            bbox_min[0], bbox_min[1], bbox_min[2], bbox_max[0], bbox_max[1], bbox_max[2]
        );
        println!(
            "Bounding Sphere Radius: {:.2}",
            model.header.bounding_sphere_radius
        );

        // Collision information
        let col_min = model.header.collision_box_min;
        let col_max = model.header.collision_box_max;
        println!(
            "Collision Box: [{:.2}, {:.2}, {:.2}] to [{:.2}, {:.2}, {:.2}]",
            col_min[0], col_min[1], col_min[2], col_max[0], col_max[1], col_max[2]
        );
        println!(
            "Collision Sphere Radius: {:.2}",
            model.header.collision_sphere_radius
        );

        // Model flags
        println!("\n--- Model Flags ---");
        println!("Flags: {:?}", model.header.flags);
    }

    Ok(())
}

fn handle_convert(input: PathBuf, output: PathBuf, version_str: String) -> Result<()> {
    println!("Loading M2 model: {}", input.display());

    let m2_format = M2Model::load(&input)
        .with_context(|| format!("Failed to load M2 model from {}", input.display()))?;
    let model = m2_format.model();

    let target_version = M2Version::from_expansion_name(&version_str)
        .with_context(|| format!("Invalid target version: {version_str}"))?;

    println!("Converting to {target_version:?}");

    let converter = M2Converter::new();
    let converted = converter
        .convert(model, target_version)
        .with_context(|| "Failed to convert model")?;

    println!("Saving converted model to: {}", output.display());
    converted
        .save(&output)
        .with_context(|| format!("Failed to save converted model to {}", output.display()))?;

    println!("Conversion complete!");
    Ok(())
}

fn handle_validate(path: PathBuf, show_warnings: bool) -> Result<()> {
    println!("Validating M2 model: {}", path.display());

    let m2_format = M2Model::load(&path)
        .with_context(|| format!("Failed to load M2 model from {}", path.display()))?;
    let model = m2_format.model();

    // Validate the model
    match model.validate() {
        Ok(_) => {
            println!("✓ Model validation passed!");
        }
        Err(e) => {
            println!("❌ Model validation failed: {e}");
            if !show_warnings {
                println!("Use --warnings to show additional details");
            }
            std::process::exit(1);
        }
    }

    Ok(())
}

fn handle_tree(path: PathBuf, max_depth: usize, show_size: bool, show_refs: bool) -> Result<()> {
    println!("Loading M2 model: {}", path.display());

    let m2_format = M2Model::load(&path)
        .with_context(|| format!("Failed to load M2 model from {}", path.display()))?;
    let model = m2_format.model();

    // Load the original file data for embedded skin parsing
    let original_m2_data = std::fs::read(&path).with_context(|| {
        format!(
            "Failed to read original M2 file data from {}",
            path.display()
        )
    })?;

    // Determine version and format details
    let version_info = if let Some(version) = model.header.version() {
        format!("{:?} ({})", version, model.header.version)
    } else {
        format!("Unknown ({})", model.header.version)
    };

    let format_type = match model.header.version() {
        Some(v) if v >= M2Version::Legion => "Chunked (MD21)",
        Some(_) => "Legacy (MD20)",
        None => "Unknown",
    };

    // Build the main model tree
    let mut root = TreeNode::new(
        format!(
            "M2 Model: {}",
            path.file_name().unwrap_or_default().to_string_lossy()
        ),
        NodeType::Root,
    )
    .with_metadata("version", &version_info)
    .with_metadata("format", format_type)
    .with_metadata("path", &path.to_string_lossy());

    // Add header information
    let mut header_node = TreeNode::new("Header".to_string(), NodeType::Header)
        .with_metadata("magic", &String::from_utf8_lossy(&model.header.magic))
        .with_metadata("version", &model.header.version.to_string())
        .with_metadata("flags", &format!("{:?}", model.header.flags));

    if let Some(ref name) = model.name {
        header_node = header_node.with_metadata("model_name", name);
    }

    // Add bounding information
    let bounds_node = TreeNode::new("Bounding Data".to_string(), NodeType::Data)
        .with_metadata(
            "bounding_box_min",
            &format!("{:.2?}", model.header.bounding_box_min),
        )
        .with_metadata(
            "bounding_box_max",
            &format!("{:.2?}", model.header.bounding_box_max),
        )
        .with_metadata(
            "bounding_radius",
            &format!("{:.2}", model.header.bounding_sphere_radius),
        )
        .with_metadata(
            "collision_box_min",
            &format!("{:.2?}", model.header.collision_box_min),
        )
        .with_metadata(
            "collision_box_max",
            &format!("{:.2?}", model.header.collision_box_max),
        )
        .with_metadata(
            "collision_radius",
            &format!("{:.2}", model.header.collision_sphere_radius),
        );

    header_node = header_node.add_child(bounds_node);
    root = root.add_child(header_node);

    // Add geometry information
    let mut geometry_node = TreeNode::new("Geometry".to_string(), NodeType::Data)
        .with_metadata("vertices", &model.header.vertices.count.to_string())
        .with_metadata("bones", &model.header.bones.count.to_string());

    if show_size {
        geometry_node = geometry_node
            .with_metadata(
                "vertex_data_offset",
                &format!("0x{:x}", model.header.vertices.offset),
            )
            .with_metadata(
                "bone_data_offset",
                &format!("0x{:x}", model.header.bones.offset),
            );
    }

    root = root.add_child(geometry_node);

    // Add animation information
    let mut anim_node = TreeNode::new("Animations".to_string(), NodeType::Data)
        .with_metadata("sequences", &model.header.animations.count.to_string())
        .with_metadata(
            "global_sequences",
            &model.header.global_sequences.count.to_string(),
        )
        .with_metadata(
            "key_bone_lookups",
            &model.header.key_bone_lookup.count.to_string(),
        );

    if show_size {
        anim_node = anim_node
            .with_metadata(
                "animation_offset",
                &format!("0x{:x}", model.header.animations.offset),
            )
            .with_metadata(
                "global_seq_offset",
                &format!("0x{:x}", model.header.global_sequences.offset),
            );
    }

    root = root.add_child(anim_node);

    // Add texture information
    let mut texture_node = TreeNode::new("Textures".to_string(), NodeType::Data)
        .with_metadata("textures", &model.header.textures.count.to_string())
        .with_metadata(
            "texture_units",
            &model.header.texture_units.count.to_string(),
        )
        .with_metadata(
            "texture_lookups",
            &model.header.texture_lookup_table.count.to_string(),
        )
        .with_metadata(
            "texture_animations",
            &model.header.texture_animations.count.to_string(),
        );

    if show_size {
        texture_node = texture_node
            .with_metadata(
                "texture_offset",
                &format!("0x{:x}", model.header.textures.offset),
            )
            .with_metadata(
                "texture_unit_offset",
                &format!("0x{:x}", model.header.texture_units.offset),
            );
    }

    root = root.add_child(texture_node);

    // Add version-specific skin information
    if let Some(version) = model.header.version() {
        let skin_node = if version <= M2Version::TBC {
            // Pre-WotLK: Embedded skins
            let mut node = TreeNode::new("Skin Data (Embedded)".to_string(), NodeType::Data)
                .with_metadata("format", "Embedded (Pre-WotLK)")
                .with_metadata("profiles", &model.header.views.count.to_string());

            if show_size {
                node = node.with_metadata(
                    "views_offset",
                    &format!("0x{:x}", model.header.views.offset),
                );
            }

            // Actually parse embedded skin profiles and show detailed information
            for i in 0..model.header.views.count {
                let skin_profile_name = format!("Skin Profile {}", i);
                let mut profile_node = TreeNode::new(skin_profile_name, NodeType::Data)
                    .with_metadata("index", &i.to_string());

                // Try to parse the embedded skin
                match model.parse_embedded_skin(&original_m2_data, i as usize) {
                    Ok(skin) => {
                        profile_node = profile_node
                            .with_metadata("status", "✅ Parsed successfully")
                            .with_metadata("indices_count", &skin.indices().len().to_string())
                            .with_metadata("triangles_count", &skin.triangles().len().to_string())
                            .with_metadata("submeshes_count", &skin.submeshes().len().to_string());

                        // Add submesh details
                        if !skin.submeshes().is_empty() {
                            for (submesh_idx, submesh) in skin.submeshes().iter().enumerate() {
                                let submesh_name = format!("Submesh {}", submesh_idx);
                                let submesh_node = TreeNode::new(submesh_name, NodeType::Data)
                                    .with_metadata("id", &submesh.id.to_string())
                                    .with_metadata(
                                        "vertex_start",
                                        &submesh.vertex_start.to_string(),
                                    )
                                    .with_metadata(
                                        "vertex_count",
                                        &submesh.vertex_count.to_string(),
                                    )
                                    .with_metadata(
                                        "triangle_start",
                                        &submesh.triangle_start.to_string(),
                                    )
                                    .with_metadata(
                                        "triangle_count",
                                        &submesh.triangle_count.to_string(),
                                    )
                                    .with_metadata("bone_count", &submesh.bone_count.to_string())
                                    .with_metadata("bone_start", &submesh.bone_start.to_string());

                                profile_node = profile_node.add_child(submesh_node);
                            }
                        }
                    }
                    Err(e) => {
                        profile_node = profile_node
                            .with_metadata("status", &format!("❌ Parse failed: {}", e))
                            .with_metadata(
                                "note",
                                if i == 0 {
                                    "Main skin should be valid"
                                } else {
                                    "Secondary skins often contain invalid data"
                                },
                            );
                    }
                }

                node = node.add_child(profile_node);
            }

            node
        } else {
            // WotLK+: External skins
            let mut node = TreeNode::new("Skin Data (External)".to_string(), NodeType::Data)
                .with_metadata("format", "External (.skin files)");

            if let Some(count) = model.header.num_skin_profiles {
                node = node.with_metadata("profiles", &count.to_string());
            }

            // Try to parse external skin files
            let base_name = path.file_stem().and_then(|s| s.to_str()).unwrap_or("model");
            let skin_count = model.header.num_skin_profiles.unwrap_or(1);

            for i in 0..skin_count {
                let skin_filename = format!("{}{:02}.skin", base_name, i);
                let mut skin_path = path.clone();
                skin_path.set_file_name(&skin_filename);

                let mut skin_ref_node = TreeNode::new(skin_filename.clone(), NodeType::Reference)
                    .with_metadata("type", "External Skin File")
                    .with_metadata("index", &i.to_string());

                // Try to load and parse the external skin file
                match wow_m2::SkinFile::load(&skin_path) {
                    Ok(skin) => {
                        skin_ref_node = skin_ref_node
                            .with_metadata("status", "✅ Loaded successfully")
                            .with_metadata("indices_count", &skin.indices().len().to_string())
                            .with_metadata("triangles_count", &skin.triangles().len().to_string())
                            .with_metadata("submeshes_count", &skin.submeshes().len().to_string());

                        // Add submesh details for external skins too
                        if !skin.submeshes().is_empty() {
                            for (submesh_idx, submesh) in skin.submeshes().iter().enumerate() {
                                let submesh_name = format!("Submesh {}", submesh_idx);
                                let submesh_node = TreeNode::new(submesh_name, NodeType::Data)
                                    .with_metadata("id", &submesh.id.to_string())
                                    .with_metadata(
                                        "vertex_start",
                                        &submesh.vertex_start.to_string(),
                                    )
                                    .with_metadata(
                                        "vertex_count",
                                        &submesh.vertex_count.to_string(),
                                    )
                                    .with_metadata(
                                        "triangle_start",
                                        &submesh.triangle_start.to_string(),
                                    )
                                    .with_metadata(
                                        "triangle_count",
                                        &submesh.triangle_count.to_string(),
                                    )
                                    .with_metadata("bone_count", &submesh.bone_count.to_string())
                                    .with_metadata("bone_start", &submesh.bone_start.to_string());

                                skin_ref_node = skin_ref_node.add_child(submesh_node);
                            }
                        }
                    }
                    Err(e) => {
                        skin_ref_node = skin_ref_node
                            .with_metadata("status", &format!("❌ Not found/failed: {}", e))
                            .with_metadata("path", skin_path.to_string_lossy().as_ref());
                    }
                }

                node = node.add_child(skin_ref_node);
            }

            node
        };

        root = root.add_child(skin_node);
    }

    // Add material and rendering information
    let mut material_node = TreeNode::new("Materials & Rendering".to_string(), NodeType::Data)
        .with_metadata("render_flags", &model.header.render_flags.count.to_string())
        .with_metadata(
            "color_animations",
            &model.header.color_animations.count.to_string(),
        );

    if show_size {
        material_node = material_node
            .with_metadata(
                "render_flags_offset",
                &format!("0x{:x}", model.header.render_flags.offset),
            )
            .with_metadata(
                "color_anim_offset",
                &format!("0x{:x}", model.header.color_animations.offset),
            );
    }

    root = root.add_child(material_node);

    // Add animation data section showing preserved animation tracks
    let mut anim_data_node = TreeNode::new(
        "Animation Track Data (Preserved)".to_string(),
        NodeType::Data,
    );

    // Bone animation data summary
    let bone_anim_count = model.raw_data.bone_animation_data.len();
    if bone_anim_count > 0 {
        // Count tracks by type
        let mut translation_count = 0;
        let mut rotation_count = 0;
        let mut scale_count = 0;
        let mut total_keyframes = 0;

        for anim in &model.raw_data.bone_animation_data {
            match anim.track_type {
                wow_m2::model::TrackType::Translation => translation_count += 1,
                wow_m2::model::TrackType::Rotation => rotation_count += 1,
                wow_m2::model::TrackType::Scale => scale_count += 1,
            }
            // Each timestamp is 4 bytes
            total_keyframes += anim.timestamps.len() / 4;
        }

        let bone_node = TreeNode::new("Bone Animations".to_string(), NodeType::Data)
            .with_metadata("total_tracks", &bone_anim_count.to_string())
            .with_metadata("translation_tracks", &translation_count.to_string())
            .with_metadata("rotation_tracks", &rotation_count.to_string())
            .with_metadata("scale_tracks", &scale_count.to_string())
            .with_metadata("total_keyframes", &total_keyframes.to_string());
        anim_data_node = anim_data_node.add_child(bone_node);
    }

    // Particle emitter animation data summary
    let particle_anim_count = model.raw_data.particle_animation_data.len();
    if particle_anim_count > 0 {
        // Count tracks by type
        let mut track_counts: std::collections::HashMap<&str, usize> =
            std::collections::HashMap::new();
        let mut total_keyframes = 0;

        for anim in &model.raw_data.particle_animation_data {
            let track_name = match anim.track_type {
                wow_m2::model::ParticleTrackType::EmissionSpeed => "emission_speed",
                wow_m2::model::ParticleTrackType::EmissionRate => "emission_rate",
                wow_m2::model::ParticleTrackType::EmissionArea => "emission_area",
                wow_m2::model::ParticleTrackType::XYScale => "xy_scale",
                wow_m2::model::ParticleTrackType::ZScale => "z_scale",
                wow_m2::model::ParticleTrackType::Color => "color",
                wow_m2::model::ParticleTrackType::Transparency => "transparency",
                wow_m2::model::ParticleTrackType::Size => "size",
                wow_m2::model::ParticleTrackType::Intensity => "intensity",
                wow_m2::model::ParticleTrackType::ZSource => "z_source",
            };
            *track_counts.entry(track_name).or_insert(0) += 1;
            total_keyframes += anim.timestamps.len() / 4;
        }

        let emitter_count = model.particle_emitters.len();
        let particle_node =
            TreeNode::new("Particle Emitter Animations".to_string(), NodeType::Data)
                .with_metadata("emitters", &emitter_count.to_string())
                .with_metadata("total_tracks", &particle_anim_count.to_string())
                .with_metadata("total_keyframes", &total_keyframes.to_string())
                .with_metadata(
                    "track_types",
                    &format!("{} unique types", track_counts.len()),
                );
        anim_data_node = anim_data_node.add_child(particle_node);
    }

    // Ribbon emitter animation data summary
    let ribbon_anim_count = model.raw_data.ribbon_animation_data.len();
    if ribbon_anim_count > 0 {
        let mut color_count = 0;
        let mut alpha_count = 0;
        let mut height_above_count = 0;
        let mut height_below_count = 0;
        let mut total_keyframes = 0;

        for anim in &model.raw_data.ribbon_animation_data {
            match anim.track_type {
                wow_m2::model::RibbonTrackType::Color => color_count += 1,
                wow_m2::model::RibbonTrackType::Alpha => alpha_count += 1,
                wow_m2::model::RibbonTrackType::HeightAbove => height_above_count += 1,
                wow_m2::model::RibbonTrackType::HeightBelow => height_below_count += 1,
            }
            total_keyframes += anim.timestamps.len() / 4;
        }

        let emitter_count = model.ribbon_emitters.len();
        let ribbon_node = TreeNode::new("Ribbon Emitter Animations".to_string(), NodeType::Data)
            .with_metadata("emitters", &emitter_count.to_string())
            .with_metadata("total_tracks", &ribbon_anim_count.to_string())
            .with_metadata("color_tracks", &color_count.to_string())
            .with_metadata("alpha_tracks", &alpha_count.to_string())
            .with_metadata("height_above_tracks", &height_above_count.to_string())
            .with_metadata("height_below_tracks", &height_below_count.to_string())
            .with_metadata("total_keyframes", &total_keyframes.to_string());
        anim_data_node = anim_data_node.add_child(ribbon_node);
    }

    // Texture animation data summary
    let texture_anim_count = model.raw_data.texture_animation_data.len();
    if texture_anim_count > 0 {
        let mut translation_u_count = 0;
        let mut translation_v_count = 0;
        let mut rotation_count = 0;
        let mut scale_u_count = 0;
        let mut scale_v_count = 0;
        let mut total_keyframes = 0;

        for anim in &model.raw_data.texture_animation_data {
            match anim.track_type {
                wow_m2::model::TextureTrackType::TranslationU => translation_u_count += 1,
                wow_m2::model::TextureTrackType::TranslationV => translation_v_count += 1,
                wow_m2::model::TextureTrackType::Rotation => rotation_count += 1,
                wow_m2::model::TextureTrackType::ScaleU => scale_u_count += 1,
                wow_m2::model::TextureTrackType::ScaleV => scale_v_count += 1,
            }
            total_keyframes += anim.timestamps.len() / 4;
        }

        let anim_count = model.texture_animations.len();
        let texture_node = TreeNode::new("Texture Animations".to_string(), NodeType::Data)
            .with_metadata("animations", &anim_count.to_string())
            .with_metadata("total_tracks", &texture_anim_count.to_string())
            .with_metadata("translation_u_tracks", &translation_u_count.to_string())
            .with_metadata("translation_v_tracks", &translation_v_count.to_string())
            .with_metadata("rotation_tracks", &rotation_count.to_string())
            .with_metadata("scale_u_tracks", &scale_u_count.to_string())
            .with_metadata("scale_v_tracks", &scale_v_count.to_string())
            .with_metadata("total_keyframes", &total_keyframes.to_string());
        anim_data_node = anim_data_node.add_child(texture_node);
    }

    // Color animation data summary
    let color_anim_count = model.raw_data.color_animation_data.len();
    if color_anim_count > 0 {
        let mut color_count = 0;
        let mut alpha_count = 0;
        let mut total_keyframes = 0;

        for anim in &model.raw_data.color_animation_data {
            match anim.track_type {
                wow_m2::model::ColorTrackType::Color => color_count += 1,
                wow_m2::model::ColorTrackType::Alpha => alpha_count += 1,
            }
            total_keyframes += anim.timestamps.len() / 4;
        }

        let anim_count = model.color_animations.len();
        let color_node = TreeNode::new("Color Animations".to_string(), NodeType::Data)
            .with_metadata("animations", &anim_count.to_string())
            .with_metadata("total_tracks", &color_anim_count.to_string())
            .with_metadata("color_tracks", &color_count.to_string())
            .with_metadata("alpha_tracks", &alpha_count.to_string())
            .with_metadata("total_keyframes", &total_keyframes.to_string());
        anim_data_node = anim_data_node.add_child(color_node);
    }

    // Transparency animation data summary
    let transparency_anim_count = model.raw_data.transparency_animation_data.len();
    if transparency_anim_count > 0 {
        let mut total_keyframes = 0;

        for anim in &model.raw_data.transparency_animation_data {
            total_keyframes += anim.timestamps.len() / 4;
        }

        let anim_count = model.transparency_animations.len();
        let transparency_node =
            TreeNode::new("Transparency Animations".to_string(), NodeType::Data)
                .with_metadata("animations", &anim_count.to_string())
                .with_metadata("total_tracks", &transparency_anim_count.to_string())
                .with_metadata("total_keyframes", &total_keyframes.to_string());
        anim_data_node = anim_data_node.add_child(transparency_node);
    }

    // Event track data summary
    let event_data_count = model.raw_data.event_data.len();
    if event_data_count > 0 {
        let mut total_timestamps = 0;

        for event in &model.raw_data.event_data {
            total_timestamps += event.timestamps.len() / 4; // 4 bytes per u32 timestamp
        }

        let event_count = model.events.len();
        let event_node = TreeNode::new("Events".to_string(), NodeType::Data)
            .with_metadata("events", &event_count.to_string())
            .with_metadata("tracks_with_data", &event_data_count.to_string())
            .with_metadata("total_timestamps", &total_timestamps.to_string());
        anim_data_node = anim_data_node.add_child(event_node);
    }

    // Attachment animation data summary
    let attachment_anim_count = model.raw_data.attachment_animation_data.len();
    if attachment_anim_count > 0 {
        let mut total_keyframes = 0;

        for anim in &model.raw_data.attachment_animation_data {
            total_keyframes += anim.timestamps.len() / 4;
        }

        let attachment_count = model.attachments.len();
        let attachment_node = TreeNode::new("Attachments".to_string(), NodeType::Data)
            .with_metadata("attachments", &attachment_count.to_string())
            .with_metadata("total_tracks", &attachment_anim_count.to_string())
            .with_metadata("total_keyframes", &total_keyframes.to_string());
        anim_data_node = anim_data_node.add_child(attachment_node);
    }

    // Camera animation data summary
    let camera_anim_count = model.raw_data.camera_animation_data.len();
    if camera_anim_count > 0 {
        let mut total_keyframes = 0;

        for anim in &model.raw_data.camera_animation_data {
            total_keyframes += anim.timestamps.len() / 4;
        }

        let camera_count = model.cameras.len();
        let camera_node = TreeNode::new("Cameras".to_string(), NodeType::Data)
            .with_metadata("cameras", &camera_count.to_string())
            .with_metadata("total_tracks", &camera_anim_count.to_string())
            .with_metadata("total_keyframes", &total_keyframes.to_string());
        anim_data_node = anim_data_node.add_child(camera_node);
    }

    // Light animation data summary
    let light_anim_count = model.raw_data.light_animation_data.len();
    if light_anim_count > 0 {
        let mut total_keyframes = 0;

        for anim in &model.raw_data.light_animation_data {
            total_keyframes += anim.timestamps.len() / 4;
        }

        let light_count = model.lights.len();
        let light_node = TreeNode::new("Lights".to_string(), NodeType::Data)
            .with_metadata("lights", &light_count.to_string())
            .with_metadata("total_tracks", &light_anim_count.to_string())
            .with_metadata("total_keyframes", &total_keyframes.to_string());
        anim_data_node = anim_data_node.add_child(light_node);
    }

    // Only add the animation data section if we have any animation data
    let has_anim_data = bone_anim_count > 0
        || particle_anim_count > 0
        || ribbon_anim_count > 0
        || texture_anim_count > 0
        || color_anim_count > 0
        || transparency_anim_count > 0
        || event_data_count > 0
        || attachment_anim_count > 0
        || camera_anim_count > 0
        || light_anim_count > 0;

    if has_anim_data {
        anim_data_node =
            anim_data_node.with_metadata("status", "✅ Animation data preserved for roundtrip");
        root = root.add_child(anim_data_node);
    }

    // Add version-specific features
    if let Some(version) = model.header.version() {
        if version >= M2Version::Cataclysm
            && let Some(ref combos) = model.header.texture_combiner_combos
        {
            let combo_node = TreeNode::new(
                "Texture Combiner Combos (Cataclysm+)".to_string(),
                NodeType::Data,
            )
            .with_metadata("count", &combos.count.to_string())
            .with_metadata("offset", &format!("0x{:x}", combos.offset));
            root = root.add_child(combo_node);
        }

        if version >= M2Version::WotLK {
            // Add chunked format features for newer versions
            if version >= M2Version::Legion {
                let chunks_node = TreeNode::new(
                    "Chunked Format Features (Legion+)".to_string(),
                    NodeType::Data,
                )
                .with_metadata("format", "MD21 Chunked")
                .with_metadata("note", "Additional chunks may be present");
                root = root.add_child(chunks_node);
            }
        }
    }

    // Configure tree rendering options
    let options = TreeOptions {
        verbose: false,
        max_depth: Some(max_depth),
        show_external_refs: show_refs,
        no_color: false,
        show_metadata: true,
        compact: false,
    };

    let tree_output = render_tree(&root, &options);
    println!("{}", tree_output);

    Ok(())
}

fn handle_skin_info_auto(path: PathBuf, detailed: bool, force_old_format: bool) -> Result<()> {
    println!("Loading Skin file: {}", path.display());

    // Get file size for reference
    let file_size = std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0);

    // If force_old_format is specified, use the old parser directly
    if force_old_format {
        let skin = SkinG::<OldSkinHeader>::load(&path)
            .with_context(|| format!("Failed to load Skin file from {}", path.display()))?;

        println!("\n=== Skin Information ===");
        println!("Format: Old (forced via --old-format)");
        println!("File size: {} bytes", file_size);
        println!("Indices: {}", skin.indices.len());
        println!("Triangles: {}", skin.triangles.len());
        println!("Bone Indices: {}", skin.bone_indices.len());
        println!("Submeshes: {}", skin.submeshes.len());
        println!("Batches: {}", skin.batches.len());

        if detailed {
            print_skin_details(&skin.submeshes, &skin.batches);
            print_skin_samples(&skin.indices, &skin.triangles, &skin.bone_indices);
        }

        return Ok(());
    }

    // Use auto-detection
    let skin = SkinFile::load(&path)
        .with_context(|| format!("Failed to load Skin file from {}", path.display()))?;

    println!("\n=== Skin Information ===");

    let format_name = if skin.is_new_format() {
        "New (Cataclysm+)"
    } else {
        "Old (WotLK and earlier)"
    };
    println!("Format: {}", format_name);
    println!("File size: {} bytes", file_size);

    println!("Indices: {}", skin.indices().len());
    println!("Triangles: {}", skin.triangles().len());
    println!("Bone Indices: {}", skin.bone_indices().len());
    println!("Submeshes: {}", skin.submeshes().len());
    println!("Batches: {}", skin.batches().len());

    if detailed {
        print_skin_details(skin.submeshes(), skin.batches());
        print_skin_samples(skin.indices(), skin.triangles(), skin.bone_indices());
    }

    Ok(())
}

fn print_skin_details(
    submeshes: &[wow_m2::skin::SkinSubmesh],
    batches: &[wow_m2::skin::SkinBatch],
) {
    if !submeshes.is_empty() {
        println!("\n=== Submeshes ===");
        for (i, submesh) in submeshes.iter().enumerate() {
            println!(
                "  [{}] ID: {}, Vertices: {} (start: {}), Triangles: {} (start: {})",
                i,
                submesh.id,
                submesh.vertex_count,
                submesh.vertex_start,
                submesh.triangle_count,
                submesh.triangle_start
            );
            println!(
                "       Bones: {} (start: {}), Center: [{:.2}, {:.2}, {:.2}]",
                submesh.bone_count,
                submesh.bone_start,
                submesh.center[0],
                submesh.center[1],
                submesh.center[2]
            );
        }
    }

    if !batches.is_empty() {
        println!("\n=== Batches ===");
        for (i, batch) in batches.iter().enumerate() {
            println!(
                "  [{}] Submesh: {}, Shader: {}, Textures: {}, Material: {}",
                i,
                batch.skin_section_index,
                batch.shader_id,
                batch.texture_count,
                batch.material_index
            );
        }
    }
}

fn print_skin_samples(indices: &[u16], triangles: &[u16], bone_indices: &[u8]) {
    println!("\n=== Data Samples ===");

    // Show first few indices
    if !indices.is_empty() {
        let sample: Vec<_> = indices.iter().take(10).collect();
        println!("Indices (first 10): {:?}", sample);
        if indices.len() > 10 {
            println!("  ... and {} more", indices.len() - 10);
        }
    }

    // Show first few triangles (as groups of 3)
    if !triangles.is_empty() {
        println!("Triangles (first 3 faces):");
        for i in 0..3.min(triangles.len() / 3) {
            let base = i * 3;
            println!(
                "  Face {}: [{}, {}, {}]",
                i,
                triangles[base],
                triangles[base + 1],
                triangles[base + 2]
            );
        }
        if triangles.len() > 9 {
            println!("  ... and {} more faces", triangles.len() / 3 - 3);
        }
    }

    // Show first few bone indices (as groups of 4 if possible)
    if !bone_indices.is_empty() {
        println!("Bone indices (first 5 vertices):");
        for i in 0..5.min(bone_indices.len() / 4) {
            let base = i * 4;
            if base + 3 < bone_indices.len() {
                println!(
                    "  Vertex {}: [{}, {}, {}, {}]",
                    i,
                    bone_indices[base],
                    bone_indices[base + 1],
                    bone_indices[base + 2],
                    bone_indices[base + 3]
                );
            }
        }
        println!(
            "  Total: {} bytes ({} if 4 bytes/vertex = {} vertices)",
            bone_indices.len(),
            bone_indices.len(),
            bone_indices.len() / 4
        );
    }
}

#[allow(dead_code)]
fn handle_skin_info<H: SkinHeaderT + Clone>(path: PathBuf, detailed: bool) -> Result<()> {
    println!("Loading Skin file: {}", path.display());

    let _skin = SkinG::<H>::load(&path)
        .with_context(|| format!("Failed to load Skin file from {}", path.display()))?;

    println!("\n=== Skin Information ===");
    println!("File loaded successfully!");

    if detailed {
        println!("\n=== Detailed Information ===");
        println!("(Detailed information requires additional public API methods)");
    }

    Ok(())
}

fn handle_skin_convert(input: PathBuf, output: PathBuf, version_str: String) -> Result<()> {
    println!("Loading Skin file: {}", input.display());

    // Use SkinFile::load() for automatic format detection
    let skin = SkinFile::load(&input)
        .with_context(|| format!("Failed to load Skin file from {}", input.display()))?;

    let source_format = if skin.is_new_format() {
        "new format"
    } else {
        "old format"
    };
    println!("Detected source format: {}", source_format);

    let target_version = M2Version::from_expansion_name(&version_str)
        .with_context(|| format!("Invalid target version: {version_str}"))?;

    let target_format = if target_version.uses_new_skin_format() {
        "new format"
    } else {
        "old format"
    };
    println!("Converting to {:?} ({})...", target_version, target_format);

    // Actually perform the conversion
    let converted = skin
        .convert(target_version)
        .with_context(|| format!("Failed to convert skin to {:?}", target_version))?;

    println!("Saving converted Skin file to: {}", output.display());
    converted
        .save(&output)
        .with_context(|| format!("Failed to save converted Skin file to {}", output.display()))?;

    println!("Conversion complete!");
    Ok(())
}

fn handle_anim_info(path: PathBuf, detailed: bool) -> Result<()> {
    println!("Loading ANIM file: {}", path.display());

    let anim = AnimFile::load(&path)
        .with_context(|| format!("Failed to load ANIM file from {}", path.display()))?;

    println!("\n=== ANIM Information ===");
    println!("Format: {:?}", anim.format);
    println!("Animation Sections: {}", anim.animation_count());

    if anim.is_legacy_format() {
        println!("Legacy Format: True");
    } else {
        println!("Modern Format: True");
    }

    // Show memory usage stats
    let usage = anim.memory_usage();
    println!("Total Keyframes: {}", usage.total_keyframes());
    println!("Memory Usage: ~{} bytes", usage.approximate_bytes);

    if detailed {
        println!("\n=== Detailed Information ===");

        // Show format-specific metadata
        match &anim.metadata {
            wow_m2::AnimMetadata::Legacy {
                file_size,
                animation_count,
                structure_hints,
            } => {
                println!("File Size: {} bytes", file_size);
                println!("Animation Count (metadata): {}", animation_count);
                println!("Structure Valid: {}", structure_hints.appears_valid);
                println!("Estimated Blocks: {}", structure_hints.estimated_blocks);
                println!("Has Timestamps: {}", structure_hints.has_timestamps);
            }
            wow_m2::AnimMetadata::Modern { header, entries } => {
                println!("ANIM Version: {}", header.version);
                println!("ID Count: {}", header.id_count);
                println!("Entry Offset: {}", header.anim_entry_offset);
                println!("Entry Count: {}", entries.len());

                if !entries.is_empty() {
                    println!("\n=== Animation Entries ===");
                    for (i, entry) in entries.iter().enumerate() {
                        println!(
                            "Entry {}: ID={}, Offset={}, Size={}",
                            i, entry.id, entry.offset, entry.size
                        );
                    }
                }
            }
        }

        // Show memory breakdown
        println!("\n=== Memory Usage Breakdown ===");
        println!("Sections: {}", usage.sections);
        println!("Bone Animations: {}", usage.bone_animations);
        println!("Translation Keyframes: {}", usage.translation_keyframes);
        println!("Rotation Keyframes: {}", usage.rotation_keyframes);
        println!("Scaling Keyframes: {}", usage.scaling_keyframes);

        // Show sections summary
        if !anim.sections.is_empty() {
            println!("\n=== Animation Sections ===");
            for (i, section) in anim.sections.iter().enumerate() {
                println!(
                    "Section {}: ID={}, Start={}, End={}, Bones={}",
                    i,
                    section.header.id,
                    section.header.start,
                    section.header.end,
                    section.bone_animations.len()
                );
            }
        }
    }

    Ok(())
}

fn handle_anim_convert(input: PathBuf, output: PathBuf, version_str: String) -> Result<()> {
    println!("Loading ANIM file: {}", input.display());

    let anim = AnimFile::load(&input)
        .with_context(|| format!("Failed to load ANIM file from {}", input.display()))?;

    let target_version = M2Version::from_expansion_name(&version_str)
        .with_context(|| format!("Invalid target version: {version_str}"))?;

    println!("Source Format: {:?}", anim.format);
    println!("Converting to {target_version:?}");

    let converted = anim.convert(target_version);
    println!("Target Format: {:?}", converted.format);

    if converted.format == anim.format {
        println!("Note: No format conversion needed - same format for target version");
    }

    println!("Saving converted ANIM file to: {}", output.display());
    converted
        .save(&output)
        .with_context(|| format!("Failed to save converted ANIM file to {}", output.display()))?;

    println!("Conversion complete!");
    Ok(())
}

fn handle_blp_info(path: PathBuf, detailed: bool) -> Result<()> {
    println!("Loading BLP texture: {}", path.display());

    let _blp = load_blp(&path)
        .with_context(|| format!("Failed to load BLP texture from {}", path.display()))?;

    println!("\n=== BLP Texture Information ===");
    println!("File loaded successfully!");

    if detailed {
        println!("\n=== Detailed Information ===");
        println!("(Detailed information requires additional public API methods)");
    }

    Ok(())
}