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
//! Build command implementation

use std::path::Path;

use anyhow::{bail, Result};
use clap::{Args, ValueEnum};

use crate::build::analytics::{
    get_cache_stats, count_files, get_artifact_size, BuildAnalytics, CacheStats, FileStats,
};
use crate::build::archive::{create_build_info_full, print_build_info_json};
use crate::build::platforms::{build_all, build_apple, get_builder};
use crate::build::{BuildContext, BuildOptions, BuildResult};
use crate::config::CcgoConfig;
use crate::workspace::{find_workspace_root, Workspace};

/// Target platform for building
#[derive(Debug, Clone, PartialEq, Eq, Hash, ValueEnum)]
pub enum BuildTarget {
    /// Build for all platforms
    All,
    /// Build for all Apple platforms
    Apple,
    /// Android platform
    Android,
    /// iOS platform
    Ios,
    /// macOS platform
    Macos,
    /// Windows platform
    Windows,
    /// Linux platform
    Linux,
    /// OpenHarmony platform
    Ohos,
    /// tvOS platform
    Tvos,
    /// watchOS platform
    Watchos,
    /// Kotlin Multiplatform
    Kmp,
    /// Conan package
    Conan,
}

impl std::fmt::Display for BuildTarget {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            BuildTarget::All => write!(f, "all"),
            BuildTarget::Apple => write!(f, "apple"),
            BuildTarget::Android => write!(f, "Android"),  // Capital A to match Python pyccgo
            BuildTarget::Ios => write!(f, "ios"),
            BuildTarget::Macos => write!(f, "macos"),
            BuildTarget::Windows => write!(f, "windows"),
            BuildTarget::Linux => write!(f, "linux"),
            BuildTarget::Ohos => write!(f, "ohos"),
            BuildTarget::Tvos => write!(f, "tvos"),
            BuildTarget::Watchos => write!(f, "watchos"),
            BuildTarget::Kmp => write!(f, "kmp"),
            BuildTarget::Conan => write!(f, "conan"),
        }
    }
}

/// Library linking type
#[derive(Debug, Clone, Default, ValueEnum, PartialEq)]
pub enum LinkType {
    /// Static library only
    Static,
    /// Shared/dynamic library only
    Shared,
    /// Both static and shared
    #[default]
    Both,
}

impl std::fmt::Display for LinkType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            LinkType::Static => write!(f, "static"),
            LinkType::Shared => write!(f, "shared"),
            LinkType::Both => write!(f, "both"),
        }
    }
}

/// Windows toolchain selection
#[derive(Debug, Clone, Default, ValueEnum)]
pub enum WindowsToolchain {
    /// MSVC toolchain
    Msvc,
    /// MinGW toolchain
    Mingw,
    /// Auto-detect (both)
    #[default]
    Auto,
}

impl std::fmt::Display for WindowsToolchain {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            WindowsToolchain::Msvc => write!(f, "msvc"),
            WindowsToolchain::Mingw => write!(f, "mingw"),
            WindowsToolchain::Auto => write!(f, "auto"),
        }
    }
}

/// Build library for specific platform
#[derive(Args, Debug)]
pub struct BuildCommand {
    /// Target platform to build
    #[arg(value_enum)]
    pub target: BuildTarget,

    /// Architectures to build (comma-separated)
    #[arg(long)]
    pub arch: Option<String>,

    /// Link type
    #[arg(long, value_enum, default_value_t = LinkType::Both)]
    pub link_type: LinkType,

    /// Build all workspace members
    #[arg(long)]
    pub workspace: bool,

    /// Build only the specified package (in a workspace)
    #[arg(long, short = 'p')]
    pub package: Option<String>,

    /// Build using Docker container
    #[arg(long)]
    pub docker: bool,

    /// Automatically use Docker when native build is not possible
    ///
    /// For example, on macOS building for Linux or Windows requires Docker.
    /// This flag will automatically detect and use Docker when needed.
    #[arg(long)]
    pub auto_docker: bool,

    /// Number of parallel jobs
    #[arg(short, long)]
    pub jobs: Option<usize>,

    /// Generate IDE project files
    #[arg(long)]
    pub ide_project: bool,

    /// Build in release mode
    #[arg(long)]
    pub release: bool,

    /// Build only native libraries without packaging (AAR/HAR)
    #[arg(long)]
    pub native_only: bool,

    /// Windows toolchain selection
    #[arg(long, value_enum, default_value_t = WindowsToolchain::Auto)]
    pub toolchain: WindowsToolchain,

    /// Development mode: use pre-built ccgo binary from GitHub releases in Docker builds
    #[arg(long)]
    pub dev: bool,

    /// Features to enable (comma-separated)
    ///
    /// Example: --features networking,advanced
    #[arg(long, short = 'F', value_delimiter = ',')]
    pub features: Vec<String>,

    /// Do not enable default features
    ///
    /// By default, the features listed in [features].default are enabled.
    /// Use this flag to disable them.
    #[arg(long)]
    pub no_default_features: bool,

    /// Enable all available features
    #[arg(long)]
    pub all_features: bool,

    /// Compiler cache to use (ccache, sccache, auto, none)
    ///
    /// Default: auto - automatically detect and use available cache
    /// Use 'none' to disable caching
    #[arg(long, default_value = "auto")]
    pub cache: String,

    /// Show build analytics summary after build
    ///
    /// Displays timing breakdown, cache statistics, and file metrics.
    /// Analytics data is saved to ~/.ccgo/analytics/ for historical tracking.
    #[arg(long)]
    pub analytics: bool,
}

impl BuildCommand {
    /// Check if a platform can be built natively on the current host
    fn can_build_natively(target: &BuildTarget) -> bool {
        let host_os = std::env::consts::OS;

        match target {
            // All/Apple/Kmp/Conan are meta-targets, check individual platforms
            BuildTarget::All | BuildTarget::Apple | BuildTarget::Kmp | BuildTarget::Conan => true,

            // Linux can only be built natively on Linux
            BuildTarget::Linux => host_os == "linux",

            // Windows can only be built natively on Windows
            BuildTarget::Windows => host_os == "windows",

            // Apple platforms can only be built on macOS (Xcode required)
            BuildTarget::Macos | BuildTarget::Ios | BuildTarget::Tvos | BuildTarget::Watchos => {
                host_os == "macos"
            }

            // Android can be built on any platform with NDK
            BuildTarget::Android => true,

            // OHOS can be built on any platform with OHOS SDK
            BuildTarget::Ohos => true,
        }
    }

    /// Determine if Docker should be used for this build
    fn should_use_docker(&self, target: &BuildTarget) -> bool {
        // Explicit --docker flag always uses Docker
        if self.docker {
            return true;
        }

        // --auto-docker enables automatic Docker detection
        if self.auto_docker && !Self::can_build_natively(target) {
            return true;
        }

        false
    }

    /// Execute the build command
    pub fn execute(self, verbose: bool) -> Result<()> {
        let current_dir = std::env::current_dir()?;

        // Check for workspace context
        if self.workspace || self.package.is_some() {
            return self.execute_workspace_build(&current_dir, verbose);
        }

        // Check if we're in a workspace root but --workspace not specified
        if Workspace::is_workspace(&current_dir) {
            eprintln!(
                "ℹ️  In workspace root. Use --workspace to build all members, \
                 or --package <name> to build a specific member."
            );
        }

        // Load project configuration
        let config = CcgoConfig::load()?;

        // Get project root (where CCGO.toml is located)
        let project_root = current_dir;

        // Get package info (required for builds)
        let package = config.require_package()?;

        if verbose {
            eprintln!(
                "Building {} for {} platform...",
                package.name, self.target
            );
        }

        // Check if we should use Docker (explicit or auto-detected)
        let use_docker = self.should_use_docker(&self.target);

        // If auto-docker detected Docker is needed, inform the user
        if self.auto_docker && use_docker && !self.docker {
            let host_os = std::env::consts::OS;
            eprintln!(
                "🐳 Auto-docker: {} cannot be built natively on {} - using Docker",
                self.target, host_os
            );
        }

        // Parse architectures from comma-separated string
        let architectures = self
            .arch
            .clone()
            .map(|s| s.split(',').map(|a| a.trim().to_string()).collect())
            .unwrap_or_default();

        // Create build options
        let options = BuildOptions {
            target: self.target.clone(),
            architectures,
            link_type: self.link_type.clone(),
            use_docker,
            auto_docker: self.auto_docker,
            jobs: self.jobs,
            ide_project: self.ide_project,
            release: self.release,
            native_only: self.native_only,
            toolchain: self.toolchain.clone(),
            verbose,
            dev: self.dev,
            features: self.features.clone(),
            use_default_features: !self.no_default_features,
            all_features: self.all_features,
            cache: Some(self.cache.clone()),
            analytics: self.analytics,
        };

        // Create build context
        let ctx = BuildContext::new(project_root, config.clone(), options);

        // Check if Docker build is requested (explicit or auto-detected)
        if use_docker {
            use crate::build::docker::DockerBuilder;

            // Docker builds only support specific platforms
            match self.target {
                BuildTarget::All | BuildTarget::Apple | BuildTarget::Kmp | BuildTarget::Conan => {
                    if self.auto_docker {
                        // For auto-docker with multi-platform targets, we should fall through
                        // to native build which will handle Docker per-platform
                        eprintln!(
                            "ℹ Auto-docker with '{}' will build each platform with Docker as needed",
                            self.target
                        );
                    } else {
                        bail!(
                            "Docker builds are not supported for '{}' target.\n\n\
                             Docker builds support: linux, windows, macos, ios, tvos, watchos, android\n\
                             Build these platforms individually with --docker flag.\n\
                             Or use --auto-docker to automatically use Docker when needed.",
                            self.target
                        );
                    }
                }
                _ => {
                    // Save context info before ctx is moved
                    let docker_project_root = ctx.project_root.clone();
                    let cache_tool = ctx.compiler_cache().map(|c| c.tool_name().to_string());
                    let jobs = ctx.jobs();
                    let analytics = self.analytics;

                    // Create Docker builder and execute
                    let docker_builder = DockerBuilder::new(ctx)?;
                    let result = docker_builder.execute()?;

                    // Print results summary (same as non-Docker builds)
                    Self::print_results(
                        &package.name,
                        &package.version,
                        &self.target.to_string(),
                        &docker_project_root,
                        &[result],
                        verbose,
                        analytics,
                        cache_tool.as_deref(),
                        jobs,
                    );
                    return Ok(());
                }
            }
        }

        // Check CCGO_CMAKE_DIR availability
        if let Some(cmake_dir) = ctx.ccgo_cmake_dir() {
            if verbose {
                eprintln!("Using CCGO cmake directory: {}", cmake_dir.display());
            }
        } else {
            eprintln!(
                "Warning: CCGO cmake directory not found. Set CCGO_CMAKE_DIR environment variable \
                 or install the ccgo package."
            );
        }

        // Get cache info before build for analytics
        let cache_tool = ctx.compiler_cache().map(|c| c.tool_name().to_string());
        let jobs = ctx.jobs();

        // Execute the build based on target
        let results = match self.target {
            BuildTarget::All => build_all(&ctx)?,
            BuildTarget::Apple => build_apple(&ctx)?,
            _ => {
                // Single platform build
                let builder = get_builder(&self.target)?;
                vec![builder.build(&ctx)?]
            }
        };

        // Print results summary
        Self::print_results(
            &package.name,
            &package.version,
            &self.target.to_string(),
            &ctx.project_root,
            &results,
            verbose,
            self.analytics,
            cache_tool.as_deref(),
            jobs,
        );

        Ok(())
    }

    /// Execute build for workspace members
    fn execute_workspace_build(&self, current_dir: &Path, verbose: bool) -> Result<()> {
        // Find workspace root
        let workspace_root = find_workspace_root(current_dir)?
            .ok_or_else(|| anyhow::anyhow!(
                "Not in a workspace. Use --workspace or --package only within a workspace."
            ))?;

        // Load workspace
        let workspace = Workspace::load(&workspace_root)?;

        if verbose {
            workspace.print_summary();
        }

        // Determine which members to build
        let members_to_build = if let Some(ref package_name) = self.package {
            // Build specific package
            let member = workspace.get_member(package_name)
                .ok_or_else(|| anyhow::anyhow!(
                    "Package '{}' not found in workspace. Available: {}",
                    package_name,
                    workspace.members.names().join(", ")
                ))?;
            vec![member]
        } else {
            // Build default members (or all if no default_members specified)
            workspace.default_members()
        };

        if members_to_build.is_empty() {
            bail!("No workspace members to build");
        }

        eprintln!("\n{}", "=".repeat(80));
        eprintln!("CCGO Workspace Build - Building {} member(s)", members_to_build.len());
        eprintln!("{}", "=".repeat(80));

        let mut all_results: Vec<(String, Vec<BuildResult>)> = Vec::new();
        let mut failed_members: Vec<String> = Vec::new();

        for member in members_to_build {
            eprintln!("\n📦 Building {} ({})...", member.name, member.version);
            eprintln!("{}", "-".repeat(60));

            // Execute build in member's directory
            match self.build_member(&workspace_root, member, verbose) {
                Ok(results) => {
                    all_results.push((member.name.clone(), results));
                }
                Err(e) => {
                    eprintln!("   ✗ Failed to build {}: {}", member.name, e);
                    failed_members.push(member.name.clone());
                }
            }
        }

        // Print summary
        eprintln!("\n{}", "=".repeat(80));
        eprintln!("Workspace Build Summary");
        eprintln!("{}", "=".repeat(80));

        let success_count = all_results.len();
        let fail_count = failed_members.len();

        eprintln!("\n✓ Successfully built: {}", success_count);
        for (name, results) in &all_results {
            let total_duration: f64 = results.iter().map(|r| r.duration_secs).sum();
            eprintln!("  - {} ({:.2}s)", name, total_duration);
        }

        if !failed_members.is_empty() {
            eprintln!("\n✗ Failed: {}", fail_count);
            for name in &failed_members {
                eprintln!("  - {}", name);
            }
            bail!("{} workspace member(s) failed to build", fail_count);
        }

        Ok(())
    }

    /// Build a single workspace member
    fn build_member(
        &self,
        workspace_root: &Path,
        member: &crate::workspace::WorkspaceMember,
        verbose: bool,
    ) -> Result<Vec<BuildResult>> {
        // Construct member's directory path
        let member_path = workspace_root.join(&member.name);

        // Load member's configuration
        let config_path = member_path.join("CCGO.toml");
        let config = CcgoConfig::load_from(&config_path)?;

        // Get package info
        let package = config.require_package()?;

        // Parse architectures
        let architectures = self.arch.clone()
            .map(|s| s.split(',').map(|a| a.trim().to_string()).collect())
            .unwrap_or_default();

        // Check if we should use Docker
        let use_docker = self.should_use_docker(&self.target);

        // Create build options
        let options = BuildOptions {
            target: self.target.clone(),
            architectures,
            link_type: self.link_type.clone(),
            use_docker,
            auto_docker: self.auto_docker,
            jobs: self.jobs,
            ide_project: self.ide_project,
            release: self.release,
            native_only: self.native_only,
            toolchain: self.toolchain.clone(),
            verbose,
            dev: self.dev,
            features: self.features.clone(),
            use_default_features: !self.no_default_features,
            all_features: self.all_features,
            cache: Some(self.cache.clone()),
            analytics: self.analytics,
        };

        // Create build context with member's path
        let ctx = BuildContext::new(member_path.clone(), config.clone(), options);

        // Get cache info for analytics
        let cache_tool = ctx.compiler_cache().map(|c| c.tool_name().to_string());
        let jobs = ctx.jobs();

        // Execute the build
        let results = if use_docker {
            use crate::build::docker::DockerBuilder;

            match self.target {
                BuildTarget::All | BuildTarget::Apple | BuildTarget::Kmp | BuildTarget::Conan => {
                    // Fall through to native build for meta-targets
                    match self.target {
                        BuildTarget::All => build_all(&ctx)?,
                        BuildTarget::Apple => build_apple(&ctx)?,
                        _ => {
                            let builder = get_builder(&self.target)?;
                            vec![builder.build(&ctx)?]
                        }
                    }
                }
                _ => {
                    let docker_builder = DockerBuilder::new(ctx)?;
                    vec![docker_builder.execute()?]
                }
            }
        } else {
            match self.target {
                BuildTarget::All => build_all(&ctx)?,
                BuildTarget::Apple => build_apple(&ctx)?,
                _ => {
                    let builder = get_builder(&self.target)?;
                    vec![builder.build(&ctx)?]
                }
            }
        };

        // Print results for this member
        Self::print_results(
            &package.name,
            &package.version,
            &self.target.to_string(),
            &member_path,
            &results,
            verbose,
            self.analytics,
            cache_tool.as_deref(),
            jobs,
        );

        Ok(results)
    }

    /// Print build results summary
    fn print_results(
        lib_name: &str,
        version: &str,
        platform: &str,
        project_root: &Path,
        results: &[BuildResult],
        verbose: bool,
        show_analytics: bool,
        cache_tool: Option<&str>,
        jobs: usize,
    ) {
        let total_duration: f64 = results.iter().map(|r| r.duration_secs).sum();

        if results.is_empty() {
            eprintln!("No builds completed.");
            return;
        }

        if verbose {
            eprintln!("\n=== Build Summary ===");
            for result in results {
                eprintln!(
                    "  {} ({:.2}s): {}",
                    result.architectures.join(", "),
                    result.duration_secs,
                    result.sdk_archive.display()
                );
            }
        }

        // Print build info JSON before success message
        let build_info = create_build_info_full(lib_name, version, platform, project_root);
        print_build_info_json(&build_info);

        eprintln!(
            "\n{} built successfully in {:.2}s",
            lib_name, total_duration
        );

        // Print archive locations and contents
        for result in results {
            // Check if this is an IDE project (directory) vs regular archive (zip file)
            let is_ide_project = result.sdk_archive.is_dir();

            if is_ide_project {
                // IDE project - just show the directory path
                eprintln!("  IDE Project: {}", result.sdk_archive.display());
            } else {
                // Regular build - show archive paths and contents
                eprintln!("  SDK: {}", result.sdk_archive.display());
                if let Some(symbols) = &result.symbols_archive {
                    eprintln!("  Symbols: {}", symbols.display());
                }
                if let Some(aar) = &result.aar_archive {
                    eprintln!("  AAR: {}", aar.display());
                }

                // Print archive tree structure
                if let Err(e) = crate::build::archive::print_zip_tree(&result.sdk_archive, "      ") {
                    eprintln!("      Warning: Failed to print archive contents: {}", e);
                }

                // Print symbols archive tree if present
                if let Some(symbols_path) = &result.symbols_archive {
                    eprintln!("\n      Symbols archive:");
                    if let Err(e) = crate::build::archive::print_zip_tree(symbols_path, "      ") {
                        eprintln!("      Warning: Failed to print symbols archive contents: {}", e);
                    }
                }

                // Print AAR/HAR archive tree if present (Android/OHOS)
                if let Some(archive_path) = &result.aar_archive {
                    // Detect archive type from extension
                    let archive_type = if archive_path.extension().map_or(false, |e| e == "har") {
                        "HAR"
                    } else {
                        "AAR"
                    };
                    eprintln!("\n      {} contents:", archive_type);
                    if let Err(e) = crate::build::archive::print_zip_tree(archive_path, "      ") {
                        eprintln!("      Warning: Failed to print {} contents: {}", archive_type, e);
                    }
                }
            }
        }

        // Show analytics summary if requested
        if show_analytics {
            Self::collect_and_display_analytics(
                lib_name,
                platform,
                project_root,
                results,
                cache_tool,
                jobs,
            );
        }
    }

    /// Collect and display build analytics
    fn collect_and_display_analytics(
        lib_name: &str,
        platform: &str,
        project_root: &Path,
        results: &[BuildResult],
        cache_tool: Option<&str>,
        jobs: usize,
    ) {
        let total_duration: f64 = results.iter().map(|r| r.duration_secs).sum();
        let _all_archs: Vec<String> = results
            .iter()
            .flat_map(|r| r.architectures.clone())
            .collect();

        // Collect file statistics
        let src_dir = project_root.join("src");
        let (source_files, header_files) = count_files(&src_dir).unwrap_or((0, 0));

        // Get artifact size (use first result's SDK archive)
        let artifact_size = results
            .first()
            .map(|r| get_artifact_size(&r.sdk_archive).unwrap_or(0))
            .unwrap_or(0);

        let file_stats = FileStats {
            source_files,
            header_files,
            total_lines: 0, // Would need to count lines
            artifact_size_bytes: artifact_size,
        };

        // Get cache statistics
        let cache_stats = cache_tool
            .and_then(|tool| get_cache_stats(Some(tool)))
            .unwrap_or(CacheStats {
                tool: cache_tool.map(|s| s.to_string()),
                hits: 0,
                misses: 0,
                hit_rate: 0.0,
            });

        // Create analytics record
        let analytics = BuildAnalytics {
            project: lib_name.to_string(),
            platform: platform.to_string(),
            timestamp: chrono::Local::now().to_rfc3339(),
            total_duration_secs: total_duration,
            phases: Vec::new(), // Phase timing would require deeper integration
            cache_stats,
            file_stats,
            parallel_jobs: jobs,
            peak_memory_mb: None,
            success: true,
            error_count: 0,
            warning_count: 0,
        };

        // Save analytics to history
        if let Err(e) = analytics.save() {
            eprintln!("\n⚠️  Failed to save build analytics: {}", e);
        }

        // Display analytics summary
        analytics.print_summary();

        // Show historical comparison if available
        if let Ok(Some(avg)) = BuildAnalytics::average_build_time(lib_name) {
            let diff = total_duration - avg;
            let pct = (diff / avg) * 100.0;
            if diff.abs() > 0.5 {
                if diff > 0.0 {
                    eprintln!(
                        "📊 This build was {:.1}s ({:.1}%) slower than average ({:.2}s)",
                        diff, pct, avg
                    );
                } else {
                    eprintln!(
                        "📊 This build was {:.1}s ({:.1}%) faster than average ({:.2}s)",
                        diff.abs(),
                        pct.abs(),
                        avg
                    );
                }
            }
        }
    }
}