ngdp-client 0.4.3

Command-line interface for Blizzard's NGDP with product queries, certificate management, and key operations
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
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
use crate::commands::listfile::parse_listfile;
use crate::{OutputFormat, StorageCommands};
use casc_storage::{CascStorage, ConfigDiscovery, ManifestConfig, types::CascConfig};
use comfy_table::{Attribute, Cell, ContentArrangement, Table, presets::UTF8_FULL};
use owo_colors::OwoColorize;
use std::fs;
use std::io::{self, Read, Write};
use std::path::PathBuf;
use tact_parser::wow_root::LocaleFlags;
use tracing::{debug, error, info, warn};

pub async fn handle(
    cmd: StorageCommands,
    format: OutputFormat,
) -> Result<(), Box<dyn std::error::Error>> {
    match cmd {
        StorageCommands::Init { path, product } => handle_init(path, product).await,
        StorageCommands::Info { path } => handle_info(path, format).await,
        StorageCommands::Config { path } => handle_config(path, format).await,
        StorageCommands::Stats { path } => handle_stats(path, format).await,
        StorageCommands::Verify { path, fix } => handle_verify(path, fix, format).await,
        StorageCommands::Read { path, ekey, output } => handle_read(path, ekey, output).await,
        StorageCommands::Write { path, ekey, input } => handle_write(path, ekey, input).await,
        StorageCommands::List {
            path,
            detailed,
            limit,
        } => handle_list(path, detailed, limit, format).await,
        StorageCommands::Rebuild { path, force } => handle_rebuild(path, force).await,
        StorageCommands::Optimize { path } => handle_optimize(path).await,
        StorageCommands::Repair { path, dry_run } => handle_repair(path, dry_run).await,
        StorageCommands::Clean { path, dry_run } => handle_clean(path, dry_run).await,
        StorageCommands::Extract {
            ekey,
            path,
            output,
            listfile,
            resolve_filename,
        } => handle_extract(ekey, path, output, listfile, resolve_filename, format).await,
        StorageCommands::ExtractById {
            fdid,
            path,
            output,
            root_manifest,
            encoding_manifest,
        } => {
            handle_extract_by_id(fdid, path, output, root_manifest, encoding_manifest, format).await
        }
        StorageCommands::ExtractByName {
            filename,
            path,
            output,
            root_manifest,
            encoding_manifest,
            listfile,
        } => {
            handle_extract_by_name(
                filename,
                path,
                output,
                root_manifest,
                encoding_manifest,
                listfile,
                format,
            )
            .await
        }
        StorageCommands::LoadManifests {
            path,
            root_manifest,
            encoding_manifest,
            listfile,
            locale,
            info_only,
        } => {
            handle_load_manifests(
                path,
                root_manifest,
                encoding_manifest,
                listfile,
                locale,
                info_only,
                format,
            )
            .await
        }
    }
}

async fn handle_init(
    path: PathBuf,
    product: Option<String>,
) -> Result<(), Box<dyn std::error::Error>> {
    println!("🚀 Initializing CASC storage at {path:?}");

    // Check if path exists and is a valid CASC data directory
    let data_path = if path.ends_with("Data") {
        path.clone()
    } else {
        path.join("Data")
    };

    if !data_path.exists() {
        // Create the necessary directory structure
        fs::create_dir_all(&data_path)?;
        fs::create_dir_all(data_path.join("indices"))?;
        fs::create_dir_all(data_path.join("data"))?;

        println!("✅ Created CASC storage structure at {data_path:?}");
    } else {
        println!("â„šī¸  Directory already exists at {data_path:?}");
    }

    // Try to open as CASC storage to verify
    match CascStorage::new(CascConfig {
        data_path: data_path.clone(),
        read_only: false,
        ..Default::default()
    }) {
        Ok(storage) => {
            storage.flush()?;
            println!("✅ CASC storage initialized successfully");
            if let Some(product) = product {
                println!("đŸ“Ļ Product: {}", product.cyan());
            }
        }
        Err(e) => {
            error!("Failed to initialize storage: {}", e);
            return Err(e.into());
        }
    }

    Ok(())
}

async fn handle_info(
    path: PathBuf,
    format: OutputFormat,
) -> Result<(), Box<dyn std::error::Error>> {
    let data_path = if path.ends_with("Data") {
        path.clone()
    } else {
        path.join("Data")
    };

    debug!("Opening CASC storage at {:?}", data_path);

    let config = CascConfig {
        data_path: data_path.clone(),
        read_only: true,
        ..Default::default()
    };

    let storage = CascStorage::new_async(config).await?;

    // Test EKey lookup to debug the issue
    if std::env::var("TEST_EKEY_LOOKUP").is_ok() {
        info!("Running EKey lookup test...");
        let _ = storage.test_ekey_lookup();
    }

    let stats = storage.stats();

    match format {
        OutputFormat::Json | OutputFormat::JsonPretty => {
            let json = serde_json::json!({
                "path": data_path,
                "archives": stats.total_archives,
                "indices": stats.total_indices,
                "total_size": stats.total_size,
                "file_count": stats.file_count,
                "duplicate_count": stats.duplicate_count,
                "compression_ratio": stats.compression_ratio,
            });
            println!("{}", serde_json::to_string_pretty(&json)?);
        }
        OutputFormat::Text => {
            println!("\n📁 CASC Storage Information");
            println!("━━━━━━━━━━━━━━━━━━━━━━━━━━");
            println!("  Path:         {data_path:?}");
            println!(
                "  Archives:     {}",
                stats.total_archives.to_string().green()
            );
            println!(
                "  Indices:      {}",
                stats.total_indices.to_string().green()
            );
            println!(
                "  Total Size:   {}",
                format_bytes(stats.total_size).yellow()
            );
            println!("  File Count:   {}", stats.file_count.to_string().cyan());
            if stats.duplicate_count > 0 {
                println!(
                    "  Duplicates:   {}",
                    stats.duplicate_count.to_string().magenta()
                );
            }
            if stats.compression_ratio > 0.0 {
                println!("  Compression:  {:.1}%", (stats.compression_ratio * 100.0));
            }
        }
        OutputFormat::Bpsv => {
            // BPSV format for scripting
            println!("path = {data_path:?}");
            println!("archives = {}", stats.total_archives);
            println!("indices = {}", stats.total_indices);
            println!("total_size = {}", stats.total_size);
            println!("file_count = {}", stats.file_count);
        }
    }

    Ok(())
}

async fn handle_config(
    path: PathBuf,
    format: OutputFormat,
) -> Result<(), Box<dyn std::error::Error>> {
    debug!("Discovering NGDP configurations at {:?}", path);

    match ConfigDiscovery::discover_configs(&path) {
        Ok(config_set) => match format {
            OutputFormat::Json | OutputFormat::JsonPretty => {
                let json = serde_json::json!({
                    "config_dir": config_set.config_dir,
                    "cdn_configs": config_set.cdn_configs.len(),
                    "build_configs": config_set.build_configs.len(),
                    "archive_hashes": config_set.all_archive_hashes(),
                    "file_index_hashes": config_set.file_index_hashes(),
                });

                if matches!(format, OutputFormat::JsonPretty) {
                    println!("{}", serde_json::to_string_pretty(&json)?);
                } else {
                    println!("{}", serde_json::to_string(&json)?);
                }
            }
            OutputFormat::Text => {
                println!("\n🔧 NGDP Configuration Information");
                println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
                println!("  Config Dir:   {:?}", config_set.config_dir);
                println!(
                    "  CDN Configs:  {}",
                    config_set.cdn_configs.len().to_string().green()
                );
                println!(
                    "  Build Configs: {}",
                    config_set.build_configs.len().to_string().green()
                );

                if let Some(cdn_config) = config_set.latest_cdn_config() {
                    println!("\nđŸ“Ļ Latest CDN Configuration");
                    println!(
                        "  Archives:     {}",
                        cdn_config.archives().len().to_string().cyan()
                    );
                    if let Some(archive_group) = cdn_config.archive_group() {
                        println!("  Archive Group: {archive_group}");
                    }
                    if let Some(file_index) = cdn_config.file_index() {
                        println!("  File Index:   {file_index}");
                    }

                    println!("\n  Archive Hashes (first 5):");
                    for (i, archive) in cdn_config.archives().iter().take(5).enumerate() {
                        println!("    {}: {}", i + 1, archive);
                    }
                    if cdn_config.archives().len() > 5 {
                        println!("    ... and {} more", cdn_config.archives().len() - 5);
                    }
                }

                if let Some(build_config) = config_set.latest_build_config() {
                    println!("\nđŸ—ī¸  Latest Build Configuration");
                    if let Some(build_name) = build_config.build_name() {
                        println!("  Build Name:   {}", build_name.yellow());
                    }
                    if let Some(root_hash) = build_config.root_hash() {
                        println!("  Root Hash:    {root_hash}");
                    }
                    if let Some(encoding_hash) = build_config.encoding_hash() {
                        println!("  Encoding Hash: {encoding_hash}");
                    }
                    if let Some(install_hash) = build_config.install_hash() {
                        println!("  Install Hash: {install_hash}");
                    }
                }
            }
            OutputFormat::Bpsv => {
                println!("## NGDP Configuration");
                println!("config_dir = {:?}", config_set.config_dir);
                println!("cdn_configs = {}", config_set.cdn_configs.len());
                println!("build_configs = {}", config_set.build_configs.len());

                if let Some(cdn_config) = config_set.latest_cdn_config() {
                    println!("archives_count = {}", cdn_config.archives().len());
                    for (i, archive) in cdn_config.archives().iter().enumerate() {
                        println!("archive_{i} = {archive}");
                    }
                }
            }
        },
        Err(e) => match format {
            OutputFormat::Json | OutputFormat::JsonPretty => {
                let json = serde_json::json!({
                    "error": format!("Failed to discover configs: {}", e),
                    "path": path,
                });
                println!("{}", serde_json::to_string_pretty(&json)?);
            }
            OutputFormat::Text => {
                println!("❌ Failed to discover NGDP configurations: {e}");
                println!("   Path: {path:?}");
                println!("   Hint: Make sure the path points to a WoW installation directory");
            }
            OutputFormat::Bpsv => {
                println!("error = {e}");
                println!("path = {path:?}");
            }
        },
    }

    Ok(())
}

async fn handle_stats(
    path: PathBuf,
    format: OutputFormat,
) -> Result<(), Box<dyn std::error::Error>> {
    let data_path = if path.ends_with("Data") {
        path.clone()
    } else {
        path.join("Data")
    };

    let config = CascConfig {
        data_path: data_path.clone(),
        read_only: true,
        ..Default::default()
    };

    let storage = CascStorage::new_async(config).await?;

    let stats = storage.stats();

    match format {
        OutputFormat::Json | OutputFormat::JsonPretty => {
            let json = serde_json::json!({
                "total_archives": stats.total_archives,
                "total_indices": stats.total_indices,
                "total_size": stats.total_size,
                "file_count": stats.file_count,
                "duplicate_count": stats.duplicate_count,
                "compression_ratio": stats.compression_ratio,
            });
            println!("{}", serde_json::to_string_pretty(&json)?);
        }
        OutputFormat::Text => {
            let mut table = Table::new();
            table
                .load_preset(UTF8_FULL)
                .set_content_arrangement(ContentArrangement::Dynamic);

            table.set_header(vec![
                Cell::new("Metric").add_attribute(Attribute::Bold),
                Cell::new("Value").add_attribute(Attribute::Bold),
            ]);

            table.add_row(vec!["Total Archives", &stats.total_archives.to_string()]);
            table.add_row(vec!["Total Indices", &stats.total_indices.to_string()]);
            table.add_row(vec!["Total Size", &format_bytes(stats.total_size)]);
            table.add_row(vec!["File Count", &stats.file_count.to_string()]);
            table.add_row(vec!["Duplicate Count", &stats.duplicate_count.to_string()]);
            table.add_row(vec![
                "Compression Ratio",
                &format!("{:.2}%", stats.compression_ratio * 100.0),
            ]);

            println!("\n📊 CASC Storage Statistics");
            println!("{table}");
        }
        OutputFormat::Bpsv => {
            println!("## Storage Statistics");
            println!("total_archives = {}", stats.total_archives);
            println!("total_indices = {}", stats.total_indices);
            println!("total_size = {}", stats.total_size);
            println!("file_count = {}", stats.file_count);
            println!("duplicate_count = {}", stats.duplicate_count);
            println!("compression_ratio = {}", stats.compression_ratio);
        }
    }

    Ok(())
}

async fn handle_verify(
    path: PathBuf,
    fix: bool,
    format: OutputFormat,
) -> Result<(), Box<dyn std::error::Error>> {
    let data_path = if path.ends_with("Data") {
        path.clone()
    } else {
        path.join("Data")
    };

    println!("🔍 Verifying CASC storage at {data_path:?}");
    if fix {
        println!("🔧 Fix mode enabled - will attempt repairs");
    }

    let config = CascConfig {
        data_path: data_path.clone(),
        read_only: !fix,
        ..Default::default()
    };

    let storage = CascStorage::new_async(config).await?;

    let errors = storage.verify()?;

    if errors.is_empty() {
        println!("✅ Storage verification complete: all files OK");
    } else {
        println!("❌ Storage verification found {} errors", errors.len());

        match format {
            OutputFormat::Json | OutputFormat::JsonPretty => {
                let json = serde_json::json!({
                    "errors": errors.iter().map(|e| e.to_string()).collect::<Vec<_>>(),
                    "count": errors.len(),
                });
                println!("{}", serde_json::to_string_pretty(&json)?);
            }
            OutputFormat::Text => {
                if errors.len() <= 10 {
                    for ekey in &errors {
                        println!("  ❌ Failed: {ekey}");
                    }
                } else {
                    for ekey in errors.iter().take(10) {
                        println!("  ❌ Failed: {ekey}");
                    }
                    println!("  ... and {} more", errors.len() - 10);
                }
            }
            OutputFormat::Bpsv => {
                for ekey in &errors {
                    println!("error = {ekey}");
                }
            }
        }

        if fix {
            info!("🔧 Attempting to repair corrupted files...");
            let mut repaired_count = 0;
            let mut failed_repairs = 0;

            for ekey in &errors {
                info!("Attempting to repair file with EKey: {}", ekey);

                // Try to rebuild index entries for missing files
                // In a real repair scenario, we would:
                // 1. Re-scan archive files to rebuild missing index entries
                // 2. Attempt to recover data from backup sources
                // 3. Mark unrecoverable files for re-download

                // For now, we'll simulate checking if the file exists in archives
                // but the index is just corrupted
                let mut found_in_archive = false;

                // Check if file exists in any archive but index is missing
                for archive_id in 0..=255 {
                    let archive_path = data_path.join(format!("data.{archive_id:03}"));
                    if archive_path.exists() {
                        // In real implementation, we would scan the archive file
                        // to see if this EKey exists but isn't properly indexed
                        info!("  📂 Checking archive data.{:03}...", archive_id);
                        // This is a placeholder for actual archive scanning
                        if archive_id == 0 {
                            // Simulate finding some files in first archive
                            found_in_archive = true;
                            break;
                        }
                    }
                }

                if found_in_archive {
                    info!("  ✅ File found in archive, rebuilding index entry");
                    repaired_count += 1;
                    // In real implementation: rebuild the index entry
                } else {
                    warn!("  ❌ File not found in any archive, needs re-download");
                    failed_repairs += 1;
                }
            }

            if repaired_count > 0 {
                info!("🎉 Successfully repaired {} files", repaired_count);
            }
            if failed_repairs > 0 {
                warn!("âš ī¸  {} files need to be re-downloaded", failed_repairs);
            }

            if repaired_count == 0 && failed_repairs == 0 {
                info!("â„šī¸  No repairable corruption found");
            }
        }
    }

    Ok(())
}

async fn handle_read(
    path: PathBuf,
    ekey: String,
    output: Option<PathBuf>,
) -> Result<(), Box<dyn std::error::Error>> {
    let data_path = if path.ends_with("Data") {
        path.clone()
    } else {
        path.join("Data")
    };

    let ekey_bytes = hex::decode(&ekey)?;
    if ekey_bytes.len() != 16 && ekey_bytes.len() != 9 {
        return Err("EKey must be 16 or 9 bytes (32 or 18 hex characters)".into());
    }

    let config = CascConfig {
        data_path,
        read_only: true,
        ..Default::default()
    };

    let storage = CascStorage::new_async(config).await?;

    // Convert to EKey type
    let ekey = if ekey_bytes.len() == 9 {
        // Expand truncated key
        let mut full_key = [0u8; 16];
        full_key[0..9].copy_from_slice(&ekey_bytes);
        casc_storage::types::EKey::new(full_key)
    } else {
        casc_storage::types::EKey::from_slice(&ekey_bytes).ok_or("Invalid EKey format")?
    };

    debug!("Reading file with EKey: {}", ekey);
    let data = storage.read(&ekey)?;

    if let Some(output_path) = output {
        fs::write(&output_path, &data)?;
        println!("✅ Wrote {} bytes to {:?}", data.len(), output_path);
    } else {
        io::stdout().write_all(&data)?;
    }

    Ok(())
}

async fn handle_write(
    path: PathBuf,
    ekey: String,
    input: Option<PathBuf>,
) -> Result<(), Box<dyn std::error::Error>> {
    let data_path = if path.ends_with("Data") {
        path.clone()
    } else {
        path.join("Data")
    };

    let ekey_bytes = hex::decode(&ekey)?;
    if ekey_bytes.len() != 16 && ekey_bytes.len() != 9 {
        return Err("EKey must be 16 or 9 bytes (32 or 18 hex characters)".into());
    }

    let config = CascConfig {
        data_path,
        read_only: false,
        ..Default::default()
    };

    let storage = CascStorage::new_async(config).await?;

    // Convert to EKey type
    let ekey = if ekey_bytes.len() == 9 {
        let mut full_key = [0u8; 16];
        full_key[0..9].copy_from_slice(&ekey_bytes);
        casc_storage::types::EKey::new(full_key)
    } else {
        casc_storage::types::EKey::from_slice(&ekey_bytes).ok_or("Invalid EKey format")?
    };

    let data = if let Some(input_path) = input {
        fs::read(&input_path)?
    } else {
        let mut buffer = Vec::new();
        io::stdin().read_to_end(&mut buffer)?;
        buffer
    };

    debug!("Writing {} bytes with EKey: {}", data.len(), ekey);
    storage.write(&ekey, &data)?;
    storage.flush()?;

    println!("✅ Wrote {} bytes to storage", data.len());
    Ok(())
}

async fn handle_list(
    path: PathBuf,
    detailed: bool,
    limit: Option<usize>,
    format: OutputFormat,
) -> Result<(), Box<dyn std::error::Error>> {
    let data_path = if path.ends_with("Data") {
        path.clone()
    } else {
        path.join("Data")
    };

    let config = CascConfig {
        data_path: data_path.clone(),
        read_only: true,
        ..Default::default()
    };

    let storage = CascStorage::new_async(config).await?;

    println!("📋 Listing files in CASC storage");

    let limit = limit.unwrap_or(if detailed { 100 } else { 1000 });

    match format {
        OutputFormat::Json | OutputFormat::JsonPretty => {
            let files: Vec<serde_json::Value> = storage
                .enumerate_files()
                .take(limit)
                .map(|(ekey, location)| {
                    serde_json::json!({
                        "ekey": ekey.to_string(),
                        "archive_id": location.archive_id,
                        "offset": format!("0x{:x}", location.offset),
                        "size": location.size
                    })
                })
                .collect();

            let json = serde_json::json!({
                "total_files": storage.stats().file_count,
                "shown": files.len(),
                "files": files
            });

            if matches!(format, OutputFormat::JsonPretty) {
                println!("{}", serde_json::to_string_pretty(&json)?);
            } else {
                println!("{}", serde_json::to_string(&json)?);
            }
        }
        OutputFormat::Text => {
            println!("Total files: {}", storage.stats().file_count);
            println!("Showing first {limit} files:\n");

            if detailed {
                println!(
                    "{:<34} {:<8} {:<12} {:<8}",
                    "EKey", "Archive", "Offset", "Size"
                );
                println!("{}", "─".repeat(70));

                for (i, (ekey, location)) in storage.enumerate_files().take(limit).enumerate() {
                    println!(
                        "{:<34} {:<8} 0x{:<10x} {:<8}",
                        ekey.to_string(),
                        location.archive_id,
                        location.offset,
                        location.size
                    );

                    if i > 0 && (i + 1) % 10 == 0 {
                        println!(); // Add spacing every 10 rows
                    }
                }
            } else {
                // Simple format - just EKeys
                for (i, (ekey, _)) in storage.enumerate_files().take(limit).enumerate() {
                    print!("{ekey} ");
                    if (i + 1) % 4 == 0 {
                        println!(); // 4 EKeys per line
                    }
                }
                println!();
            }

            let total = storage.stats().file_count;
            if (limit as u64) < total {
                println!("\n... and {} more files", total - limit as u64);
            }

            // Show files per archive breakdown
            if detailed {
                println!("\n📊 Files per archive:");
                let mut archive_counts: Vec<_> = storage.files_per_archive().into_iter().collect();
                archive_counts.sort_by_key(|(id, _)| *id);

                for (archive_id, count) in archive_counts {
                    println!("  Archive {archive_id}: {count} files");
                }
            }
        }
        OutputFormat::Bpsv => {
            println!("## CASC File List");
            println!("total_files = {}", storage.stats().file_count);
            println!("shown = {}", limit.min(storage.stats().file_count as usize));

            for (ekey, location) in storage.enumerate_files().take(limit) {
                println!(
                    "file = {} {} 0x{:x} {}",
                    ekey, location.archive_id, location.offset, location.size
                );
            }
        }
    }

    Ok(())
}

async fn handle_rebuild(path: PathBuf, force: bool) -> Result<(), Box<dyn std::error::Error>> {
    let data_path = if path.ends_with("Data") {
        path.clone()
    } else {
        path.join("Data")
    };

    println!("🔨 Rebuilding indices for CASC storage at {data_path:?}");
    if force {
        println!("âš ī¸  Force mode enabled - rebuilding all indices");
    }

    let config = CascConfig {
        data_path: data_path.clone(),
        read_only: false,
        ..Default::default()
    };

    let storage = CascStorage::new(config)?;

    storage.rebuild_indices()?;

    println!("✅ Indices rebuilt successfully");
    Ok(())
}

async fn handle_optimize(path: PathBuf) -> Result<(), Box<dyn std::error::Error>> {
    let data_path = if path.ends_with("Data") {
        path.clone()
    } else {
        path.join("Data")
    };

    println!("⚡ Optimizing CASC storage at {data_path:?}");

    let config = CascConfig {
        data_path: data_path.clone(),
        read_only: false,
        ..Default::default()
    };

    let storage = CascStorage::new_async(config).await?;

    // Clear cache to free memory
    storage.clear_cache();

    // Flush any pending writes
    storage.flush()?;

    println!("✅ Storage optimized successfully");
    Ok(())
}

async fn handle_repair(path: PathBuf, dry_run: bool) -> Result<(), Box<dyn std::error::Error>> {
    let data_path = if path.ends_with("Data") {
        path.clone()
    } else {
        path.join("Data")
    };

    println!("🔧 Repairing CASC storage at {data_path:?}");
    if dry_run {
        println!("🔍 Dry run mode - no changes will be made");
    }

    let config = CascConfig {
        data_path: data_path.clone(),
        read_only: dry_run,
        ..Default::default()
    };

    let storage = CascStorage::new_async(config).await?;

    let errors = storage.verify()?;

    if errors.is_empty() {
        println!("✅ No errors found - storage is healthy");
    } else {
        println!("❌ Found {} errors", errors.len());

        if !dry_run {
            // Attempt to rebuild indices which might fix some issues
            storage.rebuild_indices()?;
            println!("✅ Rebuilt indices");

            // Verify again
            let remaining_errors = storage.verify()?;
            if remaining_errors.len() < errors.len() {
                println!("✅ Fixed {} errors", errors.len() - remaining_errors.len());
            }
            if !remaining_errors.is_empty() {
                println!("âš ī¸  {} errors remain unfixed", remaining_errors.len());
            }
        }
    }

    Ok(())
}

async fn handle_clean(path: PathBuf, dry_run: bool) -> Result<(), Box<dyn std::error::Error>> {
    let data_path = if path.ends_with("Data") {
        path.clone()
    } else {
        path.join("Data")
    };

    println!("🧹 Cleaning CASC storage at {data_path:?}");
    if dry_run {
        println!("🔍 Dry run mode - no files will be deleted");
    }

    let config = CascConfig {
        data_path: data_path.clone(),
        read_only: dry_run,
        ..Default::default()
    };

    let storage = CascStorage::new_async(config).await?;

    // Clear the cache
    storage.clear_cache();
    println!("✅ Cleared cache");

    // Note: Additional cleanup operations would require more API from casc-storage
    // such as removing orphaned files, compacting archives, etc.

    Ok(())
}

async fn handle_extract(
    ekey: String,
    path: PathBuf,
    output: Option<PathBuf>,
    listfile: Option<PathBuf>,
    resolve_filename: bool,
    format: OutputFormat,
) -> Result<(), Box<dyn std::error::Error>> {
    let data_path = if path.ends_with("Data") {
        path.clone()
    } else {
        path.join("Data")
    };

    let ekey_bytes = hex::decode(&ekey)?;
    debug!(
        "Parsed EKey bytes: {:?} (length: {})",
        ekey_bytes,
        ekey_bytes.len()
    );
    if ekey_bytes.len() != 16 && ekey_bytes.len() != 9 {
        return Err("EKey must be 16 or 9 bytes (32 or 18 hex characters)".into());
    }

    let config = CascConfig {
        data_path,
        read_only: true,
        ..Default::default()
    };

    let storage = CascStorage::new_async(config).await?;

    // Convert to EKey type
    let ekey_obj = if ekey_bytes.len() == 9 {
        // Expand truncated key
        let mut full_key = [0u8; 16];
        full_key[0..9].copy_from_slice(&ekey_bytes);
        casc_storage::types::EKey::new(full_key)
    } else {
        casc_storage::types::EKey::from_slice(&ekey_bytes).ok_or("Invalid EKey format")?
    };

    debug!("Extracting file with EKey: {}", ekey);
    let bucket = ekey_obj.bucket_index();
    debug!("EKey {} maps to bucket {:02x}", ekey, bucket);
    let data = storage.read(&ekey_obj)?;

    // Try to resolve filename if requested
    let resolved_filename: Option<String> = None;
    if resolve_filename {
        if let Some(listfile_path) = &listfile {
            if listfile_path.exists() {
                match parse_listfile(listfile_path) {
                    Ok(mapping) => {
                        // For now, we can't map EKey to FileDataID without TACT manifests
                        // This is a placeholder for future enhancement
                        info!(
                            "Listfile loaded with {} entries, but EKey->FileDataID mapping not yet implemented",
                            mapping.len()
                        );
                        warn!("Filename resolution requires TACT manifest integration");
                    }
                    Err(e) => {
                        warn!("Failed to parse listfile: {}", e);
                    }
                }
            } else {
                warn!("Listfile not found at {:?}", listfile_path);
            }
        } else {
            // Try default listfile path
            let default_listfile = PathBuf::from("community-listfile.csv");
            if default_listfile.exists() {
                match parse_listfile(&default_listfile) {
                    Ok(mapping) => {
                        info!("Loaded default listfile with {} entries", mapping.len());
                        warn!("Filename resolution requires TACT manifest integration");
                    }
                    Err(e) => {
                        warn!("Failed to parse default listfile: {}", e);
                    }
                }
            }
        }
    }

    // Determine output path
    let output_path = if let Some(path) = output {
        path
    } else if let Some(ref filename) = resolved_filename {
        PathBuf::from(filename)
    } else {
        // Use EKey as filename
        PathBuf::from(format!("{ekey}.bin"))
    };

    // Write the file
    if output_path.to_string_lossy() == "-" {
        // Output to stdout
        io::stdout().write_all(&data)?;
    } else {
        // Create parent directories if needed
        if let Some(parent) = output_path.parent() {
            fs::create_dir_all(parent)?;
        }

        fs::write(&output_path, &data)?;

        match format {
            OutputFormat::Json | OutputFormat::JsonPretty => {
                let json = serde_json::json!({
                    "status": "success",
                    "ekey": ekey,
                    "output_path": output_path,
                    "size": data.len(),
                    "filename_resolved": resolved_filename.is_some()
                });

                if matches!(format, OutputFormat::JsonPretty) {
                    println!("{}", serde_json::to_string_pretty(&json)?);
                } else {
                    println!("{}", serde_json::to_string(&json)?);
                }
            }
            OutputFormat::Text => {
                println!("✅ Extracted file successfully!");
                println!("   EKey:   {}", ekey.cyan());
                println!("   Size:   {} bytes", data.len().to_string().green());
                println!("   Output: {:?}", output_path.bright_blue());

                if resolved_filename.is_some() {
                    println!("   📝 Filename resolved from listfile");
                } else {
                    println!("   📝 Used EKey as filename (no resolution available)");
                }
            }
            OutputFormat::Bpsv => {
                println!("status = success");
                println!("ekey = {ekey}");
                println!("output_path = {output_path:?}");
                println!("size = {}", data.len());
                println!("filename_resolved = {}", resolved_filename.is_some());
            }
        }
    }

    Ok(())
}

async fn handle_extract_by_id(
    fdid: u32,
    path: PathBuf,
    output: Option<PathBuf>,
    root_manifest: Option<PathBuf>,
    encoding_manifest: Option<PathBuf>,
    format: OutputFormat,
) -> Result<(), Box<dyn std::error::Error>> {
    let data_path = if path.ends_with("Data") {
        path.clone()
    } else {
        path.join("Data")
    };

    let config = CascConfig {
        data_path: data_path.clone(),
        read_only: true,
        cache_size_mb: 256,
        max_archive_size: 1024 * 1024 * 1024,
        use_memory_mapping: true,
    };

    let mut storage = CascStorage::new(config)?;
    storage.load_indices()?;
    storage.load_archives()?;

    // Initialize TACT manifests
    let manifest_config = ManifestConfig {
        locale: LocaleFlags::any_locale(),
        content_flags: None,
        cache_manifests: true,
        lazy_loading: true,       // Enable lazy loading by default
        lazy_cache_limit: 50_000, // Higher limit for CLI usage
    };
    storage.init_tact_manifests(manifest_config);

    // Load manifests
    if let Some(root_path) = root_manifest {
        storage.load_root_manifest_from_file(&root_path)?;
        info!("Loaded root manifest from {:?}", root_path);
    }

    if let Some(encoding_path) = encoding_manifest {
        storage.load_encoding_manifest_from_file(&encoding_path)?;
        info!("Loaded encoding manifest from {:?}", encoding_path);
    }

    if !storage.tact_manifests_loaded() {
        return Err(
            "TACT manifests not loaded. Use --root-manifest and --encoding-manifest".into(),
        );
    }

    // Extract file by FileDataID
    debug!("Extracting FileDataID: {}", fdid);
    let data = storage.read_by_fdid(fdid)?;

    // Determine output path
    let output_path = output.unwrap_or_else(|| PathBuf::from(format!("fdid_{fdid}.bin")));

    // Write the file
    if output_path.to_string_lossy() == "-" {
        io::stdout().write_all(&data)?;
    } else {
        if let Some(parent) = output_path.parent() {
            fs::create_dir_all(parent)?;
        }
        fs::write(&output_path, &data)?;

        match format {
            OutputFormat::Json | OutputFormat::JsonPretty => {
                let json = serde_json::json!({
                    "status": "success",
                    "fdid": fdid,
                    "output_path": output_path,
                    "size": data.len()
                });

                if matches!(format, OutputFormat::JsonPretty) {
                    println!("{}", serde_json::to_string_pretty(&json)?);
                } else {
                    println!("{}", serde_json::to_string(&json)?);
                }
            }
            OutputFormat::Text => {
                println!("✅ Extracted file successfully!");
                println!("   FileDataID: {}", fdid.to_string().cyan());
                println!("   Size:       {} bytes", data.len().to_string().green());
                println!("   Output:     {:?}", output_path.bright_blue());
            }
            OutputFormat::Bpsv => {
                println!("status = success");
                println!("fdid = {fdid}");
                println!("output_path = {output_path:?}");
                println!("size = {}", data.len());
            }
        }
    }

    Ok(())
}

async fn handle_extract_by_name(
    filename: String,
    path: PathBuf,
    output: Option<PathBuf>,
    root_manifest: Option<PathBuf>,
    encoding_manifest: Option<PathBuf>,
    listfile: Option<PathBuf>,
    format: OutputFormat,
) -> Result<(), Box<dyn std::error::Error>> {
    let data_path = if path.ends_with("Data") {
        path.clone()
    } else {
        path.join("Data")
    };

    let config = CascConfig {
        data_path: data_path.clone(),
        read_only: true,
        cache_size_mb: 256,
        max_archive_size: 1024 * 1024 * 1024,
        use_memory_mapping: true,
    };

    let mut storage = CascStorage::new(config)?;
    storage.load_indices()?;
    storage.load_archives()?;

    // Initialize TACT manifests
    let manifest_config = ManifestConfig {
        locale: LocaleFlags::any_locale(),
        content_flags: None,
        cache_manifests: true,
        lazy_loading: true,       // Enable lazy loading by default
        lazy_cache_limit: 50_000, // Higher limit for CLI usage
    };
    storage.init_tact_manifests(manifest_config);

    // Load manifests
    if let Some(root_path) = root_manifest {
        storage.load_root_manifest_from_file(&root_path)?;
        info!("Loaded root manifest from {:?}", root_path);
    }

    if let Some(encoding_path) = encoding_manifest {
        storage.load_encoding_manifest_from_file(&encoding_path)?;
        info!("Loaded encoding manifest from {:?}", encoding_path);
    }

    // Load listfile if provided
    if let Some(listfile_path) = listfile {
        let count = storage.load_listfile(&listfile_path)?;
        info!("Loaded {} filename mappings", count);
    }

    if !storage.tact_manifests_loaded() {
        return Err(
            "TACT manifests not loaded. Use --root-manifest and --encoding-manifest".into(),
        );
    }

    // Extract file by filename
    debug!("Extracting filename: {}", filename);
    let data = storage.read_by_filename(&filename)?;

    // Determine output path
    let output_path = output.unwrap_or_else(|| {
        // Use original filename or sanitize it
        let safe_filename = filename.replace(['\\', '/', ':'], "_");
        PathBuf::from(safe_filename)
    });

    // Write the file
    if output_path.to_string_lossy() == "-" {
        io::stdout().write_all(&data)?;
    } else {
        if let Some(parent) = output_path.parent() {
            fs::create_dir_all(parent)?;
        }
        fs::write(&output_path, &data)?;

        match format {
            OutputFormat::Json | OutputFormat::JsonPretty => {
                let json = serde_json::json!({
                    "status": "success",
                    "filename": filename,
                    "output_path": output_path,
                    "size": data.len()
                });

                if matches!(format, OutputFormat::JsonPretty) {
                    println!("{}", serde_json::to_string_pretty(&json)?);
                } else {
                    println!("{}", serde_json::to_string(&json)?);
                }
            }
            OutputFormat::Text => {
                println!("✅ Extracted file successfully!");
                println!("   Filename: {}", filename.cyan());
                println!("   Size:     {} bytes", data.len().to_string().green());
                println!("   Output:   {:?}", output_path.bright_blue());
            }
            OutputFormat::Bpsv => {
                println!("status = success");
                println!("filename = {filename}");
                println!("output_path = {output_path:?}");
                println!("size = {}", data.len());
            }
        }
    }

    Ok(())
}

async fn handle_load_manifests(
    path: PathBuf,
    root_manifest: Option<PathBuf>,
    encoding_manifest: Option<PathBuf>,
    listfile: Option<PathBuf>,
    locale: String,
    info_only: bool,
    format: OutputFormat,
) -> Result<(), Box<dyn std::error::Error>> {
    let data_path = if path.ends_with("Data") {
        path.clone()
    } else {
        path.join("Data")
    };

    // Parse locale
    let locale_flags = match locale.to_lowercase().as_str() {
        "all" => LocaleFlags::any_locale(),
        "en_us" => LocaleFlags::new().with_en_us(true),
        "de_de" => LocaleFlags::new().with_de_de(true),
        "fr_fr" => LocaleFlags::new().with_fr_fr(true),
        "es_es" => LocaleFlags::new().with_es_es(true),
        "zh_cn" => LocaleFlags::new().with_zh_cn(true),
        "zh_tw" => LocaleFlags::new().with_zh_tw(true),
        "ko_kr" => LocaleFlags::new().with_ko_kr(true),
        "ru_ru" => LocaleFlags::new().with_ru_ru(true),
        _ => {
            warn!("Unknown locale '{}', using 'all'", locale);
            LocaleFlags::any_locale()
        }
    };

    let config = CascConfig {
        data_path: data_path.clone(),
        read_only: true,
        cache_size_mb: 256,
        max_archive_size: 1024 * 1024 * 1024,
        use_memory_mapping: true,
    };

    let mut storage = CascStorage::new(config)?;
    storage.load_indices()?;
    storage.load_archives()?;

    // Initialize TACT manifests
    let manifest_config = ManifestConfig {
        locale: locale_flags,
        content_flags: None,
        cache_manifests: true,
        lazy_loading: true,       // Enable lazy loading by default
        lazy_cache_limit: 50_000, // Higher limit for CLI usage
    };
    storage.init_tact_manifests(manifest_config);

    let mut stats = serde_json::json!({
        "manifests_loaded": {},
        "errors": []
    });

    // Load root manifest
    if let Some(root_path) = root_manifest {
        match storage.load_root_manifest_from_file(&root_path) {
            Ok(_) => {
                info!("Successfully loaded root manifest from {:?}", root_path);
                stats["manifests_loaded"]["root"] = serde_json::json!({
                    "path": root_path,
                    "status": "success"
                });
            }
            Err(e) => {
                error!("Failed to load root manifest: {}", e);
                stats["errors"]
                    .as_array_mut()
                    .unwrap()
                    .push(serde_json::json!({
                        "manifest": "root",
                        "path": root_path,
                        "error": e.to_string()
                    }));
            }
        }
    }

    // Load encoding manifest
    if let Some(encoding_path) = encoding_manifest {
        match storage.load_encoding_manifest_from_file(&encoding_path) {
            Ok(_) => {
                info!(
                    "Successfully loaded encoding manifest from {:?}",
                    encoding_path
                );
                stats["manifests_loaded"]["encoding"] = serde_json::json!({
                    "path": encoding_path,
                    "status": "success"
                });
            }
            Err(e) => {
                error!("Failed to load encoding manifest: {}", e);
                stats["errors"]
                    .as_array_mut()
                    .unwrap()
                    .push(serde_json::json!({
                        "manifest": "encoding",
                        "path": encoding_path,
                        "error": e.to_string()
                    }));
            }
        }
    }

    // Load listfile
    if let Some(listfile_path) = listfile {
        match storage.load_listfile(&listfile_path) {
            Ok(count) => {
                info!(
                    "Successfully loaded {} filename mappings from listfile",
                    count
                );
                stats["manifests_loaded"]["listfile"] = serde_json::json!({
                    "path": listfile_path,
                    "status": "success",
                    "entries": count
                });
            }
            Err(e) => {
                error!("Failed to load listfile: {}", e);
                stats["errors"]
                    .as_array_mut()
                    .unwrap()
                    .push(serde_json::json!({
                        "manifest": "listfile",
                        "path": listfile_path,
                        "error": e.to_string()
                    }));
            }
        }
    }

    // Get additional stats if manifests loaded
    if storage.tact_manifests_loaded() {
        if let Ok(fdids) = storage.get_all_fdids() {
            stats["file_count"] = fdids.len().into();
        }
    }

    match format {
        OutputFormat::Json | OutputFormat::JsonPretty => {
            if matches!(format, OutputFormat::JsonPretty) {
                println!("{}", serde_json::to_string_pretty(&stats)?);
            } else {
                println!("{}", serde_json::to_string(&stats)?);
            }
        }
        OutputFormat::Text => {
            println!("📋 TACT Manifest Loading Results");
            println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");

            if storage.tact_manifests_loaded() {
                println!("✅ TACT manifests loaded successfully");

                if let Ok(fdids) = storage.get_all_fdids() {
                    println!(
                        "   FileDataIDs available: {}",
                        fdids.len().to_string().green()
                    );
                }

                println!("   Locale filter: {}", locale.yellow());

                if info_only {
                    println!("   â„šī¸  Info-only mode (not persisted)");
                }
            } else {
                println!("❌ TACT manifests not fully loaded");
            }

            if !stats["errors"].as_array().unwrap().is_empty() {
                println!("\nâš ī¸  Errors:");
                for error in stats["errors"].as_array().unwrap() {
                    println!(
                        "   â€ĸ {}: {}",
                        error["manifest"].as_str().unwrap(),
                        error["error"].as_str().unwrap()
                    );
                }
            }
        }
        OutputFormat::Bpsv => {
            println!("## TACT Manifests");
            println!("loaded = {}", storage.tact_manifests_loaded());
            if let Ok(fdids) = storage.get_all_fdids() {
                println!("file_count = {}", fdids.len());
            }
            println!("locale = {locale}");
            println!("errors = {}", stats["errors"].as_array().unwrap().len());
        }
    }

    Ok(())
}

fn format_bytes(bytes: u64) -> String {
    const UNITS: &[&str] = &["B", "KB", "MB", "GB", "TB"];
    let mut size = bytes as f64;
    let mut unit = 0;

    while size >= 1024.0 && unit < UNITS.len() - 1 {
        size /= 1024.0;
        unit += 1;
    }

    if unit == 0 {
        format!("{} {}", bytes, UNITS[unit])
    } else {
        format!("{:.2} {}", size, UNITS[unit])
    }
}