gen-orb-mcp 0.1.5

Generate MCP servers from CircleCI orb definitions
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
//! # gen-orb-mcp
//!
//! Generate MCP (Model Context Protocol) servers from CircleCI orb definitions.
//!
//! This tool enables AI coding assistants to understand and work with private
//! CircleCI orbs by generating MCP servers that expose orb commands, jobs,
//! and executors as resources.
//!
//! ## Usage
//!
//! ```bash
//! gen-orb-mcp generate --orb-path ./src/@orb.yml --output ./dist/
//! ```

pub mod conformance_rule;
pub mod consumer_parser;
pub mod differ;
pub mod generator;
pub mod migrator;
pub mod parser;
pub mod primer;

use anyhow::Result;
use clap::{Parser, Subcommand};
use generator::CodeGenerator;
use parser::OrbParser;

/// Generate MCP servers from CircleCI orb definitions
#[derive(Debug, Parser)]
#[command(name = "gen-orb-mcp")]
#[command(author, version, about, long_about = None)]
pub struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Debug, Subcommand)]
enum Commands {
    /// Generate an MCP server from an orb definition
    Generate {
        /// Path to the orb YAML file (e.g., src/@orb.yml)
        #[arg(short = 'p', long)]
        orb_path: std::path::PathBuf,

        /// Output directory for generated server
        #[arg(short = 'o', long, default_value = "./dist")]
        output: std::path::PathBuf,

        /// Output format
        #[arg(short, long, value_enum, default_value = "source")]
        format: OutputFormat,

        /// Name for the generated orb server (defaults to filename)
        #[arg(short, long)]
        name: Option<String>,

        /// Version for the generated MCP server crate (e.g., "1.0.0")
        ///
        /// Required when regenerating an existing output directory.
        /// For CI workflows, this should match the orb release version.
        #[arg(short = 'V', long)]
        version: Option<String>,

        /// Overwrite existing files without confirmation
        ///
        /// Required for non-interactive CI environments when output exists.
        #[arg(long)]
        force: bool,

        /// Directory containing conformance rule JSON files to embed in the
        /// server
        ///
        /// All *.json files in this directory are merged and embedded as
        /// migration tooling in the generated server. When provided,
        /// the server gains plan_migration and apply_migration MCP
        /// Tools in addition to Resources.
        #[arg(long)]
        migrations: Option<std::path::PathBuf>,

        /// Directory of prior orb version YAML snapshots to embed in the server
        ///
        /// Each file should be named `<version>.yml` (e.g., `4.7.1.yml`). The
        /// generated server will expose version-specific resources for each
        /// prior version alongside the current version.
        #[arg(long)]
        prior_versions: Option<std::path::PathBuf>,
    },
    /// Validate an orb definition without generating
    Validate {
        /// Path to the orb YAML file
        #[arg(short = 'p', long)]
        orb_path: std::path::PathBuf,
    },
    /// Compute conformance rules by diffing two orb versions
    ///
    /// Compares the current orb against a previous version (read from a file)
    /// and emits a JSON array of ConformanceRule values. These rules can be
    /// passed to `generate --migrations` to embed migration tooling in the
    /// generated MCP server.
    Diff {
        /// Path to the current orb YAML (the new version)
        #[arg(long)]
        current: std::path::PathBuf,

        /// Path to the previous orb YAML (the old version to diff against)
        #[arg(long)]
        previous: std::path::PathBuf,

        /// The version string to embed in emitted rules (e.g. "5.0.0")
        #[arg(long)]
        since_version: String,

        /// Optional output file for the JSON rules (default: stdout)
        #[arg(long)]
        output: Option<std::path::PathBuf>,
    },
    /// Apply conformance-based migration to a consumer's .circleci/ directory
    ///
    /// Reads conformance rules from a JSON file (produced by `diff`) and
    /// applies them to the consumer's CI config. Reports planned changes
    /// before applying.
    Migrate {
        /// Path to the consumer's .circleci/ directory
        #[arg(long, default_value = ".circleci")]
        ci_dir: std::path::PathBuf,

        /// The orb alias as used in the consumer's orbs: section (e.g.
        /// "toolkit")
        #[arg(long)]
        orb: String,

        /// Path to the conformance rules JSON file (produced by `diff`)
        #[arg(long)]
        rules: std::path::PathBuf,

        /// Show planned changes without modifying files
        #[arg(long)]
        dry_run: bool,
    },
    /// Populate prior-versions/ and migrations/ from git history
    ///
    /// Discovers version tags in a sliding window (default: last 6 months),
    /// checks out each version, saves a snapshot to
    /// `prior-versions/<version>.yml`, and computes conformance-rule diffs
    /// to `migrations/<version>.json`. Removes files for versions outside
    /// the window to keep binary size bounded. Idempotent.
    Prime {
        /// Path to the orb YAML entry point
        #[arg(short = 'p', long, default_value = "src/@orb.yml")]
        orb_path: std::path::PathBuf,

        /// Path to the git repository root (default: walk up from orb-path to
        /// .git)
        #[arg(long)]
        git_repo: Option<std::path::PathBuf>,

        /// Git tag prefix (e.g. "v" matches tags like "v4.1.0")
        #[arg(long, default_value = "v")]
        tag_prefix: String,

        /// Fixed earliest version anchor (e.g. "4.1.0"); conflicts with --since
        #[arg(long, conflicts_with = "since")]
        earliest_version: Option<String>,

        /// Rolling window duration (e.g. "6 months", "1 year"); default: "6
        /// months"
        #[arg(long)]
        since: Option<String>,

        /// Directory to write prior-version snapshots
        #[arg(long, default_value = "prior-versions")]
        prior_versions_dir: std::path::PathBuf,

        /// Directory to write migration rule JSON files
        #[arg(long, default_value = "migrations")]
        migrations_dir: std::path::PathBuf,

        /// Write to `/tmp/gen-orb-mcp-prime-<pid>/` and print
        /// PRIME_PV_DIR/PRIME_MIG_DIR to stdout
        #[arg(long)]
        ephemeral: bool,

        /// Describe actions without writing any files
        #[arg(long)]
        dry_run: bool,
    },
}

/// Output format for generated MCP server
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum OutputFormat {
    /// Compile to native binary (Linux x86_64)
    Binary,
    /// Generate Rust source code
    Source,
}

/// Default version for fresh generation when no version is specified.
const DEFAULT_VERSION: &str = "0.1.0";

/// Optional embedding inputs for `run_generate`.
struct GenerateExtras<'a> {
    migrations: &'a Option<std::path::PathBuf>,
    prior_versions_dir: &'a Option<std::path::PathBuf>,
}

impl Cli {
    /// Execute the CLI command
    pub fn run(&self) -> Result<()> {
        match &self.command {
            Commands::Generate {
                orb_path,
                output,
                format,
                name,
                version,
                force,
                migrations,
                prior_versions,
            } => run_generate(
                orb_path,
                output,
                format,
                name,
                version,
                *force,
                GenerateExtras {
                    migrations,
                    prior_versions_dir: prior_versions,
                },
            ),
            Commands::Validate { orb_path } => run_validate(orb_path),
            Commands::Diff {
                current,
                previous,
                since_version,
                output,
            } => run_diff(current, previous, since_version, output),
            Commands::Migrate {
                ci_dir,
                orb,
                rules: rules_path,
                dry_run,
            } => run_migrate(ci_dir, orb, rules_path, *dry_run),
            Commands::Prime {
                orb_path,
                git_repo,
                tag_prefix,
                earliest_version,
                since,
                prior_versions_dir,
                migrations_dir,
                ephemeral,
                dry_run,
            } => run_prime(
                orb_path,
                git_repo.as_deref(),
                tag_prefix,
                earliest_version.as_deref(),
                since.as_deref(),
                prior_versions_dir,
                migrations_dir,
                *ephemeral,
                *dry_run,
            ),
        }
    }
}

fn run_generate(
    orb_path: &std::path::PathBuf,
    output: &std::path::PathBuf,
    format: &OutputFormat,
    name: &Option<String>,
    version: &Option<String>,
    force: bool,
    extras: GenerateExtras<'_>,
) -> Result<()> {
    tracing::info!(?orb_path, ?output, ?format, "Generating MCP server");

    let orb = OrbParser::parse(orb_path).map_err(|e| anyhow::anyhow!("{}", e))?;
    tracing::info!(
        commands = orb.commands.len(),
        jobs = orb.jobs.len(),
        executors = orb.executors.len(),
        "Parsed orb definition"
    );

    let orb_name = name.clone().unwrap_or_else(|| derive_orb_name(orb_path));
    let resolved_version = resolve_version(output, version.as_deref(), force)?;
    tracing::info!(version = %resolved_version, "Using version");

    let conformance_rules = if let Some(migrations_dir) = extras.migrations {
        load_conformance_rules(migrations_dir)?
    } else {
        vec![]
    };
    if !conformance_rules.is_empty() {
        tracing::info!(rules = conformance_rules.len(), "Loaded conformance rules");
    }

    let prior_versions_data = if let Some(dir) = extras.prior_versions_dir {
        load_prior_versions(dir)?
    } else {
        vec![]
    };
    if !prior_versions_data.is_empty() {
        tracing::info!(
            versions = prior_versions_data.len(),
            "Loaded prior versions"
        );
    }

    let conformance_rules_json = if !conformance_rules.is_empty() {
        Some(serde_json::to_string(&conformance_rules)?)
    } else {
        None
    };

    let generator = CodeGenerator::new()
        .map_err(|e| anyhow::anyhow!("{}", e))?
        .with_prior_versions(prior_versions_data)
        .with_conformance_rules_json_opt(conformance_rules_json);
    let server = generator
        .generate(&orb, &orb_name, &resolved_version)
        .map_err(|e| anyhow::anyhow!("{}", e))?;

    match format {
        OutputFormat::Source => {
            server
                .write_to(output)
                .map_err(|e| anyhow::anyhow!("{}", e))?;
            println!("Generated MCP server source code:");
            println!("  Output: {}", output.display());
            println!("  Crate: {}", server.crate_name);
            println!("  Version: {}", resolved_version);
            println!("  Commands: {}", orb.commands.len());
            println!("  Jobs: {}", orb.jobs.len());
            println!("  Executors: {}", orb.executors.len());
            println!();
            println!("To build: cd {} && cargo build --release", output.display());
        }
        OutputFormat::Binary => {
            server
                .write_to(output)
                .map_err(|e| anyhow::anyhow!("{}", e))?;
            println!("Compiling MCP server...");
            let status = std::process::Command::new("cargo")
                .args(["build", "--release"])
                .current_dir(output)
                .status();
            match status {
                Ok(s) if s.success() => {
                    let binary_path = output.join("target/release").join(&server.crate_name);
                    println!("Successfully compiled MCP server:");
                    println!("  Binary: {}", binary_path.display());
                    println!("  Version: {}", resolved_version);
                }
                Ok(_) => {
                    anyhow::bail!(
                        "Compilation failed. Source code is available at: {}",
                        output.display()
                    );
                }
                Err(e) => {
                    anyhow::bail!(
                        "Failed to run cargo: {}. Source code is available at: {}",
                        e,
                        output.display()
                    );
                }
            }
        }
    }

    Ok(())
}

fn run_validate(orb_path: &std::path::PathBuf) -> Result<()> {
    tracing::info!(?orb_path, "Validating orb definition");
    let orb = OrbParser::parse(orb_path).map_err(|e| anyhow::anyhow!("{}", e))?;

    println!("Orb validation successful!");
    println!("  Version: {}", orb.version);
    if let Some(desc) = &orb.description {
        println!("  Description: {}", desc);
    }
    println!("  Commands: {}", orb.commands.len());
    for name in orb.commands.keys() {
        println!("    - {}", name);
    }
    println!("  Jobs: {}", orb.jobs.len());
    for name in orb.jobs.keys() {
        println!("    - {}", name);
    }
    println!("  Executors: {}", orb.executors.len());
    for name in orb.executors.keys() {
        println!("    - {}", name);
    }
    Ok(())
}

fn run_diff(
    current: &std::path::PathBuf,
    previous: &std::path::PathBuf,
    since_version: &str,
    output: &Option<std::path::PathBuf>,
) -> Result<()> {
    tracing::info!(?current, ?previous, "Diffing orb versions");

    let new_orb = OrbParser::parse(current).map_err(|e| anyhow::anyhow!("{}", e))?;
    let old_orb = OrbParser::parse(previous).map_err(|e| anyhow::anyhow!("{}", e))?;

    let rules = differ::diff(&old_orb, &new_orb, since_version);
    println!("Computed {} conformance rule(s):", rules.len());
    for rule in &rules {
        println!("  • {}", rule.description());
    }

    let json = serde_json::to_string_pretty(&rules)?;

    if let Some(out_path) = output {
        std::fs::write(out_path, &json)?;
        println!("\nRules written to: {}", out_path.display());
    } else {
        println!("\n{}", json);
    }

    Ok(())
}

fn run_migrate(
    ci_dir: &std::path::PathBuf,
    orb: &str,
    rules_path: &std::path::PathBuf,
    dry_run: bool,
) -> Result<()> {
    tracing::info!(?ci_dir, orb, "Migrating consumer config");

    let rules_json = std::fs::read_to_string(rules_path)
        .map_err(|e| anyhow::anyhow!("Failed to read rules file: {}", e))?;
    let rules: Vec<conformance_rule::ConformanceRule> = serde_json::from_str(&rules_json)
        .map_err(|e| anyhow::anyhow!("Failed to parse rules JSON: {}", e))?;

    let config = consumer_parser::ConsumerParser::parse_directory(ci_dir)
        .map_err(|e| anyhow::anyhow!("Failed to parse CI config: {}", e))?;

    let plan = migrator::Migrator::plan(&rules, &config, orb);
    println!("{}", plan.format_summary());

    if plan.changes.is_empty() {
        return Ok(());
    }

    if dry_run {
        println!("\n(Dry run — no files modified)");
        return Ok(());
    }

    let applied = migrator::Migrator::apply(&plan, false)?;
    println!("\n{}", applied.format_summary());

    Ok(())
}

/// Loads prior orb version snapshots from a directory of `<version>.yml` files.
fn load_prior_versions(dir: &std::path::Path) -> Result<Vec<(String, parser::OrbDefinition)>> {
    if !dir.is_dir() {
        anyhow::bail!("Prior versions directory does not exist: {}", dir.display());
    }
    let mut versions = Vec::new();
    let entries = std::fs::read_dir(dir)?;
    for entry in entries.flatten() {
        let path = entry.path();
        if path.extension().and_then(|e| e.to_str()) != Some("yml") {
            continue;
        }
        let version = path
            .file_stem()
            .and_then(|s| s.to_str())
            .unwrap_or("")
            .to_string();
        if version.is_empty() {
            continue;
        }
        let orb_def = OrbParser::parse(&path)
            .map_err(|e| anyhow::anyhow!("Failed to parse {}: {}", path.display(), e))?;
        tracing::debug!(path = %path.display(), version = %version, "Loaded prior version");
        versions.push((version, orb_def));
    }
    Ok(versions)
}

/// Loads and merges conformance rules from all `*.json` files in a directory.
fn load_conformance_rules(dir: &std::path::Path) -> Result<Vec<conformance_rule::ConformanceRule>> {
    if !dir.is_dir() {
        anyhow::bail!("Migrations directory does not exist: {}", dir.display());
    }
    let mut all_rules = Vec::new();
    let entries = std::fs::read_dir(dir)?;
    for entry in entries.flatten() {
        let path = entry.path();
        if path.extension().and_then(|e| e.to_str()) != Some("json") {
            continue;
        }
        let json = std::fs::read_to_string(&path)
            .map_err(|e| anyhow::anyhow!("Failed to read {}: {}", path.display(), e))?;
        let rules: Vec<conformance_rule::ConformanceRule> = serde_json::from_str(&json)
            .map_err(|e| anyhow::anyhow!("Failed to parse {}: {}", path.display(), e))?;
        tracing::debug!(path = %path.display(), count = rules.len(), "Loaded rules file");
        all_rules.extend(rules);
    }
    Ok(all_rules)
}

#[allow(clippy::too_many_arguments)]
fn run_prime(
    orb_path: &std::path::Path,
    git_repo: Option<&std::path::Path>,
    tag_prefix: &str,
    earliest_version: Option<&str>,
    since: Option<&str>,
    prior_versions_dir: &std::path::Path,
    migrations_dir: &std::path::Path,
    ephemeral: bool,
    dry_run: bool,
) -> Result<()> {
    use chrono::Local;
    use primer::{
        discover_tags, filter_by_date, filter_by_version, since_cutoff, tag_date, PrimeConfig,
    };

    // Resolve git repo path: either provided, or walk up from orb_path
    let repo_path = if let Some(r) = git_repo {
        r.to_path_buf()
    } else {
        find_git_root(orb_path)?
    };

    // Relative orb path from repo root
    let orb_abs = orb_path
        .canonicalize()
        .unwrap_or_else(|_| orb_path.to_path_buf());
    let repo_abs = repo_path
        .canonicalize()
        .unwrap_or_else(|_| repo_path.to_path_buf());
    let orb_rel = orb_abs
        .strip_prefix(&repo_abs)
        .unwrap_or(orb_path)
        .to_path_buf();

    // Resolve output dirs
    let (pv_dir, mig_dir) = if ephemeral {
        let base =
            std::path::PathBuf::from(format!("/tmp/gen-orb-mcp-prime-{}", std::process::id()));
        (base.join("prior-versions"), base.join("migrations"))
    } else {
        (
            prior_versions_dir.to_path_buf(),
            migrations_dir.to_path_buf(),
        )
    };

    // Discover and filter tags
    let all_tags = discover_tags(&repo_path, tag_prefix)?;
    tracing::info!(count = all_tags.len(), "Discovered version tags");

    let window_versions: Vec<String> = if let Some(ver_str) = earliest_version {
        let earliest = semver::Version::parse(ver_str)
            .map_err(|e| anyhow::anyhow!("Invalid version '{}': {}", ver_str, e))?;
        filter_by_version(&all_tags, &earliest)
    } else {
        let since_str = since.unwrap_or("6 months");
        let today = Local::now().date_naive();
        let cutoff = since_cutoff(since_str, today)?;
        // Need dates for each tag
        let tags_with_dates: Vec<primer::TagWithDate> = all_tags
            .iter()
            .filter_map(|v| match tag_date(&repo_path, tag_prefix, v) {
                Ok(d) => Some(primer::TagWithDate {
                    version: v.clone(),
                    date: d,
                }),
                Err(e) => {
                    tracing::warn!(version = %v, error = %e, "Could not get tag date, skipping");
                    None
                }
            })
            .collect();
        filter_by_date(&tags_with_dates, cutoff)
    };

    tracing::info!(count = window_versions.len(), "Versions in window");

    let config = PrimeConfig {
        git_repo: repo_path,
        tag_prefix: tag_prefix.to_string(),
        orb_path_relative: orb_rel,
        prior_versions_dir: pv_dir.clone(),
        migrations_dir: mig_dir.clone(),
        dry_run,
    };

    let result = primer::prime(&config, &window_versions)?;

    if ephemeral {
        println!("PRIME_PV_DIR={}", pv_dir.display());
        println!("PRIME_MIG_DIR={}", mig_dir.display());
    }

    println!(
        "prime: +{} snapshots, -{} snapshots, +{} migrations, -{} migrations",
        result.snapshots_added,
        result.snapshots_removed,
        result.migrations_added,
        result.migrations_removed,
    );

    Ok(())
}

/// Walk up from `start` looking for a `.git` directory.
fn find_git_root(start: &std::path::Path) -> Result<std::path::PathBuf> {
    let mut dir = if start.is_file() {
        start.parent().unwrap_or(start).to_path_buf()
    } else {
        start.to_path_buf()
    };
    loop {
        if dir.join(".git").exists() {
            return Ok(dir);
        }
        match dir.parent() {
            Some(p) => dir = p.to_path_buf(),
            None => anyhow::bail!(
                "Could not find git repository root starting from '{}'",
                start.display()
            ),
        }
    }
}

/// Derive orb name from the orb path.
///
/// For unpacked orbs (`@orb.yml`), uses the project directory name.
/// Handles the common `project/src/@orb.yml` structure by skipping the `src`
/// directory. For packed orbs, uses the file stem (filename without extension).
fn derive_orb_name(path: &std::path::Path) -> String {
    let filename = path.file_name().and_then(|s| s.to_str()).unwrap_or("orb");

    if filename == "@orb.yml" {
        // Get parent directory
        let parent = path.parent();
        let parent_name = parent.and_then(|p| p.file_name()).and_then(|s| s.to_str());

        // If parent is "src", go up one more level to get project name
        if parent_name == Some("src") {
            parent
                .and_then(|p| p.parent())
                .and_then(|p| p.file_name())
                .and_then(|s| s.to_str())
                .unwrap_or("orb")
                .to_string()
        } else {
            parent_name.unwrap_or("orb").to_string()
        }
    } else {
        // Use filename without extension
        path.file_stem()
            .and_then(|s| s.to_str())
            .unwrap_or("orb")
            .to_string()
    }
}

/// Resolve the version to use for the generated MCP server.
///
/// # Version Resolution Rules
///
/// 1. If `--version` is provided, use it
/// 2. If output directory exists with Cargo.toml and no `--version`:
///    - Error: must specify version to regenerate
/// 3. If fresh generation and no `--version`: use DEFAULT_VERSION
///
/// The `--force` flag is required when overwriting existing output.
fn resolve_version(output: &std::path::Path, version: Option<&str>, force: bool) -> Result<String> {
    let cargo_toml = output.join("Cargo.toml");
    let output_exists = cargo_toml.exists();

    match (version, output_exists) {
        // Explicit version provided - use it
        (Some(v), false) => {
            tracing::debug!("Using provided version for fresh generation");
            Ok(v.to_string())
        }
        (Some(v), true) => {
            if !force {
                anyhow::bail!(
                    "Output directory '{}' already exists. Use --force to overwrite.",
                    output.display()
                );
            }
            tracing::debug!("Using provided version, overwriting existing output");
            Ok(v.to_string())
        }

        // No version provided
        (None, false) => {
            tracing::debug!("Fresh generation with default version");
            Ok(DEFAULT_VERSION.to_string())
        }
        (None, true) => {
            anyhow::bail!(
                "Output directory '{}' already exists.\n\
                 To regenerate, you must specify the version explicitly:\n\n\
                 \x20   gen-orb-mcp generate --orb-path <PATH> --output {} --version <VERSION> --force\n\n\
                 For CI release workflows, use the orb release version (e.g., --version 1.6.0).",
                output.display(),
                output.display()
            );
        }
    }
}

#[cfg(test)]
mod tests {
    use tempfile::TempDir;

    use super::*;

    #[test]
    fn test_cli_parse_generate() {
        let cli = Cli::try_parse_from([
            "gen-orb-mcp",
            "generate",
            "--orb-path",
            "test.yml",
            "--output",
            "./out",
        ]);
        assert!(cli.is_ok());
    }

    #[test]
    fn test_cli_parse_generate_with_version() {
        let cli = Cli::try_parse_from([
            "gen-orb-mcp",
            "generate",
            "--orb-path",
            "test.yml",
            "--output",
            "./out",
            "--version",
            "1.2.3",
        ]);
        assert!(cli.is_ok());
    }

    #[test]
    fn test_cli_parse_generate_with_force() {
        let cli = Cli::try_parse_from([
            "gen-orb-mcp",
            "generate",
            "--orb-path",
            "test.yml",
            "--output",
            "./out",
            "--version",
            "1.2.3",
            "--force",
        ]);
        assert!(cli.is_ok());
    }

    #[test]
    fn test_cli_parse_validate() {
        let cli = Cli::try_parse_from(["gen-orb-mcp", "validate", "--orb-path", "test.yml"]);
        assert!(cli.is_ok());
    }

    #[test]
    fn test_derive_orb_name_from_orb_yml() {
        use std::path::Path;
        // Standard orb structure: project/src/@orb.yml -> "project"
        let path = Path::new("/path/to/my-toolkit/src/@orb.yml");
        assert_eq!(derive_orb_name(path), "my-toolkit");

        // Non-standard structure without src: my-orb/@orb.yml -> "my-orb"
        let path = Path::new("my-orb/@orb.yml");
        assert_eq!(derive_orb_name(path), "my-orb");

        // Edge case: src/@orb.yml at root -> "orb" (no grandparent, falls back to
        // default)
        let path = Path::new("src/@orb.yml");
        assert_eq!(derive_orb_name(path), "orb");
    }

    #[test]
    fn test_derive_orb_name_from_packed() {
        use std::path::Path;
        let path = Path::new("/path/to/my-toolkit.yml");
        assert_eq!(derive_orb_name(path), "my-toolkit");

        let path = Path::new("orb.yml");
        assert_eq!(derive_orb_name(path), "orb");
    }

    #[test]
    fn test_resolve_version_fresh_with_explicit() {
        let temp_dir = TempDir::new().unwrap();
        let result = resolve_version(temp_dir.path(), Some("2.0.0"), false);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "2.0.0");
    }

    #[test]
    fn test_resolve_version_fresh_with_default() {
        let temp_dir = TempDir::new().unwrap();
        let result = resolve_version(temp_dir.path(), None, false);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), DEFAULT_VERSION);
    }

    #[test]
    fn test_resolve_version_existing_without_version_fails() {
        let temp_dir = TempDir::new().unwrap();
        // Create a Cargo.toml to simulate existing output
        std::fs::write(
            temp_dir.path().join("Cargo.toml"),
            "[package]\nname = \"test\"",
        )
        .unwrap();

        let result = resolve_version(temp_dir.path(), None, false);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("already exists"));
        assert!(err.contains("--version"));
    }

    #[test]
    fn test_resolve_version_existing_with_version_no_force_fails() {
        let temp_dir = TempDir::new().unwrap();
        std::fs::write(
            temp_dir.path().join("Cargo.toml"),
            "[package]\nname = \"test\"",
        )
        .unwrap();

        let result = resolve_version(temp_dir.path(), Some("1.5.0"), false);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("--force"));
    }

    #[test]
    fn test_resolve_version_existing_with_version_and_force_succeeds() {
        let temp_dir = TempDir::new().unwrap();
        std::fs::write(
            temp_dir.path().join("Cargo.toml"),
            "[package]\nname = \"test\"",
        )
        .unwrap();

        let result = resolve_version(temp_dir.path(), Some("1.5.0"), true);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "1.5.0");
    }

    #[test]
    fn test_cli_parse_generate_with_prior_versions() {
        let cli = Cli::try_parse_from([
            "gen-orb-mcp",
            "generate",
            "--orb-path",
            "test.yml",
            "--output",
            "./out",
            "--prior-versions",
            "./prior",
        ]);
        assert!(cli.is_ok(), "expected --prior-versions flag to be accepted");
    }

    // Tests 11-15: prime command CLI parsing

    #[test]
    fn test_cli_parse_prime_defaults() {
        let cli = Cli::try_parse_from(["gen-orb-mcp", "prime"]);
        assert!(cli.is_ok(), "prime with all defaults should parse");
        if let Commands::Prime {
            orb_path,
            tag_prefix,
            earliest_version,
            since,
            prior_versions_dir,
            migrations_dir,
            ephemeral,
            dry_run,
            git_repo,
        } = cli.unwrap().command
        {
            assert_eq!(orb_path.to_str().unwrap(), "src/@orb.yml");
            assert_eq!(tag_prefix, "v");
            assert!(earliest_version.is_none());
            assert!(since.is_none());
            assert_eq!(prior_versions_dir.to_str().unwrap(), "prior-versions");
            assert_eq!(migrations_dir.to_str().unwrap(), "migrations");
            assert!(!ephemeral);
            assert!(!dry_run);
            assert!(git_repo.is_none());
        } else {
            panic!("expected Prime variant");
        }
    }

    #[test]
    fn test_cli_parse_prime_earliest_version() {
        let cli = Cli::try_parse_from(["gen-orb-mcp", "prime", "--earliest-version", "4.1.0"]);
        assert!(cli.is_ok(), "prime --earliest-version should parse");
        if let Commands::Prime {
            earliest_version, ..
        } = cli.unwrap().command
        {
            assert_eq!(earliest_version.as_deref(), Some("4.1.0"));
        } else {
            panic!("expected Prime variant");
        }
    }

    #[test]
    fn test_cli_parse_prime_since() {
        let cli = Cli::try_parse_from(["gen-orb-mcp", "prime", "--since", "3 months"]);
        assert!(cli.is_ok(), "prime --since should parse");
        if let Commands::Prime { since, .. } = cli.unwrap().command {
            assert_eq!(since.as_deref(), Some("3 months"));
        } else {
            panic!("expected Prime variant");
        }
    }

    #[test]
    fn test_cli_parse_prime_exclusive_flags() {
        // --earliest-version and --since are mutually exclusive
        let cli = Cli::try_parse_from([
            "gen-orb-mcp",
            "prime",
            "--earliest-version",
            "4.1.0",
            "--since",
            "6 months",
        ]);
        assert!(
            cli.is_err(),
            "prime with both --earliest-version and --since should be rejected"
        );
    }

    #[test]
    fn test_cli_parse_prime_ephemeral() {
        let cli = Cli::try_parse_from(["gen-orb-mcp", "prime", "--ephemeral"]);
        assert!(cli.is_ok(), "prime --ephemeral should parse");
        if let Commands::Prime { ephemeral, .. } = cli.unwrap().command {
            assert!(ephemeral);
        } else {
            panic!("expected Prime variant");
        }
    }
}