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
use crate::{
    OutputFormat, ProductsCommands,
    cached_client::create_client,
    output::{
        OutputStyle, create_list_table, create_table, format_count_badge, format_hash,
        format_header, format_key_value, format_success, format_url, format_warning, hash_cell,
        header_cell, numeric_cell, print_section_header, print_subsection_header, regular_cell,
    },
    wago_api,
};
use chrono::{Duration, Utc};
use ngdp_cache::cached_cdn_client::CachedCdnClient;
use ribbit_client::{
    CdnEntry, Endpoint, ProductCdnsResponse, ProductVersionsResponse, Region, SummaryResponse,
};
use std::str::FromStr;
use tact_parser::config::BuildConfig;

pub async fn handle(
    cmd: ProductsCommands,
    format: OutputFormat,
) -> Result<(), Box<dyn std::error::Error>> {
    match cmd {
        ProductsCommands::List { filter, region } => list_products(filter, region, format).await,
        ProductsCommands::Versions {
            product,
            region,
            all_regions,
            parse_config,
        } => show_versions(product, region, all_regions, parse_config, format).await,
        ProductsCommands::Cdns { product, region } => show_cdns(product, region, format).await,
        ProductsCommands::Info { product, region } => show_info(product, region, format).await,
        ProductsCommands::Builds {
            product,
            filter,
            days,
            limit,
            bgdl_only,
        } => show_builds(product, filter, days, limit, bgdl_only, format).await,
    }
}

async fn list_products(
    filter: Option<String>,
    region: String,
    format: OutputFormat,
) -> Result<(), Box<dyn std::error::Error>> {
    let region = Region::from_str(&region)?;
    let client = create_client(region).await?;

    let response = client.request(&Endpoint::Summary).await?;
    let summary: SummaryResponse = client.request_typed(&Endpoint::Summary).await?;

    let mut products = summary.products.clone();

    // Apply filter if provided
    if let Some(filter) = &filter {
        products.retain(|p| p.product.contains(filter));
    }

    // Sort by product name first, then by sequence number
    products.sort_by(|a, b| a.product.cmp(&b.product).then_with(|| a.seqn.cmp(&b.seqn)));

    match format {
        OutputFormat::Json | OutputFormat::JsonPretty => {
            let json_data: Vec<_> = products
                .iter()
                .map(|entry| {
                    let mut obj = serde_json::json!({
                        "code": entry.product,
                        "seqn": entry.seqn,
                    });
                    if let Some(flags) = &entry.flags {
                        obj["flags"] = serde_json::json!(flags);
                    }
                    obj
                })
                .collect();

            let output = if matches!(format, OutputFormat::JsonPretty) {
                serde_json::to_string_pretty(&json_data)?
            } else {
                serde_json::to_string(&json_data)?
            };
            println!("{output}");
        }
        OutputFormat::Bpsv => {
            if let Some(data) = response.as_text() {
                println!("{data}");
            }
        }
        OutputFormat::Text => {
            let style = OutputStyle::new();

            // Print header with count
            println!(
                "{} {}",
                format_header("Available products", &style),
                format_count_badge(products.len(), "product", &style)
            );

            // Create table
            let mut table = create_table(&style);
            table.set_header(vec![
                header_cell("Product", &style),
                header_cell("Sequence", &style),
                header_cell("Flags", &style),
            ]);

            // Add rows
            for entry in &products {
                table.add_row(vec![
                    regular_cell(&entry.product),
                    numeric_cell(&entry.seqn.to_string()),
                    regular_cell(entry.flags.as_deref().unwrap_or("")),
                ]);
            }

            println!("{table}");

            // Add a note about flags if any products have flags
            if products.iter().any(|p| p.flags.is_some()) {
                println!();
                println!("{}", format_header("Flag meanings:", &style));
                println!(
                    "  {} - Product has CDN configuration",
                    format_success("cdn", &style)
                );
                println!(
                    "  {} - Product has background download configuration",
                    format_success("bgdl", &style)
                );
            }
        }
    }

    Ok(())
}

async fn show_versions(
    product: String,
    region: String,
    all_regions: bool,
    parse_config: bool,
    format: OutputFormat,
) -> Result<(), Box<dyn std::error::Error>> {
    let region = Region::from_str(&region)?;
    let client = create_client(region).await?;

    let endpoint = Endpoint::ProductVersions(product.clone());
    let response = client.request(&endpoint).await?;
    let versions: ProductVersionsResponse = client.request_typed(&endpoint).await?;

    // If parse_config is true, fetch build configs
    let build_configs = if parse_config {
        let cdns_endpoint = Endpoint::ProductCdns(product.clone());
        let cdns: ProductCdnsResponse = client.request_typed(&cdns_endpoint).await?;

        // Get CDN configuration for the region
        if let Some(cdn_entry) = cdns.entries.iter().find(|e| e.name == region.as_str()) {
            let cdn_client = CachedCdnClient::new().await?;
            // Add CDN hosts
            cdn_client.add_primary_hosts(cdn_entry.hosts.iter().cloned());
            cdn_client.add_fallback_host("cdn.arctium.tools");
            cdn_client.add_fallback_host("tact.mirror.reliquaryhq.com");
            let cdn_host = &cdn_entry.hosts[0]; // Use first CDN host
            let cdn_path = &cdn_entry.path;

            let mut configs = std::collections::HashMap::new();

            // Download build configs for the requested regions
            let entries_to_process: Vec<_> = if all_regions {
                versions.entries.iter().collect()
            } else {
                versions
                    .entries
                    .iter()
                    .filter(|e| e.region == region.as_str())
                    .collect()
            };

            for entry in entries_to_process {
                match cdn_client
                    .download_build_config(cdn_host, cdn_path, &entry.build_config)
                    .await
                {
                    Ok(response) => match response.text().await {
                        Ok(config_text) => match BuildConfig::parse(&config_text) {
                            Ok(config) => {
                                configs.insert(entry.build_config.clone(), config);
                            }
                            Err(e) => {
                                eprintln!(
                                    "Warning: Failed to parse config {}: {}",
                                    entry.build_config, e
                                );
                            }
                        },
                        Err(e) => {
                            eprintln!(
                                "Warning: Failed to read config {}: {}",
                                entry.build_config, e
                            );
                        }
                    },
                    Err(e) => {
                        eprintln!(
                            "Warning: Failed to download config {}: {}",
                            entry.build_config, e
                        );
                    }
                }
            }

            Some(configs)
        } else {
            eprintln!(
                "Warning: No CDN configuration found for region {}",
                region.as_str()
            );
            None
        }
    } else {
        None
    };

    match format {
        OutputFormat::Json | OutputFormat::JsonPretty => {
            let json_data = if all_regions {
                let entries: Vec<_> = versions
                    .entries
                    .iter()
                    .map(|e| {
                        serde_json::json!({
                            "region": e.region,
                            "versions_name": e.versions_name,
                            "build_id": e.build_id,
                            "build_config": e.build_config,
                            "cdn_config": e.cdn_config,
                            "product_config": e.product_config,
                        })
                    })
                    .collect();
                serde_json::json!({
                    "sequence_number": versions.sequence_number,
                    "entries": entries
                })
            } else {
                // Filter to just the requested region
                let filtered: Vec<_> = versions
                    .entries
                    .iter()
                    .filter(|e| e.region == region.as_str())
                    .map(|e| {
                        serde_json::json!({
                            "region": e.region,
                            "versions_name": e.versions_name,
                            "build_id": e.build_id,
                            "build_config": e.build_config,
                            "cdn_config": e.cdn_config,
                            "product_config": e.product_config,
                        })
                    })
                    .collect();
                serde_json::Value::Array(filtered)
            };

            let output = if matches!(format, OutputFormat::JsonPretty) {
                serde_json::to_string_pretty(&json_data)?
            } else {
                serde_json::to_string(&json_data)?
            };
            println!("{output}");
        }
        OutputFormat::Bpsv => {
            if let Some(data) = response.as_text() {
                println!("{data}");
            }
        }
        OutputFormat::Text => {
            let style = OutputStyle::new();

            print_section_header(&format!("Product: {product}"), &style);
            if let Some(seqn) = versions.sequence_number {
                println!(
                    "{}",
                    format_key_value("Sequence", &seqn.to_string(), &style)
                );
            }

            if all_regions {
                println!();

                // Create table for all regions with multi-row format
                let mut table = create_table(&style);
                table.set_header(vec![
                    header_cell("Region", &style),
                    header_cell("Version", &style),
                    header_cell("Build", &style),
                    header_cell("Configuration Hash", &style),
                ]);

                for entry in &versions.entries {
                    // First row with build config
                    table.add_row(vec![
                        regular_cell(&entry.region),
                        regular_cell(&entry.versions_name),
                        numeric_cell(&entry.build_id.to_string()),
                        hash_cell(&format!("Build Config:   {}", &entry.build_config), &style),
                    ]);

                    // Second row with CDN config
                    table.add_row(vec![
                        regular_cell(""),
                        regular_cell(""),
                        regular_cell(""),
                        hash_cell(&format!("CDN Config:     {}", &entry.cdn_config), &style),
                    ]);

                    // Third row with Product config
                    table.add_row(vec![
                        regular_cell(""),
                        regular_cell(""),
                        regular_cell(""),
                        hash_cell(
                            &format!("Product Config: {}", &entry.product_config),
                            &style,
                        ),
                    ]);

                    // Fourth row with Key Ring (if present)
                    if let Some(key_ring) = &entry.key_ring {
                        table.add_row(vec![
                            regular_cell(""),
                            regular_cell(""),
                            regular_cell(""),
                            hash_cell(&format!("Key Ring:       {key_ring}"), &style),
                        ]);
                    }
                }

                println!("{table}");
            } else if let Some(entry) = versions.get_region(region.as_str()) {
                println!();

                // Create a detailed table for single region
                let mut table = create_table(&style);
                table.set_header(vec![
                    header_cell("Property", &style),
                    header_cell("Value", &style),
                ]);

                table.add_row(vec![regular_cell("Region"), regular_cell(&entry.region)]);

                table.add_row(vec![
                    regular_cell("Version"),
                    regular_cell(&entry.versions_name),
                ]);

                table.add_row(vec![
                    regular_cell("Build ID"),
                    regular_cell(&entry.build_id.to_string()),
                ]);

                table.add_row(vec![
                    regular_cell("Build Config"),
                    hash_cell(&entry.build_config, &style),
                ]);

                table.add_row(vec![
                    regular_cell("CDN Config"),
                    hash_cell(&entry.cdn_config, &style),
                ]);

                table.add_row(vec![
                    regular_cell("Product Config"),
                    hash_cell(&entry.product_config, &style),
                ]);

                if let Some(key_ring) = &entry.key_ring {
                    table.add_row(vec![regular_cell("Key Ring"), hash_cell(key_ring, &style)]);
                }

                println!("{table}");

                // Show parsed build config information if available
                if let Some(ref configs) = build_configs {
                    if let Some(build_config) = configs.get(&entry.build_config) {
                        println!();
                        print_subsection_header("Parsed Build Configuration", &style);

                        // Show key build details in a compact format
                        if let Some(build_name) = build_config.build_name() {
                            println!("{}", format_key_value("Build Name", build_name, &style));
                        }

                        if let Some(root_hash) = build_config.root_hash() {
                            let size_info = if let Some(size) = build_config.config.get_size("root")
                            {
                                format!(" ({:.1} MB)", size as f64 / (1024.0 * 1024.0))
                            } else {
                                String::new()
                            };
                            println!(
                                "{}",
                                format_key_value(
                                    "Root File",
                                    &format!("{root_hash}{size_info}"),
                                    &style
                                )
                            );
                        }

                        if let Some(encoding_hash) = build_config.encoding_hash() {
                            let size_info =
                                if let Some(size) = build_config.config.get_size("encoding") {
                                    format!(" ({:.1} MB)", size as f64 / (1024.0 * 1024.0))
                                } else {
                                    String::new()
                                };
                            println!(
                                "{}",
                                format_key_value(
                                    "Encoding File",
                                    &format!("{encoding_hash}{size_info}"),
                                    &style
                                )
                            );
                        }

                        if let Some(install_hash) = build_config.install_hash() {
                            let size_info =
                                if let Some(size) = build_config.config.get_size("install") {
                                    format!(" ({:.1} KB)", size as f64 / 1024.0)
                                } else {
                                    String::new()
                                };
                            println!(
                                "{}",
                                format_key_value(
                                    "Install Manifest",
                                    &format!("{install_hash}{size_info}"),
                                    &style
                                )
                            );
                        }

                        if let Some(download_hash) = build_config.download_hash() {
                            let size_info =
                                if let Some(size) = build_config.config.get_size("download") {
                                    format!(" ({:.1} MB)", size as f64 / (1024.0 * 1024.0))
                                } else {
                                    String::new()
                                };
                            println!(
                                "{}",
                                format_key_value(
                                    "Download Manifest",
                                    &format!("{download_hash}{size_info}"),
                                    &style
                                )
                            );
                        }

                        // Show patch information
                        let has_patch = build_config
                            .config
                            .get_value("patch")
                            .is_some_and(|v| !v.is_empty());
                        if has_patch {
                            if let Some(patch_hash) = build_config.config.get_value("patch") {
                                let size_info =
                                    if let Some(size) = build_config.config.get_size("patch") {
                                        format!(" ({:.1} KB)", size as f64 / 1024.0)
                                    } else {
                                        String::new()
                                    };
                                println!(
                                    "{}",
                                    format_key_value(
                                        "Patch",
                                        &format!("{patch_hash}{size_info}"),
                                        &style
                                    )
                                );
                            }
                        } else {
                            println!("{}", format_key_value("Patch", "Not available", &style));
                        }

                        // Count VFS entries
                        let vfs_count = build_config
                            .config
                            .keys()
                            .into_iter()
                            .filter(|k| k.starts_with("vfs-") && !k.ends_with("-size"))
                            .count();
                        if vfs_count > 0 {
                            println!(
                                "{}",
                                format_key_value(
                                    "VFS Entries",
                                    &format!("{vfs_count} files"),
                                    &style
                                )
                            );
                        }
                    }
                }
            } else {
                println!();
                println!(
                    "{}",
                    format_warning(
                        &format!(
                            "No version information available for region '{}'",
                            region.as_str()
                        ),
                        &style
                    )
                );
            }
        }
    }

    Ok(())
}

async fn show_cdns(
    product: String,
    region: String,
    format: OutputFormat,
) -> Result<(), Box<dyn std::error::Error>> {
    let region_enum = Region::from_str(&region)?;
    let client = create_client(region_enum).await?;

    let endpoint = Endpoint::ProductCdns(product.clone());
    let response = client.request(&endpoint).await?;
    let cdns: ProductCdnsResponse = client.request_typed(&endpoint).await?;

    // Filter CDN entries for the specified region
    let filtered_entries: Vec<&CdnEntry> =
        cdns.entries.iter().filter(|e| e.name == region).collect();

    match format {
        OutputFormat::Json | OutputFormat::JsonPretty => {
            let json_data = filtered_entries
                .iter()
                .map(|e| {
                    serde_json::json!({
                        "name": e.name,
                        "path": e.path,
                        "config_path": e.config_path,
                        "hosts": e.hosts,
                        "servers": e.servers,
                    })
                })
                .collect::<Vec<_>>();

            let output = if matches!(format, OutputFormat::JsonPretty) {
                serde_json::to_string_pretty(&json_data)?
            } else {
                serde_json::to_string(&json_data)?
            };
            println!("{output}");
        }
        OutputFormat::Bpsv => {
            if let Some(data) = response.as_text() {
                println!("{data}");
            }
        }
        OutputFormat::Text => {
            let style = OutputStyle::new();

            print_section_header(
                &format!("CDN Configuration for {product} ({region})"),
                &style,
            );
            if let Some(seqn) = cdns.sequence_number {
                println!(
                    "{}",
                    format_key_value("Sequence", &seqn.to_string(), &style)
                );
            }

            println!();

            if filtered_entries.is_empty() {
                println!(
                    "{}",
                    format_warning(
                        &format!("No CDN configuration found for region '{region}'"),
                        &style
                    )
                );
            } else {
                // Show the CDN config for the specified region
                for entry in &filtered_entries {
                    let mut table = create_table(&style);
                    table.set_header(vec![
                        header_cell("Property", &style),
                        header_cell("Value", &style),
                    ]);

                    table.add_row(vec![regular_cell("Path"), regular_cell(&entry.path)]);

                    table.add_row(vec![
                        regular_cell("Config Path"),
                        regular_cell(&entry.config_path),
                    ]);

                    // Add hosts to the table (before servers)
                    if !entry.hosts.is_empty() {
                        // First host
                        table.add_row(vec![
                            regular_cell("CDN Hosts"),
                            regular_cell(&entry.hosts[0]),
                        ]);

                        // Additional hosts on separate lines
                        for host in &entry.hosts[1..] {
                            table.add_row(vec![regular_cell(""), regular_cell(host)]);
                        }
                    }

                    if !entry.servers.is_empty() {
                        // First server
                        table.add_row(vec![
                            regular_cell("Servers"),
                            regular_cell(&entry.servers[0]),
                        ]);

                        // Additional servers on separate lines
                        for server in &entry.servers[1..] {
                            table.add_row(vec![regular_cell(""), regular_cell(server)]);
                        }
                    }

                    println!("{table}");
                }
            }
        }
    }

    Ok(())
}

async fn show_info(
    product: String,
    region: Option<String>,
    format: OutputFormat,
) -> Result<(), Box<dyn std::error::Error>> {
    // Use US as default for fetching data, but we'll show all regions if none specified
    let fetch_region = region.as_deref().unwrap_or("us");
    let fetch_region_enum = Region::from_str(fetch_region)?;
    let client = create_client(fetch_region_enum).await?;

    // Get both versions and CDNs
    let versions_endpoint = Endpoint::ProductVersions(product.clone());
    let cdns_endpoint = Endpoint::ProductCdns(product.clone());

    // Fetch all data concurrently
    let versions_response = client
        .request(&versions_endpoint)
        .await
        .map_err(|e| Box::new(e) as Box<dyn std::error::Error>)?;
    let versions = client
        .request_typed::<ProductVersionsResponse>(&versions_endpoint)
        .await
        .map_err(|e| Box::new(e) as Box<dyn std::error::Error>)?;

    let cdns_response = client
        .request(&cdns_endpoint)
        .await
        .map_err(|e| Box::new(e) as Box<dyn std::error::Error>)?;
    let cdns = client
        .request_typed::<ProductCdnsResponse>(&cdns_endpoint)
        .await
        .map_err(|e| Box::new(e) as Box<dyn std::error::Error>)?;

    let summary = client
        .request_typed::<SummaryResponse>(&Endpoint::Summary)
        .await
        .map_err(|e| Box::new(e) as Box<dyn std::error::Error>)?;

    match format {
        OutputFormat::Json | OutputFormat::JsonPretty => {
            // Filter data based on region parameter
            let versions_data: Vec<_> = versions
                .entries
                .iter()
                .filter(|e| region.is_none() || region.as_deref() == Some(&e.region))
                .map(|e| {
                    serde_json::json!({
                        "region": e.region,
                        "versions_name": e.versions_name,
                        "build_id": e.build_id,
                    })
                })
                .collect();

            let cdns_data: Vec<_> = cdns
                .entries
                .iter()
                .filter(|e| region.is_none() || region.as_deref() == Some(&e.name))
                .map(|e| {
                    serde_json::json!({
                        "name": e.name,
                        "hosts": e.hosts,
                        "servers": e.servers,
                        "path": e.path,
                        "config_path": e.config_path,
                    })
                })
                .collect();

            let info = serde_json::json!({
                "product": product,
                "summary": summary.get_product(&product).map(|s| serde_json::json!({
                    "product": s.product,
                    "seqn": s.seqn,
                    "flags": s.flags,
                })),
                "versions": versions_data,
                "cdns": cdns_data,
            });

            let output = if matches!(format, OutputFormat::JsonPretty) {
                serde_json::to_string_pretty(&info)?
            } else {
                serde_json::to_string(&info)?
            };
            println!("{output}");
        }
        OutputFormat::Bpsv => {
            println!("# Versions");
            if let Some(data) = versions_response.as_text() {
                println!("{data}");
            }
            println!("\n# CDNs");
            if let Some(data) = cdns_response.as_text() {
                println!("{data}");
            }
        }
        OutputFormat::Text => {
            let style = OutputStyle::new();

            let header = if let Some(ref r) = region {
                format!("Product Information: {product} ({r})")
            } else {
                format!("Product Information: {product}")
            };
            print_section_header(&header, &style);

            if let Some(summary_entry) = summary.get_product(&product) {
                print_subsection_header("Summary", &style);
                println!(
                    "{}",
                    format_key_value("Sequence", &summary_entry.seqn.to_string(), &style)
                );
                if let Some(flags) = &summary_entry.flags {
                    println!("{}", format_key_value("Flags", flags, &style));
                }
            }

            // Filter versions based on region parameter
            let filtered_versions: Vec<_> = versions
                .entries
                .iter()
                .filter(|e| region.is_none() || region.as_deref() == Some(&e.region))
                .collect();

            if region.is_some() {
                // Show detailed info for specific region
                if let Some(version) = filtered_versions.first() {
                    print_subsection_header(&format!("Version ({})", version.region), &style);
                    println!(
                        "{}",
                        format_key_value("Version", &version.versions_name, &style)
                    );
                    println!(
                        "{}",
                        format_key_value("Build ID", &version.build_id.to_string(), &style)
                    );
                    println!(
                        "{}",
                        format_key_value(
                            "Build Config",
                            &format_hash(&version.build_config, &style),
                            &style
                        )
                    );
                    println!(
                        "{}",
                        format_key_value(
                            "CDN Config",
                            &format_hash(&version.cdn_config, &style),
                            &style
                        )
                    );
                    println!(
                        "{}",
                        format_key_value(
                            "Product Config",
                            &format_hash(&version.product_config, &style),
                            &style
                        )
                    );
                    if let Some(key_ring) = &version.key_ring {
                        println!(
                            "{}",
                            format_key_value("Key Ring", &format_hash(key_ring, &style), &style)
                        );
                    }
                }
            } else {
                // Show all regions in a table
                print_subsection_header("Available Regions", &style);
                let mut table = create_list_table(&style);
                table.set_header(vec![
                    header_cell("Region", &style),
                    header_cell("Version", &style),
                    header_cell("Build ID", &style),
                ]);

                for version in &filtered_versions {
                    table.add_row(vec![
                        regular_cell(&version.region),
                        regular_cell(&version.versions_name),
                        numeric_cell(&version.build_id.to_string()),
                    ]);
                }
                println!("{table}");
            }

            // CDN hosts - filter based on region
            let filtered_cdns: Vec<_> = cdns
                .entries
                .iter()
                .filter(|e| region.is_none() || region.as_deref() == Some(&e.name))
                .collect();

            if !filtered_cdns.is_empty() {
                // Collect unique hosts
                let hosts: Vec<String> = filtered_cdns
                    .iter()
                    .flat_map(|e| e.hosts.iter())
                    .cloned()
                    .collect::<std::collections::HashSet<_>>()
                    .into_iter()
                    .collect();

                // Display CDN hosts
                if !hosts.is_empty() {
                    let cdn_header = if region.is_some() {
                        format!(
                            "CDN Hosts for {} {}",
                            region.as_deref().unwrap(),
                            format_count_badge(hosts.len(), "host", &style)
                        )
                    } else {
                        format!(
                            "CDN Hosts {}",
                            format_count_badge(hosts.len(), "host", &style)
                        )
                    };
                    print_subsection_header(&cdn_header, &style);

                    for host in hosts {
                        println!(
                            "  {} {}",
                            format_success("•", &style),
                            format_url(&host, &style)
                        );
                    }
                }

                // Collect unique servers
                let servers: Vec<String> = filtered_cdns
                    .iter()
                    .flat_map(|e| e.servers.iter())
                    .cloned()
                    .collect::<std::collections::HashSet<_>>()
                    .into_iter()
                    .collect();

                // Display CDN servers
                if !servers.is_empty() {
                    let servers_header = if region.is_some() {
                        format!(
                            "CDN Servers for {} {}",
                            region.as_deref().unwrap(),
                            format_count_badge(servers.len(), "server", &style)
                        )
                    } else {
                        format!(
                            "CDN Servers {}",
                            format_count_badge(servers.len(), "server", &style)
                        )
                    };
                    print_subsection_header(&servers_header, &style);

                    for server in servers {
                        println!(
                            "  {} {}",
                            format_success("•", &style),
                            format_url(&server, &style)
                        );
                    }
                }
            }
        }
    }

    Ok(())
}

async fn show_builds(
    product: String,
    filter: Option<String>,
    days: Option<u32>,
    limit: Option<usize>,
    bgdl_only: bool,
    format: OutputFormat,
) -> Result<(), Box<dyn std::error::Error>> {
    let style = OutputStyle::new();

    // Show progress indicator for text format
    if matches!(format, OutputFormat::Text) {
        eprintln!("Fetching build history from Wago Tools API...");
    }

    // Fetch builds from Wago API
    let builds_response = wago_api::fetch_builds().await?;
    let mut builds = wago_api::filter_builds_by_product(builds_response, &product);

    if builds.is_empty() {
        match format {
            OutputFormat::Json | OutputFormat::JsonPretty => {
                println!("[]");
            }
            OutputFormat::Bpsv => {
                // Still output the header for consistency
                println!("## seqn = 1");
                println!(
                    "product!STRING:0|version!STRING:0|created_at!STRING:0|build_config!HEX:16|is_bgdl!BOOL:0"
                );
            }
            OutputFormat::Text => {
                println!(
                    "{}",
                    format_warning(&format!("No builds found for product '{product}'"), &style)
                );
            }
        }
        return Ok(());
    }

    // Sort builds by created_at date (newest first)
    builds.sort_by(|a, b| b.created_at.cmp(&a.created_at));

    // Apply filters
    if let Some(filter_pattern) = &filter {
        builds.retain(|b| b.version.contains(filter_pattern));
    }

    if bgdl_only {
        builds.retain(|b| b.is_bgdl);
    }

    if let Some(days) = days {
        let cutoff = Utc::now() - Duration::days(days as i64);
        builds.retain(|b| {
            wago_api::parse_wago_date(&b.created_at)
                .map(|dt| dt > cutoff)
                .unwrap_or(false)
        });
    }

    // Apply limit
    if let Some(limit) = limit {
        builds.truncate(limit);
    }

    // Format output
    match format {
        OutputFormat::Json | OutputFormat::JsonPretty => {
            let output = if matches!(format, OutputFormat::JsonPretty) {
                serde_json::to_string_pretty(&builds)?
            } else {
                serde_json::to_string(&builds)?
            };
            println!("{output}");
        }
        OutputFormat::Bpsv => {
            // Convert to BPSV format
            println!("## seqn = 1");
            println!(
                "product!STRING:0|version!STRING:0|created_at!STRING:0|build_config!HEX:16|is_bgdl!BOOL:0"
            );
            for build in &builds {
                println!(
                    "{}|{}|{}|{}|{}",
                    build.product,
                    build.version,
                    build.created_at,
                    build.build_config,
                    if build.is_bgdl { "1" } else { "0" }
                );
            }
        }
        OutputFormat::Text => {
            // Print header with count
            println!(
                "{} {}",
                format_header(&format!("Build history for {product}"), &style),
                format_count_badge(builds.len(), "build", &style)
            );

            if let Some(filter_pattern) = &filter {
                println!("{}", format_key_value("Filter", filter_pattern, &style));
            }

            if bgdl_only {
                println!(
                    "{}",
                    format_key_value("Type", "Background downloads only", &style)
                );
            }

            if let Some(days) = days {
                println!(
                    "{}",
                    format_key_value("Period", &format!("Last {days} days"), &style)
                );
            }

            println!();

            // Create table
            let mut table = create_table(&style);
            table.set_header(vec![
                header_cell("Version", &style),
                header_cell("Created", &style),
                header_cell("Build Config", &style),
                header_cell("Type", &style),
            ]);

            // Add rows
            for build in &builds {
                // Format the date for display
                let date_display = if let Some(dt) = wago_api::parse_wago_date(&build.created_at) {
                    let days_ago = (Utc::now() - dt).num_days();
                    if days_ago == 0 {
                        format!("{} (today)", dt.format("%Y-%m-%d %H:%M"))
                    } else if days_ago == 1 {
                        format!("{} (yesterday)", dt.format("%Y-%m-%d %H:%M"))
                    } else if days_ago < 7 {
                        format!("{} ({} days ago)", dt.format("%Y-%m-%d %H:%M"), days_ago)
                    } else {
                        dt.format("%Y-%m-%d %H:%M").to_string()
                    }
                } else {
                    build.created_at.clone()
                };

                table.add_row(vec![
                    regular_cell(&build.version),
                    regular_cell(&date_display),
                    hash_cell(&format!("Build Config:   {}", build.build_config), &style),
                    regular_cell(if build.is_bgdl { "BGDL" } else { "Full" }),
                ]);

                // Add additional config rows if present
                if build.cdn_config.is_some() || build.product_config.is_some() {
                    if let Some(cdn_config) = &build.cdn_config {
                        table.add_row(vec![
                            regular_cell(""),
                            regular_cell(""),
                            hash_cell(&format!("CDN Config:     {cdn_config}"), &style),
                            regular_cell(""),
                        ]);
                    }

                    if let Some(product_config) = &build.product_config {
                        table.add_row(vec![
                            regular_cell(""),
                            regular_cell(""),
                            hash_cell(&format!("Product Config: {product_config}"), &style),
                            regular_cell(""),
                        ]);
                    }
                }
            }

            println!("{table}");

            // Add note about data source
            println!();
            println!(
                "{}",
                format_key_value("Source", "Wago Tools API (https://wago.tools)", &style)
            );
        }
    }

    Ok(())
}