ccgo 3.4.2

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
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
//! Package command implementation

use anyhow::{anyhow, Context, Result};
use chrono::Local;
use clap::Args;
use console::style;
use serde::Serialize;
use std::collections::HashSet;
use std::fs;
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::process::Command;
use walkdir::WalkDir;
use zip::{write::FileOptions, ZipArchive, ZipWriter};

/// Archive metadata
#[derive(Debug, Serialize)]
struct ArchiveInfo {
    project_name: String,
    version: String,
    platforms: Vec<String>,
    merged: bool,
    created_at: String,
}

/// Find CCGO.toml in project directory or subdirectories
fn find_ccgo_toml(start_dir: &Path) -> Result<PathBuf> {
    // First check current directory
    let config_file = start_dir.join("CCGO.toml");
    if config_file.is_file() {
        return Ok(config_file);
    }

    // Then check immediate subdirectories
    if let Ok(entries) = fs::read_dir(start_dir) {
        for entry in entries.flatten() {
            if !entry.path().is_dir() {
                continue;
            }
            let config_file = entry.path().join("CCGO.toml");
            if config_file.is_file() {
                return Ok(config_file);
            }
        }
    }

    Err(anyhow!(
        "CCGO.toml not found!\n\n\
         Current directory: {}\n\n\
         The 'ccgo package' command must be run from a CCGO project directory\n\
         (a directory containing CCGO.toml or with a subdirectory containing it).\n\n\
         Please navigate to your project directory and try again:\n\
         $ cd /path/to/your-project\n\
         $ ccgo package",
        start_dir.display()
    ))
}

/// Get project name from CCGO.toml
fn get_project_name(config_file: &Path) -> Result<String> {
    let content = fs::read_to_string(config_file)
        .context("Failed to read CCGO.toml")?;
    let config: crate::config::CcgoConfig = toml::from_str(&content)
        .context("Failed to parse CCGO.toml")?;
    let pkg = config.package.context("CCGO.toml must have a [package] section")?;
    Ok(pkg.name)
}

/// Get version from args, git, or CCGO.toml
fn get_version(config_file: &Path, version_arg: Option<&str>, release: bool) -> String {
    // Use provided version argument
    if let Some(version) = version_arg {
        return version.to_string();
    }

    // Try git tag with full version info (--long --dirty for beta and dirty status)
    let project_dir = config_file.parent().unwrap();
    if let Ok(output) = Command::new("git")
        .args(["describe", "--tags", "--always", "--long", "--dirty"])
        .current_dir(project_dir)
        .output()
    {
        if output.status.success() {
            if let Ok(git_version) = String::from_utf8(output.stdout) {
                let git_version = git_version.trim();
                if !git_version.is_empty() {
                    // Parse git describe output: v1.0.2-18-g<hash>-dirty
                    // Format: <tag>-<commits>-g<hash>[-dirty]
                    return format_version_from_git(git_version, release);
                }
            }
        }
    }

    // Try CCGO.toml
    if let Ok(content) = fs::read_to_string(config_file) {
        if let Ok(config) = toml::from_str::<crate::config::CcgoConfig>(&content) {
            if let Some(pkg) = config.package {
                return pkg.version;
            }
        }
    }

    // Default to date
    Local::now().format("%Y%m%d").to_string()
}

/// Format version from git describe output
/// Input: v1.0.2-18-g<hash>-dirty or v1.0.2-0-g<hash>
/// Output (debug): 1.0.2-beta.18-dirty or 1.0.2 (if on exact tag)
/// Output (release): 1.0.2-release
fn format_version_from_git(git_version: &str, release: bool) -> String {
    let mut parts: Vec<&str> = git_version.split('-').collect();
    let is_dirty = parts.last() == Some(&"dirty");
    if is_dirty {
        parts.pop(); // Remove "dirty"
    }

    // Extract base version (strip 'v' prefix)
    let base_version = parts[0].strip_prefix('v').unwrap_or(parts[0]);

    // For release builds, always use -release suffix
    if release {
        return format!("{}-release", base_version);
    }

    // For debug builds, extract commit count
    if parts.len() >= 3 {
        // parts: ["v1.0.2", "18", "g<hash>"]
        let commits = parts[1];

        // If commits is 0, we're exactly on a tag
        if commits == "0" {
            if is_dirty {
                format!("{}-dirty", base_version)
            } else {
                base_version.to_string()
            }
        } else {
            // Not on exact tag, use beta.N format
            if is_dirty {
                format!("{}-beta.{}-dirty", base_version, commits)
            } else {
                format!("{}-beta.{}", base_version, commits)
            }
        }
    } else {
        // Fallback: just return base version
        if is_dirty {
            format!("{}-dirty", base_version)
        } else {
            base_version.to_string()
        }
    }
}

/// Find all ZIP files for a platform in target/debug/<platform>/ or target/release/<platform>/
fn find_platform_zips(project_dir: &Path, platform: &str, release: bool) -> Vec<PathBuf> {
    let target_dir = project_dir.join("target");
    if !target_dir.exists() {
        return Vec::new();
    }

    let mut zip_files = Vec::new();
    let platform_upper = platform.to_uppercase();

    // Determine build type based on release flag (matching ccgo build behavior)
    let build_type = if release { "release" } else { "debug" };

    // Search in target/<build_type>/<platform>
    let platform_dir = target_dir.join(build_type).join(platform);
    if platform_dir.exists() {
        for entry in WalkDir::new(&platform_dir)
            .into_iter()
            .filter_map(|e| e.ok())
        {
            let path = entry.path();
            if path.is_file() {
                if let Some(filename) = path.file_name() {
                    let filename_str = filename.to_string_lossy();
                    // Match ZIP files for this platform (e.g., CCGONOW_ANDROID_SDK-*.zip)
                    if filename_str.ends_with(".zip")
                        && !filename_str.starts_with("ARCHIVE")
                        && filename_str.to_uppercase().contains(&platform_upper)
                    {
                        zip_files.push(path.to_path_buf());
                    }
                }
            }
        }
    }

    // Also check legacy target/<platform> (for backward compatibility)
    let legacy_platform_dir = target_dir.join(platform);
    if legacy_platform_dir.exists() {
        for entry in WalkDir::new(&legacy_platform_dir)
            .into_iter()
            .filter_map(|e| e.ok())
        {
            let path = entry.path();
            if path.is_file() {
                if let Some(filename) = path.file_name() {
                    let filename_str = filename.to_string_lossy();
                    if filename_str.ends_with(".zip")
                        && !filename_str.starts_with("ARCHIVE")
                        && filename_str.to_uppercase().contains(&platform_upper)
                    {
                        zip_files.push(path.to_path_buf());
                    }
                }
            }
        }
    }

    zip_files
}

/// Generate a minimal CCGO.toml string to embed at the ZIP root.
/// Contains [package] metadata and only zip-sourced [[dependencies]].
fn generate_embedded_ccgo_toml(config_file: &Path) -> Result<String> {
    let content = fs::read_to_string(config_file)
        .context("Failed to read CCGO.toml")?;

    // Use the full config parser to access dependencies
    let config: crate::config::CcgoConfig = toml::from_str(&content)
        .context("Failed to parse CCGO.toml")?;

    let pkg = config.package.as_ref()
        .context("CCGO.toml must have a [package] section")?;

    let mut out = format!(
        "[package]\nname = \"{}\"\nversion = \"{}\"\n",
        pkg.name,
        pkg.version
    );

    if let Some(ref desc) = pkg.description {
        out.push_str(&format!("description = \"{}\"\n", desc));
    }

    // Only embed zip-sourced transitive deps (skip git/path deps)
    for dep in &config.dependencies {
        if let Some(ref zip) = dep.zip {
            out.push_str(&format!(
                "\n[[dependencies]]\nname = \"{}\"\nversion = \"{}\"\nzip = \"{}\"\n",
                dep.name, dep.version, zip
            ));
        }
    }

    Ok(out)
}

/// Merge multiple ZIP files into a single unified SDK ZIP
fn merge_zips(
    zip_files: &[PathBuf],
    output_zip_path: &Path,
    project_name: &str,
    version: &str,
    config_file: &Path,
) -> Result<()> {
    println!("\n{}", "=".repeat(80));
    println!("Merging ZIP files into unified SDK");
    println!("{}", "=".repeat(80));

    // Create temporary directory for extraction
    let temp_dir = tempfile::tempdir()?;
    let merged_dir = temp_dir.path().join("merged");
    fs::create_dir_all(&merged_dir)?;

    let mut platforms_merged = HashSet::new();

    for zip_path in zip_files {
        let filename = zip_path.file_name().unwrap().to_string_lossy();
        println!("   📦 Processing: {}", filename);

        let file = fs::File::open(zip_path)?;
        let mut archive = ZipArchive::new(file)?;

        for i in 0..archive.len() {
            let mut file = archive.by_index(i)?;
            let outpath = merged_dir.join(file.name());

            if file.name().ends_with('/') {
                fs::create_dir_all(&outpath)?;
            } else {
                if let Some(p) = outpath.parent() {
                    fs::create_dir_all(p)?;
                }

                // Skip if file already exists (don't overwrite)
                if !outpath.exists() {
                    let mut outfile = fs::File::create(&outpath)?;
                    std::io::copy(&mut file, &mut outfile)?;
                }
            }
        }

        // Detect platform from filename
        let fname_lower = filename.to_lowercase();
        for plat in &[
            "android", "ios", "macos", "watchos", "tvos", "windows", "linux", "ohos", "kmp",
            "conan", "include",
        ] {
            if fname_lower.contains(plat) {
                platforms_merged.insert(plat.to_string());
                break;
            }
        }
    }

    // Create unified archive_info.json
    let platforms: Vec<String> = platforms_merged.into_iter().collect();
    let archive_info = ArchiveInfo {
        project_name: project_name.to_string(),
        version: version.to_string(),
        platforms,
        merged: true,
        created_at: Local::now().to_rfc3339(),
    };

    let meta_dir = merged_dir.join("meta");
    fs::create_dir_all(&meta_dir)?;
    let archive_info_path = meta_dir.join("archive_info.json");
    let archive_info_json = serde_json::to_string_pretty(&archive_info)?;
    fs::write(archive_info_path, archive_info_json)?;

    // Create the merged ZIP
    println!("\n   📦 Creating merged SDK ZIP...");

    let file = fs::File::create(output_zip_path)?;
    let mut zip = ZipWriter::new(file);
    let options: FileOptions<()> = FileOptions::default()
        .compression_method(zip::CompressionMethod::Deflated)
        .unix_permissions(0o755);

    for entry in WalkDir::new(&merged_dir) {
        let entry = entry?;
        let path = entry.path();
        let name = path.strip_prefix(&merged_dir)?;

        if path.is_file() {
            zip.start_file(name.to_string_lossy().to_string(), options)?;
            let mut f = fs::File::open(path)?;
            let mut buffer = Vec::new();
            f.read_to_end(&mut buffer)?;
            zip.write_all(&buffer)?;
        }
    }

    // Embed CCGO.toml at ZIP root for use as prebuilt dep
    match generate_embedded_ccgo_toml(config_file) {
        Ok(toml_content) => {
            let options = zip::write::SimpleFileOptions::default()
                .compression_method(zip::CompressionMethod::Deflated);
            zip.start_file("CCGO.toml", options)?;
            zip.write_all(toml_content.as_bytes())?;
            println!("   ✓ Embedded CCGO.toml into ZIP root");
        }
        Err(e) => {
            eprintln!("   ⚠️  Could not embed CCGO.toml: {}", e);
        }
    }

    zip.finish()?;

    let size_mb = fs::metadata(output_zip_path)?.len() as f64 / (1024.0 * 1024.0);
    println!(
        "   ✅ Created: {} ({:.2} MB)",
        output_zip_path.file_name().unwrap().to_string_lossy(),
        size_mb
    );
    println!("   📍 Location: {}", output_zip_path.display());

    Ok(())
}

/// Print contents of a ZIP file
fn print_zip_contents(zip_path: &Path, indent: &str) -> Result<()> {
    let file = fs::File::open(zip_path)?;
    let mut archive = ZipArchive::new(file)?;

    for i in 0..archive.len() {
        let file = archive.by_index(i)?;
        if !file.name().ends_with('/') {
            println!("{}├── {}", indent, file.name());
        }
    }

    Ok(())
}

/// Publish packaged artifacts to a git distribution branch using a worktree.
///
/// Steps:
///  1. Check that we are in a git repository.
///  2. Create (or reset) a temporary git worktree for `branch`.
///  3. Copy every file from `package_dir` into the worktree root.
///  4. Commit the changes with a version-stamped message.
///  5. Optionally push the branch to `origin`.
///  6. Remove the worktree.
fn publish_to_dist_branch(
    project_dir: &Path,
    package_dir: &Path,
    branch: &str,
    project_name: &str,
    version: &str,
    push: bool,
) -> Result<()> {
    println!("\n{}", "=".repeat(80));
    println!("Publishing to dist branch: {}", branch);
    println!("{}", "=".repeat(80));

    // Verify we are inside a git repo
    let git_check = Command::new("git")
        .current_dir(project_dir)
        .args(["rev-parse", "--git-dir"])
        .output()
        .context("Failed to run git")?;
    if !git_check.status.success() {
        return Err(anyhow!("Not inside a git repository"));
    }

    // Locate the .git directory so we can place the worktree alongside it
    let git_dir_out = String::from_utf8_lossy(&git_check.stdout).trim().to_string();
    // git_dir_out is relative or absolute; make it absolute
    let git_dir = if Path::new(&git_dir_out).is_absolute() {
        PathBuf::from(&git_dir_out)
    } else {
        project_dir.join(&git_dir_out)
    };
    let repo_root = git_dir.parent().unwrap_or(project_dir);

    let worktree_path = repo_root.join(".ccgo-dist-worktree");

    // Remove stale worktree if it already exists
    if worktree_path.exists() {
        println!("   🧹 Removing stale worktree...");
        let _ = Command::new("git")
            .current_dir(project_dir)
            .args(["worktree", "remove", "--force", worktree_path.to_str().unwrap()])
            .status();
        if worktree_path.exists() {
            fs::remove_dir_all(&worktree_path)?;
        }
    }

    // Check if the branch exists (locally)
    let branch_exists = Command::new("git")
        .current_dir(project_dir)
        .args(["rev-parse", "--verify", branch])
        .status()
        .map(|s| s.success())
        .unwrap_or(false);

    if branch_exists {
        // Checkout existing branch into worktree
        println!("   📂 Checking out existing branch '{}'...", branch);
        let status = Command::new("git")
            .current_dir(project_dir)
            .args(["worktree", "add", worktree_path.to_str().unwrap(), branch])
            .status()
            .context("Failed to create git worktree")?;
        if !status.success() {
            return Err(anyhow!("git worktree add failed"));
        }
    } else {
        // Create orphan branch in worktree (no parent commits)
        println!("   📂 Creating new orphan branch '{}'...", branch);
        let status = Command::new("git")
            .current_dir(project_dir)
            .args(["worktree", "add", "--orphan", "-b", branch, worktree_path.to_str().unwrap()])
            .status()
            .context("Failed to create git worktree with orphan branch")?;
        if !status.success() {
            return Err(anyhow!("git worktree add --orphan failed"));
        }
    }

    // Clear the worktree (keep .git file that links back to main repo)
    println!("   🧹 Clearing worktree...");
    if let Ok(entries) = fs::read_dir(&worktree_path) {
        for entry in entries.flatten() {
            let name = entry.file_name();
            if name == ".git" {
                continue;
            }
            let p = entry.path();
            if p.is_dir() {
                fs::remove_dir_all(&p)?;
            } else {
                fs::remove_file(&p)?;
            }
        }
    }

    // Copy all packaged files into the worktree root
    println!("   📦 Copying artifacts...");
    let mut copied = 0usize;
    for entry in fs::read_dir(package_dir)
        .context("Failed to read package directory")?
        .flatten()
    {
        let src = entry.path();
        let dst = worktree_path.join(entry.file_name());
        fs::copy(&src, &dst)
            .with_context(|| format!("Failed to copy {} to worktree", src.display()))?;
        println!(
            "{}",
            entry.file_name().to_string_lossy()
        );
        copied += 1;
    }

    if copied == 0 {
        // Clean up and bail
        let _ = Command::new("git")
            .current_dir(project_dir)
            .args(["worktree", "remove", "--force", worktree_path.to_str().unwrap()])
            .status();
        return Err(anyhow!("No artifacts found in package directory"));
    }

    // Stage all changes
    Command::new("git")
        .current_dir(&worktree_path)
        .args(["add", "-A"])
        .status()
        .context("Failed to stage dist files")?;

    // Check if there is anything to commit
    let porcelain = Command::new("git")
        .current_dir(&worktree_path)
        .args(["status", "--porcelain"])
        .output()
        .context("Failed to check git status")?;

    if porcelain.stdout.is_empty() {
        println!("   ℹ️  No changes to commit (dist branch is up-to-date)");
    } else {
        let commit_msg = format!("dist: {} v{}", project_name, version);
        println!("   💾 Committing: {}", commit_msg);
        let status = Command::new("git")
            .current_dir(&worktree_path)
            .args(["commit", "-m", &commit_msg])
            .status()
            .context("Failed to commit dist artifacts")?;
        if !status.success() {
            return Err(anyhow!("git commit failed in dist branch"));
        }
    }

    // Remove worktree (branch persists in the repo)
    let _ = Command::new("git")
        .current_dir(project_dir)
        .args(["worktree", "remove", "--force", worktree_path.to_str().unwrap()])
        .status();

    println!(
        "\n   ✅ Artifacts committed to branch '{}'",
        branch
    );

    // Push if requested
    if push {
        println!("   📤 Pushing branch '{}' to origin...", branch);
        let status = Command::new("git")
            .current_dir(project_dir)
            .args(["push", "origin", branch])
            .status()
            .context("Failed to push dist branch")?;
        if !status.success() {
            return Err(anyhow!("git push failed for branch '{}'", branch));
        }
        println!("   ✅ Pushed '{}' to origin", branch);
    } else {
        println!(
            "   💡 Use --dist-push to push '{}' to remote",
            branch
        );
    }

    Ok(())
}

/// Package SDK for distribution
#[derive(Args, Debug)]
#[command(disable_version_flag = true)]
pub struct PackageCommand {
    /// SDK version (default: auto-detect from git or CCGO.toml)
    #[arg(long)]
    pub version: Option<String>,

    /// Output directory for packaged SDK (default: ./target/debug/package or ./target/release/package)
    #[arg(long)]
    pub output: Option<String>,

    /// Comma-separated platforms to include (default: all built platforms)
    #[arg(long)]
    pub platforms: Option<String>,

    /// Keep individual ZIP files instead of merging into one unified SDK ZIP
    #[arg(long)]
    pub no_merge: bool,

    /// Package release builds (default: debug builds)
    #[arg(long)]
    pub release: bool,

    /// Publish packaged artifacts to a git distribution branch (e.g. "dist")
    #[arg(long)]
    pub dist_branch: Option<String>,

    /// Shorthand for --dist-branch dist
    #[arg(long)]
    pub dist: bool,

    /// Push the dist branch to remote after committing
    #[arg(long)]
    pub dist_push: bool,
}

impl PackageCommand {
    /// Execute the package command
    pub fn execute(self, _verbose: bool) -> Result<()> {
        println!("{}", "=".repeat(80));
        println!("CCGO Package - Collect Build Artifacts");
        println!("{}", "=".repeat(80));

        // Get current working directory
        let project_dir = std::env::current_dir()
            .context("Failed to get current working directory")?;

        // Find CCGO.toml
        let config_file = find_ccgo_toml(&project_dir)?;

        // Get project info
        let project_name = get_project_name(&config_file)?;
        let version = get_version(&config_file, self.version.as_deref(), self.release);

        // Determine build mode and default output path
        let build_mode = if self.release { "release" } else { "debug" };
        let default_output = format!("./target/{}/package", build_mode);

        // Convert output path to absolute path
        let output_str = self.output.as_deref().unwrap_or(&default_output);
        let output_path = if Path::new(output_str).is_absolute() {
            PathBuf::from(output_str)
        } else {
            project_dir.join(output_str)
        };

        let merge_mode = !self.no_merge;
        let mode_str = if merge_mode {
            "Merge into unified SDK"
        } else {
            "Keep individual ZIPs"
        };

        println!("\nProject: {}", project_name);
        println!("Version: {}", version);
        println!("Build Mode: {}", build_mode);
        println!("Output: {}", output_path.display());
        println!("Mode: {}", mode_str);

        // Clean output directory
        if output_path.exists() {
            println!("\n🧹 Cleaning output directory...");
            fs::remove_dir_all(&output_path)?;
        }

        // Create output directory
        fs::create_dir_all(&output_path)?;

        println!("\n{}", "=".repeat(80));
        println!("Scanning Build Artifacts");
        println!("{}", "=".repeat(80));

        // Define platforms to scan
        let platforms: Vec<String> = if let Some(platforms_str) = &self.platforms {
            platforms_str.split(',').map(|s| s.trim().to_string()).collect()
        } else {
            vec![
                "android", "ios", "macos", "tvos", "watchos", "windows", "linux", "ohos", "conan",
                "kmp",
            ]
            .into_iter()
            .map(String::from)
            .collect()
        };

        let mut collected_platforms = Vec::new();
        let mut failed_platforms = Vec::new();
        let mut all_zip_files = Vec::new();

        for platform in &platforms {
            let zip_files = find_platform_zips(&project_dir, platform, self.release);
            if !zip_files.is_empty() {
                collected_platforms.push(platform.clone());
                for zf in &zip_files {
                    println!("   ✓ Found: {}", zf.file_name().unwrap().to_string_lossy());
                }
                all_zip_files.extend(zip_files);
            } else {
                failed_platforms.push(platform.clone());
            }
        }

        // Check if any artifacts were found
        if collected_platforms.is_empty() {
            println!("\n{}", "=".repeat(80));
            println!("⚠️  WARNING: No platform artifacts found!");
            println!("{}", "=".repeat(80));
            println!("\nIt looks like no platforms have been built yet in {} mode.", build_mode);
            println!("\nTo build platforms, use:");
            if self.release {
                println!("  ccgo build android --release");
                println!("  ccgo build ios --release");
                println!("  ccgo build all --release");
            } else {
                println!("  ccgo build android");
                println!("  ccgo build ios");
                println!("  ccgo build all");
            }
            println!("\nThen run 'ccgo package{}' again.\n", if self.release { " --release" } else { "" });
            return Err(anyhow!("No platform artifacts found in {} mode", build_mode));
        }

        if merge_mode {
            // Merge all ZIPs into one unified SDK ZIP
            // Strip leading 'v' from version if present (e.g., v1.0.2 -> 1.0.2)
            let version_clean = version.strip_prefix('v').unwrap_or(&version);
            let sdk_zip_name = format!("{}_SDK-{}.zip", project_name.to_uppercase(), version_clean);
            let sdk_zip_path = output_path.join(&sdk_zip_name);

            merge_zips(&all_zip_files, &sdk_zip_path, &project_name, &version, &config_file)?;

            // Print summary
            println!("\n{}", "=".repeat(80));
            println!("Package Summary");
            println!("{}", "=".repeat(80));
            println!("\nPlatforms merged: {}", collected_platforms.join(", "));
            println!("Output: {}", sdk_zip_path.display());

            let size_mb = fs::metadata(&sdk_zip_path)?.len() as f64 / (1024.0 * 1024.0);
            println!("Size: {:.2} MB", size_mb);
        } else {
            // Copy individual ZIPs to output directory
            println!("\n{}", "=".repeat(80));
            println!("Copying Individual ZIP Files");
            println!("{}", "=".repeat(80));

            let mut copied_files = Vec::new();
            for zip_file in &all_zip_files {
                let filename = zip_file.file_name().unwrap();
                let dest_path = output_path.join(filename);
                fs::copy(zip_file, &dest_path)?;
                let size_mb = fs::metadata(&dest_path)?.len() as f64 / (1024.0 * 1024.0);
                println!("{} ({:.2} MB)", filename.to_string_lossy(), size_mb);
                copied_files.push(filename.to_string_lossy().to_string());
            }

            // Print summary
            println!("\n{}", "=".repeat(80));
            println!("Package Summary");
            println!("{}", "=".repeat(80));
            println!("\nOutput Directory: {}", output_path.display());
            println!("\nCopied {} artifact(s):", copied_files.len());
            println!("{}", "-".repeat(60));
            for f in &copied_files {
                let file_path = output_path.join(f);
                let size_mb = fs::metadata(&file_path)?.len() as f64 / (1024.0 * 1024.0);
                println!("  {} ({:.2} MB)", f, size_mb);
            }
            println!("{}", "-".repeat(60));
        }

        // Platform status
        println!("\n{}", "=".repeat(80));
        println!("Platform Status");
        println!("{}", "=".repeat(80));
        println!();

        for platform in &collected_platforms {
            println!("  {} {}", style("").green(), platform.to_uppercase());
        }
        for platform in &failed_platforms {
            println!(
                "  {} {} (not built)",
                style("⚠️").yellow(),
                platform.to_uppercase()
            );
        }

        let total_platforms = collected_platforms.len() + failed_platforms.len();
        println!(
            "\nTotal: {}/{} platform(s)",
            collected_platforms.len(),
            total_platforms
        );
        println!("{}", "=".repeat(80));

        // Print package contents
        println!("\n{}", "=".repeat(80));
        println!("Package Contents");
        println!("{}", "=".repeat(80));
        println!("\n📁 {}/", output_path.display());

        if let Ok(entries) = fs::read_dir(&output_path) {
            let mut items: Vec<_> = entries.filter_map(|e| e.ok()).collect();
            items.sort_by_key(|e| e.file_name());

            for entry in items {
                let path = entry.path();
                if path.is_file() {
                    let filename = path.file_name().unwrap().to_string_lossy();
                    let size_mb = fs::metadata(&path)?.len() as f64 / (1024.0 * 1024.0);
                    println!("   📦 {} ({:.2} MB)", filename, size_mb);

                    // If it's a ZIP file, print its contents
                    if filename.ends_with(".zip") {
                        if let Err(e) = print_zip_contents(&path, "      ") {
                            println!("      Error reading ZIP contents: {}", e);
                        }
                    }
                }
            }
        }

        println!("\n{}", "=".repeat(80));
        println!("\n{}", style("✅ Package complete!").green().bold());
        println!("   Output: {}\n", output_path.display());

        // Publish to dist branch if requested
        let branch = if let Some(ref b) = self.dist_branch {
            Some(b.as_str())
        } else if self.dist {
            Some("dist")
        } else {
            None
        };

        if let Some(branch) = branch {
            let version_clean = version.strip_prefix('v').unwrap_or(&version);
            publish_to_dist_branch(
                &project_dir,
                &output_path,
                branch,
                &project_name,
                version_clean,
                self.dist_push,
            )?;
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_generate_embedded_ccgo_toml_with_zip_deps() {
        let tmp = tempfile::tempdir().unwrap();
        let config_path = tmp.path().join("CCGO.toml");
        fs::write(&config_path, r#"
[package]
name = "netcomm"
version = "1.2.3"
description = "netcomm SDK"

[[dependencies]]
name = "foundrycomm"
version = "1.0.0"
zip = "https://cdn.example.com/foundrycomm_SDK-1.0.0.zip"

[[dependencies]]
name = "locallib"
version = "0.5.0"
git = "https://github.com/example/locallib.git"
"#).unwrap();

        let result = generate_embedded_ccgo_toml(&config_path).unwrap();
        assert!(result.contains("[package]"));
        assert!(result.contains("name = \"netcomm\""));
        assert!(result.contains("version = \"1.2.3\""));
        assert!(result.contains("description = \"netcomm SDK\""));
        // Only zip deps included
        assert!(result.contains("foundrycomm"));
        assert!(result.contains("zip = \"https://cdn.example.com/foundrycomm_SDK-1.0.0.zip\""));
        // git deps NOT included
        assert!(!result.contains("locallib"));
    }

    #[test]
    fn test_generate_embedded_ccgo_toml_no_deps() {
        let tmp = tempfile::tempdir().unwrap();
        let config_path = tmp.path().join("CCGO.toml");
        fs::write(&config_path, r#"
[package]
name = "standalone"
version = "2.0.0"
"#).unwrap();

        let result = generate_embedded_ccgo_toml(&config_path).unwrap();
        assert!(result.contains("name = \"standalone\""));
        assert!(!result.contains("[[dependencies]]"));
    }
}