blazy 0.3.0

Unified, AI-safe meta-package manager for 28 OS and language package managers
use crate::model::{ActionKind, ProviderId};
use clap::{Parser, Subcommand, ValueEnum};

#[derive(Debug, Parser)]
#[command(
    name = "blazy",
    version,
    about = "A unified meta-package manager for humans and AI"
)]
pub struct Cli {
    /// Emit machine-readable JSON output
    #[arg(long, global = true)]
    pub json: bool,

    /// Emit newline-delimited JSON progress events (ideal for streaming AI agents)
    #[arg(long, global = true)]
    pub ndjson: bool,

    /// Disable ANSI colors in human output
    #[arg(long, global = true)]
    pub no_color: bool,

    /// Suppress informational headers and warnings in human output
    #[arg(short = 'q', long, global = true)]
    pub quiet: bool,

    /// Skip interactive confirmation prompts
    #[arg(short = 'y', long, global = true)]
    pub yes: bool,

    /// Allow operations that may require administrator elevation
    #[arg(long, global = true)]
    pub allow_elevation: bool,

    #[command(subcommand)]
    pub command: Commands,
}

#[derive(Debug, Subcommand)]
pub enum Commands {
    /// Inspect installed package managers, versions, and environment health
    Doctor {
        /// Exit with non-zero code if no package managers are available or PATH shadowing is detected
        #[arg(long)]
        check: bool,
    },

    /// Search for a package across available providers
    Search {
        /// Package name or query
        query: String,

        /// Restrict search to specific comma-separated providers (e.g. scoop,winget,uv)
        #[arg(long, value_delimiter = ',')]
        r#in: Vec<ProviderId>,

        /// Maximum number of candidates to return (ignored if --all is passed)
        #[arg(long, default_value_t = 20)]
        limit: usize,

        /// Return all matching candidates without truncation
        #[arg(long)]
        all: bool,
    },

    /// Build a deterministic execution plan without modifying the system
    Plan {
        /// Action to plan
        #[arg(value_enum)]
        action: PlanAction,

        /// Package target (e.g. ripgrep, scoop:ripgrep, uv:ruff@0.9.0)
        target: String,

        /// Force a specific provider
        #[arg(long)]
        provider: Option<ProviderId>,
    },

    /// Install a package via the best matching or explicit provider
    #[command(aliases = ["add", "i"])]
    Install {
        /// Package target (e.g. python, ripgrep, scoop:ripgrep, npm:typescript)
        target: String,

        /// Force a specific provider
        #[arg(long)]
        provider: Option<ProviderId>,

        /// Show the execution plan without running it
        #[arg(long)]
        dry_run: bool,
    },

    /// Uninstall an installed package
    #[command(aliases = ["remove", "rm"])]
    Uninstall {
        /// Package target (e.g. ripgrep, scoop:ripgrep)
        target: String,

        /// Force a specific provider
        #[arg(long)]
        provider: Option<ProviderId>,

        /// Show the execution plan without running it
        #[arg(long)]
        dry_run: bool,
    },

    /// Update a specific package or all packages across providers (use `*` or omit target for all)
    Update {
        /// Optional package target; omit or pass `*` to update all available providers
        target: Option<String>,

        /// Force a specific provider
        #[arg(long)]
        provider: Option<ProviderId>,

        /// Show the execution plan without running it
        #[arg(long)]
        dry_run: bool,
    },

    /// Check which installed packages have updates available
    Outdated {
        /// Restrict check to specific comma-separated providers
        #[arg(long, value_delimiter = ',')]
        r#in: Vec<ProviderId>,
    },

    /// List installed packages across providers
    List {
        /// Restrict listing to specific comma-separated providers
        #[arg(long, value_delimiter = ',')]
        r#in: Vec<ProviderId>,
    },

    /// Create a starter blazy.toml manifest in the current directory
    Init {
        /// Path to the manifest file
        #[arg(long, default_value = "blazy.toml")]
        file: String,

        /// Overwrite an existing manifest file
        #[arg(long)]
        force: bool,
    },

    /// Export currently installed packages into a blazy.toml manifest
    Export {
        /// Path to write the exported manifest
        #[arg(long, default_value = "blazy.toml")]
        file: String,

        /// Restrict export to specific comma-separated providers
        #[arg(long, value_delimiter = ',')]
        r#in: Vec<ProviderId>,

        /// Overwrite an existing manifest file
        #[arg(long)]
        force: bool,

        /// Pin exact installed versions (e.g. `ripgrep@14.1.1`)
        #[arg(long)]
        pin: bool,
    },

    /// Sync missing packages declared in blazy.toml
    Sync {
        /// Path to the manifest file
        #[arg(long, default_value = "blazy.toml")]
        file: String,

        /// Show what would be installed without modifying the system
        #[arg(long)]
        dry_run: bool,

        /// Fail with non-zero exit code if manifest/lockfile and installed state drift (CI mode)
        #[arg(long)]
        locked: bool,
    },

    /// Show recent package actions recorded in the audit log
    History {
        /// Maximum number of entries to display
        #[arg(long, default_value_t = 20)]
        limit: usize,
    },

    /// Undo the most recent successful add or remove action
    Undo {
        /// Show the rollback plan without executing it
        #[arg(long)]
        dry_run: bool,
    },

    /// Output a ready-to-use SKILL.md for AI coding agents
    Skill {
        /// Optional file path to write SKILL.md to (prints to stdout if omitted)
        #[arg(long)]
        out: Option<String>,

        /// Install SKILL.md directly into an agent's skill directory (codex, claude, opencode, cursor, antigravity)
        #[arg(long, value_enum)]
        install: Option<SkillClient>,
    },

    /// Locate a command on PATH, show shadowed binaries, and identify owning package managers
    Which {
        /// Command or binary name (e.g. rg, node, python, cargo)
        command: String,

        /// Print a dry-run PATH reorder command to resolve shadowing
        #[arg(long)]
        fix: bool,

        /// Apply the PATH reorder to your current user environment (Windows; requires -y)
        #[arg(long)]
        apply: bool,
    },

    /// Audit installed packages for cross-provider duplicates and conflicts
    Audit {
        /// Restrict audit to specific comma-separated providers
        #[arg(long, value_delimiter = ',')]
        r#in: Vec<ProviderId>,

        /// Interactively remove duplicate installations (keeps your highest-priority provider)
        #[arg(long)]
        fix: bool,
    },

    /// Generate shell tab-completion scripts (powershell, bash, zsh, fish, elvish)
    Completions {
        /// Target shell
        #[arg(value_enum)]
        shell: clap_complete::Shell,
    },

    /// View or update preferred package managers in your config file (~/.config/blazy/config.toml)
    Config {
        #[command(subcommand)]
        action: ConfigAction,
    },

    /// Run a tool ephemerally without installing it globally (e.g. `blazy run ruff -- --version`)
    Run {
        /// Tool or package target (e.g. ruff, uv:ruff, bun:biome, or a cached alias)
        target: String,

        /// Show the ephemeral execution plan without running it
        #[arg(long)]
        dry_run: bool,

        /// Cache this tool under an alias in ~/.config/blazy/run_cache.json for instant reuse
        #[arg(long)]
        keep: Option<String>,

        /// Arguments passed through to the tool
        #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
        args: Vec<String>,
    },

    /// Run a cached ephemeral tool alias saved with `blazy run --keep <alias>`
    Tool {
        /// Cached tool alias
        alias: String,

        /// Arguments passed through to the cached tool
        #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
        args: Vec<String>,
    },

    /// Bootstrap/install a missing package manager (scoop, uv, bun, pnpm, rustup, brew)
    Bootstrap {
        /// Name of the package manager to bootstrap
        manager: String,

        /// Show the bootstrap command without running it
        #[arg(long)]
        dry_run: bool,
    },

    /// Inspect or update the built-in cross-ecosystem package catalog
    Catalog {
        #[command(subcommand)]
        action: CatalogAction,
    },

    /// Inspect package metadata, catalog mappings, PATH status, and safety notes before installing
    Inspect {
        /// Package name or target (e.g. rg, python, github:sharkdp/fd)
        target: String,

        /// Force a specific provider
        #[arg(long)]
        provider: Option<ProviderId>,
    },

    /// Emit shell environment exports for local project toolchains (.venv, node_modules/.bin, blazy.toml)
    Env {
        /// Target shell syntax
        #[arg(long, value_enum)]
        shell: Option<EnvShell>,
    },

    /// Open an interactive terminal dashboard for doctor, outdated, audit, search, and sync
    Ui,

    /// Start the Model Context Protocol (MCP) stdio server for AI agents
    Mcp,
}

#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum SkillClient {
    Codex,
    Claude,
    Opencode,
    Cursor,
    Antigravity,
}

#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum EnvShell {
    Pwsh,
    Bash,
    Zsh,
}

#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum PlanAction {
    #[value(alias = "install")]
    Add,
    #[value(alias = "uninstall")]
    Remove,
    Update,
}

#[derive(Debug, Subcommand)]
pub enum ConfigAction {
    /// Show active configuration, preference order, and config file path
    Show,
    /// Create a user preferences config file (~/.config/blazy/config.toml)
    Init {
        /// Overwrite existing config file
        #[arg(long)]
        force: bool,
    },
    /// Set your preferred package manager priority order (e.g. `blazy config prefer scoop uv bun`)
    Prefer {
        /// Ordered list of preferred providers (highest priority first)
        #[arg(required = true)]
        providers: Vec<ProviderId>,
    },
}

#[derive(Debug, Subcommand)]
pub enum CatalogAction {
    /// List all canonical tools and aliases known by the catalog
    List,
    /// Download/sync community catalog overrides into ~/.config/blazy/catalog.json
    Update {
        /// Custom URL to fetch catalog JSON from
        #[arg(
            long,
            default_value = "https://raw.githubusercontent.com/Yash-K-Jagani/blazy/main/catalog.json"
        )]
        url: String,
    },
}

impl From<PlanAction> for ActionKind {
    fn from(value: PlanAction) -> Self {
        match value {
            PlanAction::Add => ActionKind::Add,
            PlanAction::Remove => ActionKind::Remove,
            PlanAction::Update => ActionKind::Update,
        }
    }
}