ccgo 3.4.1

A high-performance C++ cross-platform build CLI
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
//! Windows platform builder
//!
//! Builds static and dynamic libraries for Windows using CMake with MinGW or MSVC.
//! Supports cross-compilation from macOS/Linux using MinGW-w64.

use std::path::PathBuf;
use std::time::Instant;

use anyhow::{bail, Context, Result};

use crate::build::archive::{get_unified_include_path, ArchiveBuilder};
use crate::build::cmake::{BuildType, CMakeConfig};
use crate::build::toolchains::mingw::{is_mingw_available, MingwToolchain};
use crate::build::toolchains::msvc::{is_msvc_available, MsvcToolchain};
use crate::build::toolchains::Toolchain;
use crate::build::{BuildContext, BuildResult, PlatformBuilder};
use crate::commands::build::LinkType;

/// Windows toolchain type
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum WindowsToolchain {
    /// MinGW-w64 (cross-compilation)
    MinGW,
    /// Microsoft Visual C++ (Windows only)
    MSVC,
}

impl WindowsToolchain {
    /// Get the toolchain name for archive paths
    pub fn name(&self) -> &str {
        match self {
            WindowsToolchain::MinGW => "mingw",
            WindowsToolchain::MSVC => "msvc",
        }
    }
}

/// Windows platform builder
pub struct WindowsBuilder;

impl WindowsBuilder {
    pub fn new() -> Self {
        Self
    }

    /// Merge all module static libraries into a single library (MinGW)
    /// This is essential for KMP cinterop which expects a single complete library
    fn merge_module_static_libs_mingw(
        &self,
        mingw: &MingwToolchain,
        build_dir: &PathBuf,
        lib_name: &str,
        verbose: bool,
    ) -> Result<()> {
        // Find the output directory where CMake puts libraries
        let out_dir = build_dir.join("out");
        if !out_dir.exists() {
            // No out directory means no libraries to merge
            return Ok(());
        }

        // Check if the main library already exists (CMake may have already merged it)
        let main_lib_name = format!("lib{}.a", lib_name);
        let main_lib_path = out_dir.join(&main_lib_name);

        if main_lib_path.exists() {
            // Check if it's a non-empty file (CMake already created the merged library)
            if let Ok(metadata) = std::fs::metadata(&main_lib_path) {
                if metadata.len() > 0 {
                    if verbose {
                        eprintln!("    Main library {} already exists, skipping merge", main_lib_name);
                    }
                    // Clean up module libraries (keep output directory clean)
                    for entry in std::fs::read_dir(&out_dir)? {
                        let entry = entry?;
                        let path = entry.path();
                        if path.is_file() && path != main_lib_path {
                            if let Some(ext) = path.extension() {
                                if ext == "a" {
                                    let _ = std::fs::remove_file(&path);
                                }
                            }
                        }
                    }
                    return Ok(());
                }
            }
        }

        // Find all .a files (module libraries)
        let mut module_libs: Vec<PathBuf> = Vec::new();
        for entry in std::fs::read_dir(&out_dir)? {
            let entry = entry?;
            let path = entry.path();
            if path.is_file() {
                if let Some(ext) = path.extension() {
                    if ext == "a" {
                        module_libs.push(path);
                    }
                }
            }
        }

        if module_libs.is_empty() {
            return Ok(());
        }

        // Check if we only have the main library (already merged or single module)
        if module_libs.len() == 1 && module_libs[0].file_name().map_or(false, |n| n == main_lib_name.as_str()) {
            // Already a single main library, nothing to merge
            return Ok(());
        }

        // Filter out the main library if it exists (we'll recreate it)
        module_libs.retain(|p| p != &main_lib_path);

        if module_libs.is_empty() {
            return Ok(());
        }

        if verbose {
            eprintln!(
                "    Merging {} module libraries into {}",
                module_libs.len(),
                main_lib_name
            );
        }

        // Merge all module libraries into the main library
        mingw.merge_static_libs(&module_libs, &main_lib_path)?;

        // Clean up module libraries after merge (optional, keeps output clean)
        for lib in &module_libs {
            if lib != &main_lib_path {
                let _ = std::fs::remove_file(lib);
            }
        }

        Ok(())
    }

    /// Merge third-party static libs from cmake build root into the main lib (MinGW)
    fn merge_third_party_static_libs_mingw(
        &self,
        mingw: &MingwToolchain,
        build_dir: &PathBuf,
        lib_name: &str,
        verbose: bool,
    ) -> Result<()> {
        let out_dir = build_dir.join("out");
        let main_lib_path = out_dir.join(format!("lib{}.a", lib_name));
        if !main_lib_path.exists() {
            return Ok(());
        }

        let placeholder_name = format!("lib{}.a", lib_name);
        let mut third_party_libs: Vec<PathBuf> = Vec::new();
        for entry in std::fs::read_dir(build_dir)? {
            let entry = entry?;
            let path = entry.path();
            if path.is_file() {
                if let Some(ext) = path.extension() {
                    if ext == "a" {
                        let fname = path.file_name().unwrap_or_default().to_str().unwrap_or_default();
                        if fname != placeholder_name {
                            third_party_libs.push(path);
                        }
                    }
                }
            }
        }

        if third_party_libs.is_empty() {
            return Ok(());
        }

        if verbose {
            eprintln!("    Merging {} third-party libs into {}", third_party_libs.len(), placeholder_name);
        }

        let mut all_libs = vec![main_lib_path.clone()];
        all_libs.extend(third_party_libs);
        mingw.merge_static_libs(&all_libs, &main_lib_path)?;

        Ok(())
    }

    /// Detect available Windows toolchain
    fn detect_toolchain() -> Result<WindowsToolchain> {
        // Prefer MinGW for cross-platform builds
        if is_mingw_available() {
            return Ok(WindowsToolchain::MinGW);
        }

        // Fall back to MSVC on Windows
        if is_msvc_available() {
            return Ok(WindowsToolchain::MSVC);
        }

        bail!(
            "No Windows toolchain found.\n\
             - For cross-compilation: Install MinGW-w64 (x86_64-w64-mingw32-gcc)\n\
             - For native builds: Install Visual Studio with C++ tools"
        )
    }

    /// Build for a specific link type with MinGW
    fn build_with_mingw(
        &self,
        ctx: &BuildContext,
        mingw: &MingwToolchain,
        link_type: &str,
    ) -> Result<PathBuf> {
        let build_dir = ctx
            .cmake_build_dir
            .join(format!("{}/mingw", link_type));
        let install_dir = build_dir.join("install");

        let build_shared = link_type == "shared";

        // Get MinGW CMake variables
        let cmake_vars = mingw.cmake_variables_for_arch();

        // Configure and build with CMake
        let mut cmake = CMakeConfig::new(ctx.project_root.clone(), build_dir.clone())
            .generator("Unix Makefiles")
            .build_type(if ctx.options.release {
                BuildType::Release
            } else {
                BuildType::Debug
            })
            .install_prefix(install_dir.clone())
            .variable("CCGO_BUILD_STATIC", if build_shared { "OFF" } else { "ON" })
            .variable("CCGO_BUILD_SHARED", if build_shared { "ON" } else { "OFF" })
            .variable("CCGO_BUILD_SHARED_LIBS", if build_shared { "ON" } else { "OFF" })
            .variable("CCGO_LIB_NAME", ctx.lib_name())
            .jobs(ctx.jobs())
            .verbose(ctx.options.verbose);

        // Add CCGO_CMAKE_DIR if available
        if let Some(cmake_dir) = ctx.ccgo_cmake_dir() {
            cmake = cmake.variable("CCGO_CMAKE_DIR", cmake_dir.display().to_string());
        }

        // Add MinGW-specific variables
        for (name, value) in cmake_vars {
            cmake = cmake.variable(&name, &value);
        }

        // Add CCGO configuration variables
        cmake = cmake.variable(
            "CCGO_CONFIG_PRESET_VISIBILITY",
            ctx.symbol_visibility().to_string(),
        );

        // Add submodule dependencies for shared library linking
        if let Some(deps_map) = ctx.deps_map() {
            cmake = cmake.variable("CCGO_CONFIG_DEPS_MAP", deps_map);
        }

        // Add feature definitions for conditional compilation
        if let Ok(feature_defines) = ctx.cmake_feature_defines() {
            if !feature_defines.is_empty() {
                cmake = cmake.feature_definitions(&feature_defines);
                if ctx.options.verbose {
                    eprintln!("    Enabled features: {}", feature_defines.replace(';', ", "));
                }
            }
        }

        // Add compiler cache if available
        if let Some(cache) = ctx.compiler_cache() {
            cmake = cmake.compiler_cache(cache);
        }

        cmake.configure_build_install()?;

        // For static builds, merge all module libraries into a single library
        // This is essential for KMP cinterop which expects a single complete library
        if !build_shared {
            self.merge_module_static_libs_mingw(mingw, &build_dir, ctx.lib_name(), ctx.options.verbose)?;
            self.merge_third_party_static_libs_mingw(mingw, &build_dir, ctx.lib_name(), ctx.options.verbose)?;
        }

        Ok(build_dir)
    }

    /// Build for a specific link type with MSVC
    /// Supports both native Windows (Visual Studio) and Linux (xwin + clang-cl)
    fn build_with_msvc(
        &self,
        ctx: &BuildContext,
        msvc: &MsvcToolchain,
        link_type: &str,
    ) -> Result<PathBuf> {
        let build_dir = ctx
            .cmake_build_dir
            .join(format!("{}/msvc", link_type));
        let install_dir = build_dir.join("install");

        let build_shared = link_type == "shared";

        // Configure and build with CMake
        let mut cmake = CMakeConfig::new(ctx.project_root.clone(), build_dir.clone())
            .generator(msvc.cmake_generator())
            .build_type(if ctx.options.release {
                BuildType::Release
            } else {
                BuildType::Debug
            })
            .install_prefix(install_dir.clone())
            .variable("CCGO_BUILD_STATIC", if build_shared { "OFF" } else { "ON" })
            .variable("CCGO_BUILD_SHARED", if build_shared { "ON" } else { "OFF" })
            .variable("CCGO_BUILD_SHARED_LIBS", if build_shared { "ON" } else { "OFF" })
            .variable("CCGO_LIB_NAME", ctx.lib_name())
            .jobs(ctx.jobs())
            .verbose(ctx.options.verbose);

        // Add MSVC-specific CMake variables
        for (name, value) in msvc.cmake_variables() {
            cmake = cmake.variable(&name, &value);
        }

        // Add CCGO_CMAKE_DIR if available
        if let Some(cmake_dir) = ctx.ccgo_cmake_dir() {
            cmake = cmake.variable("CCGO_CMAKE_DIR", cmake_dir.display().to_string());
        }

        // Add CCGO configuration variables
        cmake = cmake.variable(
            "CCGO_CONFIG_PRESET_VISIBILITY",
            ctx.symbol_visibility().to_string(),
        );

        // Add submodule dependencies for shared library linking
        if let Some(deps_map) = ctx.deps_map() {
            cmake = cmake.variable("CCGO_CONFIG_DEPS_MAP", deps_map);
        }

        // Add feature definitions for conditional compilation
        if let Ok(feature_defines) = ctx.cmake_feature_defines() {
            if !feature_defines.is_empty() {
                cmake = cmake.feature_definitions(&feature_defines);
                if ctx.options.verbose {
                    eprintln!("    Enabled features: {}", feature_defines.replace(';', ", "));
                }
            }
        }

        // Add compiler cache if available
        if let Some(cache) = ctx.compiler_cache() {
            cmake = cmake.compiler_cache(cache);
        }

        cmake.configure_build_install()?;

        Ok(build_dir)
    }

    /// Find library files in build directory
    fn find_libraries(
        &self,
        build_dir: &PathBuf,
        is_shared: bool,
        toolchain: WindowsToolchain,
    ) -> Result<Vec<PathBuf>> {
        let (static_ext, shared_ext) = match toolchain {
            WindowsToolchain::MinGW => ("a", "dll"),
            WindowsToolchain::MSVC => ("lib", "dll"),
        };

        let extension = if is_shared { shared_ext } else { static_ext };
        let mut libs = Vec::new();

        // Check multiple possible directories
        // Prioritize out/ directory where CCGO cmake puts the merged library
        // This avoids including intermediate module libs (e.g., lib{name}-api.a)
        let possible_dirs = vec![
            build_dir.join("out"),           // Merged library (priority)
            build_dir.join("install/lib"),   // Fallback: CMake install location
            build_dir.join("lib"),
            build_dir.join("bin"),           // DLLs often go to bin/
        ];

        for lib_dir in possible_dirs {
            if !lib_dir.exists() {
                continue;
            }

            for entry in std::fs::read_dir(&lib_dir)? {
                let entry = entry?;
                let path = entry.path();
                if path.is_file() {
                    if let Some(ext) = path.extension() {
                        if ext == extension {
                            // Avoid duplicates
                            if !libs
                                .iter()
                                .any(|p: &PathBuf| p.file_name() == path.file_name())
                            {
                                libs.push(path);
                            }
                        }
                    }
                }
            }

            // If we found libraries, stop searching
            if !libs.is_empty() {
                break;
            }
        }

        // For shared libraries, also look for import libraries (.dll.a or .lib)
        if is_shared {
            let import_ext = match toolchain {
                WindowsToolchain::MinGW => "dll.a",
                WindowsToolchain::MSVC => "lib",
            };

            // Prioritize out/ directory for import libraries as well
            for lib_dir in &[
                build_dir.join("out"),
                build_dir.join("install/lib"),
                build_dir.join("lib"),
            ] {
                if !lib_dir.exists() {
                    continue;
                }

                for entry in std::fs::read_dir(lib_dir)? {
                    let entry = entry?;
                    let path = entry.path();
                    if path.is_file() {
                        let name = path.file_name().unwrap().to_str().unwrap();
                        if name.ends_with(import_ext) {
                            if !libs.iter().any(|p: &PathBuf| p.file_name() == path.file_name()) {
                                libs.push(path);
                            }
                        }
                    }
                }
            }
        }

        Ok(libs)
    }

    /// Build for a specific link type
    fn build_link_type(
        &self,
        ctx: &BuildContext,
        link_type: &str,
        toolchain: WindowsToolchain,
    ) -> Result<PathBuf> {
        if ctx.options.verbose {
            eprintln!(
                "Building {} library for Windows ({})...",
                link_type,
                toolchain.name()
            );
        }

        match toolchain {
            WindowsToolchain::MinGW => {
                let mingw = MingwToolchain::detect()?;
                self.build_with_mingw(ctx, &mingw, link_type)
            }
            WindowsToolchain::MSVC => {
                let msvc = MsvcToolchain::detect()?;
                self.build_with_msvc(ctx, &msvc, link_type)
            }
        }
    }

    /// Add libraries to archive with toolchain-specific paths
    fn add_libraries_to_archive(
        &self,
        archive: &ArchiveBuilder,
        build_dir: &PathBuf,
        link_type: &str,
        is_shared: bool,
        toolchain: WindowsToolchain,
    ) -> Result<()> {
        let libs = self.find_libraries(build_dir, is_shared, toolchain)?;

        for lib in &libs {
            let lib_name = lib.file_name().unwrap().to_str().unwrap();
            // Archive path: lib/windows/{static|shared}/{toolchain}/{lib_name}
            let dest = format!(
                "lib/{}/{}/{}/{}",
                self.platform_name(),
                link_type,
                toolchain.name(),
                lib_name
            );
            archive.add_file(lib, &dest)?;
        }

        Ok(())
    }

    /// Generate Visual Studio IDE project for Windows
    pub fn generate_ide_project(&self, ctx: &BuildContext) -> Result<BuildResult> {
        use std::process::Command;

        let build_dir = ctx.cmake_build_dir.join("ide_project");

        // Clean build directory
        if build_dir.exists() {
            std::fs::remove_dir_all(&build_dir)
                .with_context(|| format!("Failed to clean {}", build_dir.display()))?;
        }

        // Create build directory
        std::fs::create_dir_all(&build_dir)
            .with_context(|| format!("Failed to create {}", build_dir.display()))?;

        // Determine generator based on available toolchain
        let (generator, toolchain_name) = if is_msvc_available() {
            ("Visual Studio 17 2022", "MSVC")
        } else if is_mingw_available() {
            // MinGW can use CodeLite or just Unix Makefiles with compile_commands.json
            ("CodeLite - MinGW Makefiles", "MinGW")
        } else {
            bail!(
                "No Windows toolchain found for IDE project generation.\n\
                 - For Visual Studio: Install Visual Studio with C++ tools\n\
                 - For MinGW: Install MinGW-w64"
            );
        };

        eprintln!(
            "Generating {} project for Windows in {}...",
            toolchain_name,
            build_dir.display()
        );

        // Configure with CMake
        let mut cmake_cmd = Command::new("cmake");
        cmake_cmd
            .arg("-S")
            .arg(&ctx.project_root)
            .arg("-B")
            .arg(&build_dir)
            .arg("-G")
            .arg(generator)
            .arg("-DCMAKE_EXPORT_COMPILE_COMMANDS=ON");

        // Add CCGO_CMAKE_DIR if available
        if let Some(cmake_dir) = ctx.ccgo_cmake_dir() {
            cmake_cmd.arg(format!("-DCCGO_CMAKE_DIR={}", cmake_dir.display()));
        }

        // Add lib name
        cmake_cmd.arg(format!("-DCCGO_LIB_NAME={}", ctx.lib_name()));

        if ctx.options.verbose {
            eprintln!("CMake configure: {:?}", cmake_cmd);
        }

        let status = cmake_cmd.status().context("Failed to run CMake configure")?;
        if !status.success() {
            bail!("CMake configure failed");
        }

        // Find and report project file
        let sln_file = build_dir.join(format!("{}.sln", ctx.lib_name()));
        let workspace_file = build_dir.join(format!("{}.workspace", ctx.lib_name()));

        if sln_file.exists() {
            eprintln!(
                "\n✓ Visual Studio solution generated: {}",
                sln_file.display()
            );

            // Try to open the solution on Windows
            #[cfg(target_os = "windows")]
            {
                let _ = Command::new("cmd")
                    .args(["/C", "start", ""])
                    .arg(&sln_file)
                    .status();
            }
        } else if workspace_file.exists() {
            eprintln!(
                "\n✓ CodeLite workspace generated: {}",
                workspace_file.display()
            );
        } else {
            eprintln!(
                "\n✓ IDE project files generated in: {}",
                build_dir.display()
            );
        }

        // Report compile_commands.json for IDEs that use it
        let compile_commands = build_dir.join("compile_commands.json");
        if compile_commands.exists() {
            eprintln!(
                "   compile_commands.json: {}",
                compile_commands.display()
            );
        }

        // Return a placeholder result for IDE generation
        Ok(BuildResult {
            sdk_archive: build_dir,
            symbols_archive: None,
            aar_archive: None,
            duration_secs: 0.0,
            architectures: vec![],
        })
    }

    /// Strip shared libraries (MinGW only)
    fn strip_libraries(
        &self,
        mingw: &MingwToolchain,
        build_dir: &PathBuf,
        verbose: bool,
    ) -> Result<()> {
        let strip_path = mingw.strip_path();
        let libs = self.find_libraries(build_dir, true, WindowsToolchain::MinGW)?;

        for lib in libs {
            // Only strip DLLs
            if let Some(ext) = lib.extension() {
                if ext == "dll" {
                    if verbose {
                        eprintln!("  Stripping {}...", lib.display());
                    }

                    let status = std::process::Command::new(&strip_path)
                        .arg("--strip-unneeded")
                        .arg(&lib)
                        .status()
                        .with_context(|| format!("Failed to strip {}", lib.display()))?;

                    if !status.success() && verbose {
                        eprintln!("Warning: Failed to strip {}", lib.display());
                    }
                }
            }
        }

        Ok(())
    }
}

impl PlatformBuilder for WindowsBuilder {
    fn platform_name(&self) -> &str {
        "windows"
    }

    fn default_architectures(&self) -> Vec<String> {
        vec!["x86_64".to_string()]
    }

    fn validate_prerequisites(&self, ctx: &BuildContext) -> Result<()> {
        // Check for CMake
        if !crate::build::cmake::is_cmake_available() {
            bail!("CMake is required for Windows builds. Please install CMake.");
        }

        // Check for a Windows toolchain
        let toolchain = Self::detect_toolchain()?;

        match toolchain {
            WindowsToolchain::MinGW => {
                let mingw = MingwToolchain::detect()?;
                mingw.validate()?;

                if ctx.options.verbose {
                    eprintln!(
                        "Using MinGW-w64 {} at {}",
                        mingw.version(),
                        mingw.path().unwrap().display()
                    );
                }
            }
            WindowsToolchain::MSVC => {
                let msvc = MsvcToolchain::detect()?;
                msvc.validate()?;

                if ctx.options.verbose {
                    eprintln!(
                        "Using MSVC {} at {}",
                        msvc.version(),
                        msvc.path().unwrap().display()
                    );
                }
            }
        }

        Ok(())
    }

    fn build(&self, ctx: &BuildContext) -> Result<BuildResult> {
        // Check for IDE project generation mode
        if ctx.options.ide_project {
            return self.generate_ide_project(ctx);
        }

        let start = Instant::now();

        // Validate prerequisites first
        self.validate_prerequisites(ctx)?;

        let toolchain = Self::detect_toolchain()?;

        if ctx.options.verbose {
            eprintln!("Building {} for Windows...", ctx.lib_name());
        }

        // Create output directory
        std::fs::create_dir_all(&ctx.output_dir)?;

        // Create archive builder
        let archive = ArchiveBuilder::new(
            ctx.lib_name(),
            ctx.version(),
            ctx.publish_suffix(),
            ctx.options.release,
            "windows",
            ctx.output_dir.clone(),
        )?;

        let mut built_link_types = Vec::new();

        // Build static libraries
        if matches!(ctx.options.link_type, LinkType::Static | LinkType::Both) {
            let build_dir = self.build_link_type(ctx, "static", toolchain)?;
            self.add_libraries_to_archive(&archive, &build_dir, "static", false, toolchain)?;
            built_link_types.push("static");
        }

        // Build shared libraries
        if matches!(ctx.options.link_type, LinkType::Shared | LinkType::Both) {
            let build_dir = self.build_link_type(ctx, "shared", toolchain)?;

            // Strip shared libraries for release builds (MinGW only)
            if ctx.options.release && toolchain == WindowsToolchain::MinGW {
                if ctx.options.verbose {
                    eprintln!("Stripping shared libraries...");
                }
                let mingw = MingwToolchain::detect()?;
                self.strip_libraries(&mingw, &build_dir, ctx.options.verbose)?;
            }

            self.add_libraries_to_archive(&archive, &build_dir, "shared", true, toolchain)?;
            built_link_types.push("shared");
        }

        // Add include files from project's include directory (matching pyccgo behavior)
        let include_source = ctx.include_source_dir();
        if include_source.exists() {
            let include_path = get_unified_include_path(ctx.lib_name(), &include_source);
            archive.add_directory(&include_source, &include_path)?;
            if ctx.options.verbose {
                eprintln!("Added include files from {} to {}", include_source.display(), include_path);
            }
        }

        // Create the SDK archive
        let architectures = vec!["x86_64".to_string()];
        let link_type_str = ctx.options.link_type.to_string();
        let sdk_archive = archive.create_sdk_archive(&architectures, &link_type_str)?;

        let duration = start.elapsed();

        if ctx.options.verbose {
            eprintln!(
                "Windows build completed in {:.2}s: {}",
                duration.as_secs_f64(),
                sdk_archive.display()
            );
        }

        Ok(BuildResult {
            sdk_archive,
            symbols_archive: None,
            aar_archive: None,
            duration_secs: duration.as_secs_f64(),
            architectures,
        })
    }

    fn clean(&self, ctx: &BuildContext) -> Result<()> {
        // Clean new directory structure: cmake_build/{release|debug}/windows
        for subdir in &["release", "debug"] {
            let build_dir = ctx.project_root.join("cmake_build").join(subdir).join("windows");
            if build_dir.exists() {
                std::fs::remove_dir_all(&build_dir)
                    .with_context(|| format!("Failed to clean {}", build_dir.display()))?;
            }
        }

        // Clean old structure for backwards compatibility: cmake_build/Windows, cmake_build/windows
        for old_dir in &[
            ctx.project_root.join("cmake_build/Windows"),
            ctx.project_root.join("cmake_build/windows"),
        ] {
            if old_dir.exists() {
                std::fs::remove_dir_all(old_dir)
                    .with_context(|| format!("Failed to clean {}", old_dir.display()))?;
            }
        }

        // Clean target directories
        for old_dir in &[
            ctx.project_root.join("target/release/windows"),
            ctx.project_root.join("target/debug/windows"),
            ctx.project_root.join("target/release/Windows"),
            ctx.project_root.join("target/debug/Windows"),
            ctx.project_root.join("target/windows"),
            ctx.project_root.join("target/Windows"),
        ] {
            if old_dir.exists() {
                std::fs::remove_dir_all(old_dir)
                    .with_context(|| format!("Failed to clean {}", old_dir.display()))?;
            }
        }

        Ok(())
    }
}

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