msvc-kit 0.2.10

A portable MSVC Build Tools installer and manager for Rust development
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
//! msvc-kit CLI - Portable MSVC Build Tools installer and manager

use std::path::PathBuf;

use clap::{CommandFactory, Parser, Subcommand};
use tracing_subscriber::{fmt, prelude::*, EnvFilter};

use msvc_kit::bundle::{generate_bundle_scripts, save_bundle_scripts, BundleLayout};
use msvc_kit::env::generate_activation_script;
use msvc_kit::version::{list_installed_msvc, list_installed_sdk, Architecture};
use msvc_kit::{
    download_msvc, download_sdk, generate_script, get_env_vars, load_config, save_config,
    setup_environment, DownloadOptions, MsvcComponent, MsvcKitConfig, ScriptContext, ShellType,
};

/// Portable MSVC Build Tools installer and manager
#[derive(Parser)]
#[command(name = "msvc-kit")]
#[command(author = "loonghao <hal.long@outlook.com>")]
#[command(version)]
#[command(about = "Download and manage MSVC compiler and Windows SDK", long_about = None)]
struct Cli {
    /// Enable verbose output
    #[arg(short, long, global = true)]
    verbose: bool,

    /// Configuration file path
    #[arg(short, long, global = true)]
    config: Option<PathBuf>,

    #[command(subcommand)]
    command: Option<Commands>,
}

#[derive(Subcommand)]
enum Commands {
    /// Download MSVC and/or Windows SDK components
    Download {
        /// MSVC version to download (default: latest)
        #[arg(long)]
        msvc_version: Option<String>,

        /// Windows SDK version to download (default: latest)
        #[arg(long)]
        sdk_version: Option<String>,

        /// Target directory for installation
        #[arg(short, long)]
        target: Option<PathBuf>,

        /// Target architecture (x64, x86, arm64)
        #[arg(short, long, default_value = "x64")]
        arch: String,

        /// Skip MSVC download
        #[arg(long)]
        no_msvc: bool,

        /// Skip Windows SDK download
        #[arg(long)]
        no_sdk: bool,

        /// Skip hash verification
        #[arg(long)]
        no_verify: bool,

        /// Max parallel downloads
        #[arg(long)]
        parallel_downloads: Option<usize>,

        /// Include optional MSVC components (spectre, mfc, atl, asan, uwp, custom:<pattern>)
        /// Can be specified multiple times
        #[arg(long = "include-component", value_name = "COMPONENT")]
        include_components: Vec<String>,

        /// Exclude packages matching pattern (case-insensitive substring match)
        /// Can be specified multiple times
        #[arg(long = "exclude-pattern", value_name = "PATTERN")]
        exclude_patterns: Vec<String>,
    },

    /// Setup environment variables for MSVC toolchain
    Setup {
        /// Installation directory (default: from config)
        #[arg(short, long)]
        dir: Option<PathBuf>,

        /// Target architecture
        #[arg(short, long, default_value = "x64")]
        arch: String,

        /// Generate activation script instead of modifying environment
        #[arg(long)]
        script: bool,

        /// Shell type for script (cmd, powershell, bash)
        #[arg(long, default_value = "powershell")]
        shell: String,

        /// Replace install root with a portable placeholder when generating scripts (requires --script)
        #[arg(long, requires = "script", value_name = "PORTABLE_ROOT")]
        portable_root: Option<String>,

        /// Write to Windows registry (persistent)
        #[arg(long)]
        persistent: bool,
    },

    /// List installed versions
    List {
        /// Installation directory
        #[arg(short, long)]
        dir: Option<PathBuf>,

        /// Show available versions from Microsoft
        #[arg(long)]
        available: bool,
    },

    /// Remove installed versions
    Clean {
        /// Installation directory
        #[arg(short, long)]
        dir: Option<PathBuf>,

        /// MSVC version to remove
        #[arg(long)]
        msvc_version: Option<String>,

        /// SDK version to remove
        #[arg(long)]
        sdk_version: Option<String>,

        /// Remove all installed versions
        #[arg(long)]
        all: bool,

        /// Also remove downloaded cache
        #[arg(long)]
        cache: bool,
    },

    /// Show current configuration
    Config {
        /// Set installation directory
        #[arg(long)]
        set_dir: Option<PathBuf>,

        /// Set default MSVC version
        #[arg(long)]
        set_msvc: Option<String>,

        /// Set default SDK version
        #[arg(long)]
        set_sdk: Option<String>,

        /// Reset configuration to defaults
        #[arg(long)]
        reset: bool,
    },

    /// Print environment variables for shell integration
    Env {
        /// Installation directory
        #[arg(short, long)]
        dir: Option<PathBuf>,

        /// Output format (shell, json)
        #[arg(short, long, default_value = "shell")]
        format: String,
    },

    /// Create a portable bundle with MSVC toolchain (downloads components locally)
    Bundle {
        /// Output directory for the bundle
        #[arg(short, long, default_value = "./msvc-bundle")]
        output: PathBuf,

        /// Target architecture (x64, x86, arm64)
        #[arg(short, long, default_value = "x64")]
        arch: String,

        /// Host architecture for cross-compilation (x64, x86, arm64)
        /// Defaults to current system architecture
        #[arg(long)]
        host_arch: Option<String>,

        /// MSVC version to download (default: latest)
        #[arg(long)]
        msvc_version: Option<String>,

        /// Windows SDK version to download (default: latest)
        #[arg(long)]
        sdk_version: Option<String>,

        /// Accept Microsoft license terms (required)
        #[arg(long)]
        accept_license: bool,

        /// Create a zip archive of the bundle
        #[arg(long)]
        zip: bool,
    },

    #[cfg(feature = "self-update")]
    /// Update msvc-kit to the latest version
    Update {
        /// Check for updates without installing
        #[arg(long)]
        check: bool,

        /// Update to a specific version
        #[arg(long)]
        version: Option<String>,
    },
}

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let cli = Cli::parse();

    // Initialize logging
    let filter = if cli.verbose {
        EnvFilter::new("debug")
    } else {
        EnvFilter::new("info")
    };

    tracing_subscriber::registry()
        .with(fmt::layer())
        .with(filter)
        .init();

    // Load configuration
    let mut config = load_config().unwrap_or_default();

    // Handle the case where no subcommand is provided (for winget compatibility)
    let command = match cli.command {
        Some(cmd) => cmd,
        None => {
            // Print help and exit with code 0 for winget validation
            Cli::command().print_help().unwrap();
            return Ok(());
        }
    };

    match command {
        Commands::Download {
            msvc_version,
            sdk_version,
            target,
            arch,
            no_msvc,
            no_sdk,
            no_verify,
            parallel_downloads,
            include_components,
            exclude_patterns,
        } => {
            let target_dir = target.unwrap_or_else(|| config.install_dir.clone());
            let arch: Architecture = arch.parse().map_err(|e: String| anyhow::anyhow!(e))?;

            // Parse component strings into MsvcComponent enum values
            let components = include_components
                .iter()
                .filter_map(|s| {
                    s.parse::<MsvcComponent>()
                        .map_err(|e| eprintln!("⚠️  Warning: {}", e))
                        .ok()
                })
                .collect();

            let options = DownloadOptions {
                msvc_version,
                sdk_version,
                target_dir: target_dir.clone(),
                arch,
                host_arch: Some(Architecture::host()),
                verify_hashes: !no_verify,
                parallel_downloads: parallel_downloads.unwrap_or(config.parallel_downloads),
                http_client: None,
                progress_handler: None,
                cache_manager: None,
                dry_run: false,
                include_components: components,
                exclude_patterns,
            };

            println!("📦 msvc-kit - Downloading MSVC Build Tools\n");
            println!("Target directory: {}", target_dir.display());
            println!("Architecture: {}", arch);
            println!();

            if !no_msvc {
                println!("⬇️  Downloading MSVC compiler...");
                let mut msvc_info = download_msvc(&options).await?;
                println!("📁 Extracting MSVC packages...");
                msvc_kit::extract_and_finalize_msvc(&mut msvc_info).await?;
                println!(
                    "✅ MSVC {} installed to {}",
                    msvc_info.version,
                    target_dir.display()
                );
            }

            if !no_sdk {
                println!("\n⬇️  Downloading Windows SDK...");
                let sdk_info = download_sdk(&options).await?;
                println!("📁 Extracting SDK packages...");
                msvc_kit::extract_and_finalize_sdk(&sdk_info).await?;
                println!(
                    "✅ Windows SDK {} installed to {}",
                    sdk_info.version,
                    target_dir.display()
                );
            }

            println!("\n🎉 Download complete!");
            println!("\nRun 'msvc-kit setup' to configure environment variables.");
        }

        Commands::Setup {
            dir,
            arch,
            script,
            shell,
            portable_root,
            persistent,
        } => {
            let install_dir = dir.unwrap_or_else(|| config.install_dir.clone());
            let arch: Architecture = arch.parse().map_err(|e: String| anyhow::anyhow!(e))?;

            // Find installed versions
            let msvc_versions = list_installed_msvc(&install_dir);
            let sdk_versions = list_installed_sdk(&install_dir);

            if msvc_versions.is_empty() {
                anyhow::bail!("No MSVC installation found. Run 'msvc-kit download' first.");
            }

            let msvc_version = &msvc_versions[0];
            let sdk_version = sdk_versions.first();

            // Create mock install info for environment setup
            let msvc_info = msvc_kit::installer::InstallInfo {
                component_type: "msvc".to_string(),
                version: msvc_version.version.clone(),
                install_path: msvc_version.install_path.clone().unwrap(),
                downloaded_files: vec![],
                arch,
            };

            let sdk_info = sdk_version.map(|v| msvc_kit::installer::InstallInfo {
                component_type: "sdk".to_string(),
                version: v.version.clone(),
                install_path: v.install_path.clone().unwrap(),
                downloaded_files: vec![],
                arch,
            });

            let env = setup_environment(&msvc_info, sdk_info.as_ref())?;

            if script {
                let shell_type = match shell.to_lowercase().as_str() {
                    "cmd" | "bat" => ShellType::Cmd,
                    "powershell" | "ps1" | "pwsh" => ShellType::PowerShell,
                    "bash" | "sh" => ShellType::Bash,
                    _ => ShellType::detect(),
                };

                // Create script context based on whether portable root is specified
                let ctx = if let Some(ref _portable_root) = portable_root {
                    // Use portable mode with relative paths
                    ScriptContext::portable(
                        &env.vc_tools_version,
                        &env.windows_sdk_version,
                        arch,
                        arch,
                    )
                } else {
                    // Use absolute mode with actual paths
                    ScriptContext::absolute(
                        install_dir.clone(),
                        &env.vc_tools_version,
                        &env.windows_sdk_version,
                        arch,
                        arch,
                    )
                };

                let script_content = generate_script(&ctx, shell_type)?;
                println!("{}", script_content);
            } else if persistent {
                #[cfg(windows)]
                {
                    msvc_kit::env::write_to_registry(&env)?;
                    println!("✅ Environment variables written to registry.");
                    println!("Please restart your terminal for changes to take effect.");
                }
                #[cfg(not(windows))]
                {
                    anyhow::bail!("Persistent environment setup is only supported on Windows.");
                }
            } else {
                // Print instructions for temporary setup
                let shell_type = ShellType::detect();
                let _script = generate_activation_script(&env, shell_type)?;

                println!("📋 MSVC Environment Setup\n");
                println!("To activate the MSVC environment, run:\n");

                match shell_type {
                    ShellType::Cmd => {
                        println!("  msvc-kit setup --script --shell cmd > activate.bat");
                        println!("  activate.bat");
                    }
                    ShellType::PowerShell => {
                        println!(
                            "  msvc-kit setup --script --shell powershell | Invoke-Expression"
                        );
                        println!("\nOr save to a file:");
                        println!("  msvc-kit setup --script --shell powershell > activate.ps1");
                        println!("  . .\\activate.ps1");
                    }
                    ShellType::Bash => {
                        println!("  eval \"$(msvc-kit setup --script --shell bash)\"");
                    }
                }

                println!("\nFor persistent setup (Windows only):");
                println!("  msvc-kit setup --persistent");
            }
        }

        Commands::List { dir, available } => {
            let install_dir = dir.unwrap_or_else(|| config.install_dir.clone());

            if available {
                println!("📋 Fetching available versions from Microsoft...\n");

                let manifest = msvc_kit::downloader::VsManifest::fetch().await?;

                if let Some(msvc) = manifest.get_latest_msvc_version() {
                    println!("Latest MSVC version: {}", msvc);
                }
                if let Some(sdk) = manifest.get_latest_sdk_version() {
                    println!("Latest Windows SDK version: {}", sdk);
                }
            } else {
                println!("📋 Installed versions in {}\n", install_dir.display());

                let msvc_versions = list_installed_msvc(&install_dir);
                let sdk_versions = list_installed_sdk(&install_dir);

                if msvc_versions.is_empty() && sdk_versions.is_empty() {
                    println!("No installations found.");
                    println!("\nRun 'msvc-kit download' to install MSVC and Windows SDK.");
                } else {
                    if !msvc_versions.is_empty() {
                        println!("MSVC Compiler:");
                        for v in &msvc_versions {
                            println!("  - {}", v);
                        }
                    }

                    if !sdk_versions.is_empty() {
                        println!("\nWindows SDK:");
                        for v in &sdk_versions {
                            println!("  - {}", v);
                        }
                    }
                }
            }
        }

        Commands::Clean {
            dir,
            msvc_version,
            sdk_version,
            all,
            cache,
        } => {
            let install_dir = dir.unwrap_or_else(|| config.install_dir.clone());

            if all {
                println!("🗑️  Removing all installed versions...");

                if install_dir.exists() {
                    tokio::fs::remove_dir_all(&install_dir).await?;
                    println!("✅ Removed {}", install_dir.display());
                }
            } else {
                if let Some(version) = msvc_version {
                    let msvc_path = install_dir
                        .join("VC")
                        .join("Tools")
                        .join("MSVC")
                        .join(&version);
                    if msvc_path.exists() {
                        tokio::fs::remove_dir_all(&msvc_path).await?;
                        println!("✅ Removed MSVC {}", version);
                    } else {
                        println!("⚠️  MSVC {} not found", version);
                    }
                }

                if let Some(version) = sdk_version {
                    let sdk_path = install_dir
                        .join("Windows Kits")
                        .join("10")
                        .join("Include")
                        .join(&version);
                    if sdk_path.exists() {
                        // Remove SDK version from all subdirectories
                        for subdir in ["Include", "Lib", "bin"] {
                            let path = install_dir
                                .join("Windows Kits")
                                .join("10")
                                .join(subdir)
                                .join(&version);
                            if path.exists() {
                                tokio::fs::remove_dir_all(&path).await?;
                            }
                        }
                        println!("✅ Removed Windows SDK {}", version);
                    } else {
                        println!("⚠️  Windows SDK {} not found", version);
                    }
                }
            }

            if cache {
                let cache_dir = install_dir.join("downloads");
                if cache_dir.exists() {
                    tokio::fs::remove_dir_all(&cache_dir).await?;
                    println!("✅ Removed download cache");
                }
            }
        }

        Commands::Config {
            set_dir,
            set_msvc,
            set_sdk,
            reset,
        } => {
            if reset {
                config = MsvcKitConfig::default();
                save_config(&config)?;
                println!("✅ Configuration reset to defaults");
            } else if set_dir.is_some() || set_msvc.is_some() || set_sdk.is_some() {
                if let Some(dir) = set_dir {
                    config.install_dir = dir;
                }
                if let Some(msvc) = set_msvc {
                    config.default_msvc_version = Some(msvc);
                }
                if let Some(sdk) = set_sdk {
                    config.default_sdk_version = Some(sdk);
                }
                save_config(&config)?;
                println!("✅ Configuration updated");
            }

            println!("📋 Current configuration:\n");
            println!("  Install directory: {}", config.install_dir.display());
            println!(
                "  Default MSVC version: {}",
                config.default_msvc_version.as_deref().unwrap_or("latest")
            );
            println!(
                "  Default SDK version: {}",
                config.default_sdk_version.as_deref().unwrap_or("latest")
            );
            println!("  Default architecture: {}", config.default_arch);
            println!("  Verify hashes: {}", config.verify_hashes);
            println!("  Parallel downloads: {}", config.parallel_downloads);
        }

        Commands::Bundle {
            output,
            arch,
            host_arch,
            msvc_version,
            sdk_version,
            accept_license,
            zip,
        } => {
            if !accept_license {
                println!("⚠️  License Agreement Required\n");
                println!(
                    "The MSVC compiler and Windows SDK are subject to Microsoft's license terms:"
                );
                println!("  https://visualstudio.microsoft.com/license-terms/\n");
                println!("By using --accept-license, you confirm that you have read and accepted");
                println!("Microsoft's Visual Studio License Terms.\n");
                println!("Usage:");
                println!("  msvc-kit bundle --accept-license [--output <dir>] [--arch <arch>]\n");
                anyhow::bail!(
                    "You must accept the license terms with --accept-license to proceed."
                );
            }

            let arch: Architecture = arch.parse().map_err(|e: String| anyhow::anyhow!(e))?;
            let host_arch: Architecture = host_arch
                .map(|s| s.parse().map_err(|e: String| anyhow::anyhow!(e)))
                .transpose()?
                .unwrap_or_else(Architecture::host);

            println!("📦 msvc-kit - Creating Portable MSVC Bundle\n");
            println!("Output directory: {}", output.display());
            println!("Target architecture: {}", arch);
            println!("Host architecture: {}", host_arch);
            println!();

            // Create output directory
            tokio::fs::create_dir_all(&output).await?;

            // Download options - download directly to bundle root (not runtime/)
            let options = DownloadOptions {
                msvc_version: msvc_version.clone(),
                sdk_version: sdk_version.clone(),
                target_dir: output.clone(),
                arch,
                host_arch: Some(host_arch),
                verify_hashes: true,
                parallel_downloads: config.parallel_downloads,
                http_client: None,
                progress_handler: None,
                cache_manager: None,
                dry_run: false,
                include_components: Default::default(),
                exclude_patterns: Default::default(),
            };

            // Download and extract MSVC
            println!("⬇️  Downloading MSVC compiler...");
            let mut msvc_info = download_msvc(&options).await?;
            println!("📁 Extracting MSVC packages...");
            msvc_kit::extract_and_finalize_msvc(&mut msvc_info).await?;
            let msvc_ver = msvc_info.version.clone();
            println!("✅ MSVC {} installed", msvc_ver);

            // Download and extract SDK
            println!("\n⬇️  Downloading Windows SDK...");
            let sdk_info = download_sdk(&options).await?;
            println!("📁 Extracting SDK packages...");
            msvc_kit::extract_and_finalize_sdk(&sdk_info).await?;
            let sdk_ver = sdk_info.version.clone();
            println!("✅ Windows SDK {} installed", sdk_ver);

            // Create bundle layout
            let layout = BundleLayout::from_root_with_versions(
                &output, &msvc_ver, &sdk_ver, arch, host_arch,
            )?;

            // Generate and save activation scripts (includes README)
            let scripts = generate_bundle_scripts(&layout)?;
            save_bundle_scripts(&layout, &scripts).await?;

            // Copy msvc-kit executable
            let exe_name = if cfg!(windows) {
                "msvc-kit.exe"
            } else {
                "msvc-kit"
            };
            let current_exe = std::env::current_exe()?;
            let target_exe = output.join(exe_name);
            tokio::fs::copy(&current_exe, &target_exe).await?;

            println!("\n✅ Bundle created successfully!");
            println!("\nContents:");
            println!("  {}/", output.display());
            println!("  ├── {}", exe_name);
            println!("  ├── setup.bat");
            println!("  ├── setup.ps1");
            println!("  ├── setup.sh");
            println!("  ├── README.txt");
            println!("  ├── VC/Tools/MSVC/{}/", msvc_ver);
            println!("  └── Windows Kits/10/");

            if zip {
                println!("\n📦 Creating zip archive...");
                let zip_name = format!(
                    "msvc-kit-bundle-{}-{}-{}.zip",
                    msvc_ver.replace('.', "_"),
                    sdk_ver.replace('.', "_"),
                    arch
                );
                let zip_path = output.parent().unwrap_or(&output).join(&zip_name);

                #[cfg(windows)]
                {
                    let output_str = output.display().to_string();
                    let zip_str = zip_path.display().to_string();
                    let status = std::process::Command::new("powershell")
                        .args([
                            "-NoProfile",
                            "-Command",
                            &format!(
                                "Compress-Archive -Path '{}\\*' -DestinationPath '{}' -Force",
                                output_str, zip_str
                            ),
                        ])
                        .status()?;
                    if status.success() {
                        println!("✅ Created: {}", zip_path.display());
                    } else {
                        println!("⚠️  Failed to create zip archive");
                    }
                }
                #[cfg(not(windows))]
                {
                    println!("⚠️  Zip creation is only supported on Windows");
                }
            }

            println!("\n🎉 Done! Run setup.bat (cmd) or .\\setup.ps1 (PowerShell) to activate.");
        }

        Commands::Env { dir, format } => {
            let install_dir = dir.unwrap_or_else(|| config.install_dir.clone());

            let msvc_versions = list_installed_msvc(&install_dir);
            if msvc_versions.is_empty() {
                anyhow::bail!("No MSVC installation found. Run 'msvc-kit download' first.");
            }

            let msvc_version = &msvc_versions[0];
            let sdk_versions = list_installed_sdk(&install_dir);
            let sdk_version = sdk_versions.first();

            let msvc_info = msvc_kit::installer::InstallInfo {
                component_type: "msvc".to_string(),
                version: msvc_version.version.clone(),
                install_path: msvc_version.install_path.clone().unwrap(),
                downloaded_files: vec![],
                arch: config.default_arch,
            };

            let sdk_info = sdk_version.map(|v| msvc_kit::installer::InstallInfo {
                component_type: "sdk".to_string(),
                version: v.version.clone(),
                install_path: v.install_path.clone().unwrap(),
                downloaded_files: vec![],
                arch: config.default_arch,
            });

            let env = setup_environment(&msvc_info, sdk_info.as_ref())?;
            let vars = get_env_vars(&env);

            match format.as_str() {
                "json" => {
                    println!("{}", serde_json::to_string_pretty(&vars)?);
                }
                _ => {
                    for (key, value) in &vars {
                        println!("{}={}", key, value);
                    }
                }
            }
        }

        #[cfg(feature = "self-update")]
        Commands::Update { check, version } => {
            let current_version = env!("CARGO_PKG_VERSION");

            // Configure axoupdater with GitHub release source (no cargo-dist receipt needed)
            let source = axoupdater::ReleaseSource {
                release_type: axoupdater::ReleaseSourceType::GitHub,
                owner: "loonghao".to_string(),
                name: "msvc-kit".to_string(),
                app_name: "msvc-kit".to_string(),
            };

            let mut updater = axoupdater::AxoUpdater::new_for("msvc-kit");
            updater.set_release_source(source);
            updater
                .set_current_version(
                    current_version
                        .parse()
                        .map_err(|e| anyhow::anyhow!("Failed to parse current version: {}", e))?,
                )
                .map_err(|e| anyhow::anyhow!("{}", e))?;

            // Disable installer output noise
            updater.disable_installer_output();

            if let Some(ref target_version) = version {
                updater.configure_version_specifier(axoupdater::UpdateRequest::SpecificVersion(
                    target_version.clone(),
                ));
                updater.always_update(true);
            }

            if check {
                println!("🔍 Checking for updates...\n");
                println!("Current version: v{}", current_version);

                match updater.query_new_version().await {
                    Ok(Some(new_version)) => {
                        println!("Latest version:  v{}", new_version);
                        println!("\n📦 A new version is available!");
                        println!("Run 'msvc-kit update' to upgrade.");
                    }
                    Ok(None) => {
                        println!("\n✅ You are running the latest version.");
                    }
                    Err(e) => {
                        println!("⚠️  Failed to check for updates: {}", e);
                    }
                }
            } else {
                println!("🔄 Updating msvc-kit...\n");
                println!("Current version: v{}", current_version);

                match updater.run().await {
                    Ok(Some(result)) => {
                        println!("\n✅ Updated to v{}!", result.new_version);
                        println!("Please restart msvc-kit to use the new version.");
                    }
                    Ok(None) => {
                        println!(
                            "\n✅ Already running the latest version (v{}).",
                            current_version
                        );
                    }
                    Err(e) => {
                        anyhow::bail!("Failed to update: {}", e);
                    }
                }
            }
        }
    }

    Ok(())
}