//! # Cargo Rustelo
//!
//! Cargo subcommand for the Rustelo framework.
//! Provides project initialization, asset management, and build tools.
//!
//! Usage: cargo rustelo <command>

use std::path::PathBuf;

use clap::{Parser, Subcommand};
use rustelo_core::Result;

mod assets;
mod commands;
mod conflicts;
mod integration;
mod marketplace;
mod performance;
mod security;
mod updater;

use commands::*;

#[derive(Parser)]
#[command(name = "cargo-rustelo")]
#[command(bin_name = "cargo rustelo")]
#[command(about = "Rustelo Framework - Cargo subcommand for project management")]
#[command(version)]
struct Cli {
    #[command(subcommand)]
    command: Commands,

    /// Enable verbose output
    #[arg(short, long, global = true)]
    verbose: bool,
}

#[derive(Subcommand)]
enum Commands {
    /// Build the implementation with asset resolution
    Build {
        /// Build for production
        #[arg(long)]
        release: bool,

        /// Skip asset resolution
        #[arg(long)]
        no_assets: bool,

        /// Only process specific asset categories
        #[arg(long, value_delimiter = ',')]
        categories: Option<Vec<String>>,

        /// Organize assets by category in output
        #[arg(long)]
        organize_by_category: bool,
    },

    /// Start development server with asset fallback
    Dev {
        /// Port to serve on
        #[arg(short, long, default_value = "3030")]
        port: u16,

        /// Enable hot reloading
        #[arg(long)]
        watch: bool,
    },

    /// Update framework version while preserving local changes
    Update {
        /// Framework version to update to
        version: Option<String>,

        /// Force update even if there are conflicts
        #[arg(long)]
        force: bool,

        /// Interactive mode - ask before making changes
        #[arg(short, long)]
        interactive: bool,

        /// Check what would be updated without applying changes
        #[arg(short, long)]
        check: bool,
    },

    /// Asset management commands
    Assets {
        #[command(subcommand)]
        command: AssetCommands,
    },

    /// Build pipeline management
    Pipeline {
        #[command(subcommand)]
        command: PipelineCommands,
    },

    /// Cross-compilation for Linux targets
    Cross {
        #[command(subcommand)]
        command: CrossCommands,
    },

    /// Feature management and discovery
    Features {
        #[command(subcommand)]
        command: FeatureCommands,
    },

    /// Foundation discovery and management
    Foundation {
        #[command(subcommand)]
        command: FoundationCommands,

        /// Force execution from Rustelo source (for framework developers)
        #[arg(long, global = true)]
        force_in_source: bool,
    },

    /// Foundation discovery and management (alias for foundation)
    Fn {
        #[command(subcommand)]
        command: FoundationCommands,

        /// Force execution from Rustelo source (for framework developers)
        #[arg(long, global = true)]
        force_in_source: bool,
    },

    /// Contribution detection and management
    Contributions {
        #[command(subcommand)]
        command: ContributionCommands,
    },

    /// Marketplace management commands
    Marketplace {
        #[command(subcommand)]
        command: MarketplaceCommands,
    },

    /// Conflict resolution and detection
    Conflicts {
        #[command(subcommand)]
        command: ConflictCommands,
    },

    /// Update management system
    UpdateManager {
        #[command(subcommand)]
        command: UpdateCommands,
    },

    /// Security scanning and validation
    Security {
        #[command(subcommand)]
        command: SecurityCommands,
    },

    /// Performance profiling and optimization
    Performance {
        #[command(subcommand)]
        command: PerformanceCommands,
    },

    /// Check and install prerequisites (Rust, Node.js, Nushell, Just)
    Prerequisites {
        /// Install missing prerequisites
        #[arg(long)]
        install: bool,

        /// Show verbose prerequisite information
        #[arg(short, long)]
        verbose: bool,

        /// Attempt to fix PATH issues
        #[arg(long)]
        fix_path: bool,

        /// Output format: human, json, yaml, toml
        #[arg(short, long, default_value = "human")]
        format: String,
    },

    /// Framework-integrity boundary check: protected paths, required traits and
    /// high-severity forbidden patterns, validated against the inherited
    /// manifest chain (framework first, then derived-layer manifests).
    Integrity {
        /// Manifest file(s) in chain order, framework-first then derived
        /// layers (e.g. a domain `site_manifest.toml`). Repeatable.
        #[arg(long = "manifest", value_name = "FILE", required = true)]
        manifests: Vec<PathBuf>,

        /// Implementation root to validate.
        #[arg(long = "impl", default_value = ".")]
        impl_root: PathBuf,

        /// Restrict the forbidden-pattern scan to these changed files
        /// (repeatable). Omit to scan the whole implementation tree.
        #[arg(long = "changed", value_name = "FILE")]
        changed: Vec<PathBuf>,

        /// Minimum severity to flag: critical | high | medium | low.
        #[arg(long, default_value = "high")]
        min_severity: String,

        /// Emit JSON instead of a text report.
        #[arg(long)]
        json: bool,
    },
}

#[derive(Subcommand)]
enum AssetCommands {
    /// List asset resolution paths
    List {
        /// Filter by asset category
        #[arg(long, value_delimiter = ',')]
        categories: Option<Vec<String>>,

        /// Show category statistics
        #[arg(long)]
        stats: bool,
    },

    /// Check for asset conflicts
    Check {
        /// Only check specific asset categories
        #[arg(long, value_delimiter = ',')]
        categories: Option<Vec<String>>,
    },

    /// Resolve a specific asset path
    Resolve { path: String },

    /// Organize assets by category
    Organize {
        /// Target directory for organized assets
        target: PathBuf,

        /// Only organize specific categories
        #[arg(long, value_delimiter = ',')]
        categories: Option<Vec<String>>,
    },

    /// Sync framework assets (for local development)
    Sync {
        /// Asset categories to sync
        #[arg(long, value_delimiter = ',')]
        categories: Option<Vec<String>>,

        /// Override asset source
        #[arg(long)]
        source: Option<String>,
    },

    /// Validate framework asset source
    Validate,

    /// List available framework assets
    FrameworkAssets,
}

#[derive(Subcommand)]
enum PipelineCommands {
    /// Initialize build pipeline configuration
    Init {
        /// Force overwrite existing configuration
        #[arg(long)]
        force: bool,
    },

    /// List available build targets
    Targets,

    /// Run a specific build target
    Run {
        /// Target name to run
        target: String,

        /// Additional build variables
        #[arg(long, value_delimiter = ',')]
        vars: Option<Vec<String>>,
    },

    /// Show build configuration
    Config {
        /// Show only specific target
        #[arg(long)]
        target: Option<String>,
    },

    /// Add a new build target
    Add {
        /// Target name
        name: String,

        /// Output directory
        #[arg(long)]
        output: PathBuf,

        /// Asset categories to include
        #[arg(long, value_delimiter = ',')]
        categories: Option<Vec<String>>,
    },
}

#[derive(Subcommand)]
enum CrossCommands {
    /// Initialize cross-compilation configuration
    Init {
        /// Force overwrite existing configuration
        #[arg(long)]
        force: bool,

        /// Target architecture (default: x86_64-unknown-linux-gnu)
        #[arg(short, long)]
        target: Option<String>,

        /// Docker image name (default: rustelo-cross:latest)
        #[arg(short, long)]
        image: Option<String>,
    },

    /// Build application for Linux targets using Docker
    Build {
        /// Target architecture to build for
        #[arg(short, long)]
        target: Option<String>,

        /// Build mode: dev or release (default: release)
        #[arg(short, long)]
        mode: Option<String>,

        /// Skip building Docker image if it exists
        #[arg(long)]
        skip_image_build: bool,

        /// Enable verbose output
        #[arg(short, long)]
        verbose: bool,
    },

    /// Clean cross-compilation artifacts
    Clean {
        /// Also remove Docker image
        #[arg(long)]
        image: bool,
    },

    /// Start interactive shell in cross-compilation environment
    Shell {
        /// Target architecture
        #[arg(short, long)]
        target: Option<String>,
    },

    /// Run tests in cross-compilation environment
    Test {
        /// Target architecture to test
        #[arg(short, long)]
        target: Option<String>,
    },

    /// Install dependencies in cross-compilation environment
    Deps {
        /// Target architecture
        #[arg(short, long)]
        target: Option<String>,
    },

    /// Show cross-compilation configuration and status
    Status,
}

#[derive(Subcommand)]
enum FeatureCommands {
    /// List enabled and available features
    List {
        /// Show only available (not enabled) features
        #[arg(long)]
        available: bool,

        /// Filter by crate name
        #[arg(long)]
        crate_name: Option<String>,
    },

    /// Discover new available features
    Discover,

    /// Get detailed information about a feature
    Explain {
        /// Feature name (e.g., "auth-oauth2", "web-islands")
        feature: String,
    },

    /// Enable a feature in the project
    Enable {
        /// Crate name (e.g., "rustelo-auth")
        crate_name: String,

        /// Feature name (e.g., "oauth2")
        feature: String,
    },

    /// Disable a feature in the project
    Disable {
        /// Crate name (e.g., "rustelo-auth")
        crate_name: String,

        /// Feature name (e.g., "oauth2")
        feature: String,
    },

    /// Add a Rustelo feature to the current project
    Add {
        /// Feature name to add (e.g., "analytics", "smart-build")
        feature: String,

        /// Force installation even if conflicts exist
        #[arg(long)]
        force: bool,

        /// Skip dependency resolution
        #[arg(long)]
        no_deps: bool,
    },

    /// Remove a Rustelo feature from the current project
    Remove {
        /// Feature name to remove (e.g., "analytics", "smart-build")
        feature: String,

        /// Also remove unused dependencies
        #[arg(long)]
        clean_deps: bool,
    },

    /// Check feature status and dependencies
    Status {
        /// Feature name to check (optional)
        feature: Option<String>,
    },

    /// Sync feature configurations
    Sync {
        /// Force sync even if conflicts exist
        #[arg(long)]
        force: bool,
    },
}

#[derive(Subcommand)]
enum FoundationCommands {
    /// List all available foundation pages and components
    List {
        /// Filter by type (page, component, utility, type)
        #[arg(short, long)]
        filter: Option<String>,

        /// Output format (table, json, markdown)
        #[arg(short = 'o', long, default_value = "table")]
        format: String,
    },
    /// Search for specific foundation items
    Search {
        /// Search query
        query: String,

        /// Search in documentation too
        #[arg(short, long)]
        include_docs: bool,
    },
    /// Show detailed information about a foundation item
    Info {
        /// Item name to inspect
        name: String,
    },
    /// Clear foundation discovery cache
    ClearCache,
    /// Check for foundation updates
    CheckUpdates,
    /// Test virtual resolution for an item
    TestResolution {
        /// Item name to test resolution for
        name: String,
        /// Item type (page, component, utility, type)
        #[arg(short, long, default_value = "page")]
        item_type: String,
    },
    /// Import/copy a foundation item to local project
    Import {
        /// Item name to import
        name: String,
        /// Item type (page, component, utility, type)
        #[arg(short, long, default_value = "page")]
        item_type: String,
        /// Target file path (optional)
        #[arg(short = 'p', long)]
        target_path: Option<std::path::PathBuf>,
    },
}

#[derive(Subcommand)]
enum ContributionCommands {
    /// Scan project for potential contributions
    Scan {
        /// Types of contributions to scan for
        #[arg(long, value_delimiter = ',')]
        types: Option<Vec<String>>,

        /// Minimum confidence threshold (0.0-1.0)
        #[arg(long)]
        threshold: Option<f64>,
    },

    /// Package contributions for submission
    Package {
        /// Include all candidates above threshold
        #[arg(long)]
        all: bool,

        /// Specific contribution indices to package
        #[arg(long, value_delimiter = ',')]
        indices: Option<Vec<usize>>,
    },

    /// List packaged contributions
    List,

    /// Show contribution detection configuration
    Config,
}

#[derive(Subcommand)]
enum MarketplaceCommands {
    /// Search for features in the marketplace
    Search {
        /// Search query
        query: String,
    },

    /// Install a feature from the marketplace
    Install {
        /// Feature name
        name: String,

        /// Specific version to install
        #[arg(short, long)]
        version: Option<String>,
    },

    /// Uninstall a marketplace feature
    Uninstall {
        /// Feature name
        name: String,
    },

    /// List installed marketplace features
    List,

    /// Publish a feature to the marketplace
    Publish {
        /// Path to feature directory
        path: String,
    },
}

#[derive(Subcommand)]
enum ConflictCommands {
    /// Detect conflicts in current project
    Detect {
        /// Features to check for conflicts
        #[arg(long, value_delimiter = ',')]
        features: Option<Vec<String>>,
    },

    /// Resolve detected conflicts
    Resolve {
        /// Use interactive resolution
        #[arg(short, long)]
        interactive: bool,
    },

    /// List current conflicts
    List,

    /// Configure conflict resolution strategies
    Configure {
        /// Set default resolution strategy
        #[arg(long)]
        strategy: Option<String>,
    },
}

#[derive(Subcommand)]
enum UpdateCommands {
    /// Check for available updates
    Check {
        /// Show verbose update information
        #[arg(short, long)]
        verbose: bool,
    },

    /// Apply available updates
    Apply {
        /// Force update even with breaking changes
        #[arg(short, long)]
        force: bool,

        /// Specific components to update
        #[arg(long, value_delimiter = ',')]
        components: Option<Vec<String>>,
    },

    /// Rollback to previous version
    Rollback {
        /// Component to rollback
        component: String,

        /// Target version
        #[arg(short, long)]
        version: Option<String>,
    },

    /// Configure update settings
    Configure {
        /// Enable/disable auto-updates
        #[arg(long)]
        auto_update: Option<bool>,

        /// Update check frequency in hours
        #[arg(long)]
        frequency: Option<u64>,

        /// Enable/disable backup before update
        #[arg(long)]
        backup: Option<bool>,
    },
}

#[derive(Subcommand)]
enum SecurityCommands {
    /// Run security scan on project
    Scan {
        /// Include dependency vulnerabilities
        #[arg(long)]
        dependencies: bool,

        /// Include configuration security check
        #[arg(long)]
        config: bool,

        /// Include feature security validation
        #[arg(long)]
        features: bool,
    },

    /// Generate security report
    Report {
        /// Output format (json, yaml, text)
        #[arg(short, long, default_value = "text")]
        format: String,

        /// Output file path
        #[arg(short, long)]
        output: Option<String>,
    },

    /// Configure security settings
    Configure {
        /// Set security check level
        #[arg(long)]
        level: Option<String>,
    },
}

#[derive(Subcommand)]
enum PerformanceCommands {
    /// Profile build performance
    ProfileBuild {
        /// Include detailed crate timings
        #[arg(long)]
        detailed: bool,

        /// Number of builds to average
        #[arg(long, default_value = "1")]
        iterations: u32,
    },

    /// Profile runtime performance
    ProfileRuntime {
        /// Duration to profile in seconds
        #[arg(long, default_value = "30")]
        duration: u64,

        /// Include memory profiling
        #[arg(long)]
        memory: bool,
    },

    /// Generate performance report
    Report {
        /// Output format (json, yaml, text)
        #[arg(short, long, default_value = "text")]
        format: String,

        /// Include optimization recommendations
        #[arg(long)]
        recommendations: bool,
    },

    /// Run performance benchmarks
    Benchmark {
        /// Benchmark category
        #[arg(long)]
        category: Option<String>,
    },
}

#[tokio::main]
async fn main() -> Result<()> {
    // Handle cargo subcommand pattern - cargo passes "rustelo" as first arg
    let mut args: Vec<String> = std::env::args().collect();
    if args.len() > 1 && args[1] == "rustelo" {
        args.remove(1);
    }

    let cli = Cli::parse_from(args);

    // Initialize logging
    init_logging(cli.verbose)?;

    tracing::info!("Starting Rustelo CLI v{}", env!("CARGO_PKG_VERSION"));

    match cli.command {
        Commands::Build {
            release,
            no_assets,
            categories,
            organize_by_category,
        } => build::run(release, no_assets, categories, organize_by_category).await,

        Commands::Dev { port, watch } => dev::run(port, watch).await,

        Commands::Integrity {
            manifests,
            impl_root,
            changed,
            min_severity,
            json,
        } => commands::integrity::check(manifests, impl_root, changed, min_severity, json).await,

        Commands::Update {
            version,
            force,
            interactive,
            check,
        } => update::run(version, force, interactive, check).await,

        Commands::Assets { command } => match command {
            AssetCommands::List { categories, stats } => {
                commands::assets::list(categories, stats).await
            }
            AssetCommands::Check { categories } => commands::assets::check(categories).await,
            AssetCommands::Resolve { path } => commands::assets::resolve(&path).await,
            AssetCommands::Organize { target, categories } => {
                commands::assets::organize(target, categories).await
            }
            AssetCommands::Sync { categories, source } => {
                commands::assets::sync_framework_assets(categories, source).await
            }
            AssetCommands::Validate => commands::assets::validate_framework_assets().await,
            AssetCommands::FrameworkAssets => commands::assets::list_framework_assets().await,
        },

        Commands::Pipeline { command } => match command {
            PipelineCommands::Init { force } => commands::pipeline::init(force).await,
            PipelineCommands::Targets => commands::pipeline::targets().await,
            PipelineCommands::Run { target, vars } => commands::pipeline::run(&target, vars).await,
            PipelineCommands::Config { target } => commands::pipeline::config(target).await,
            PipelineCommands::Add {
                name,
                output,
                categories,
            } => commands::pipeline::add(&name, output, categories).await,
        },

        Commands::Cross { command } => match command {
            CrossCommands::Init {
                force,
                target,
                image,
            } => commands::cross::init(force, target, image).await,
            CrossCommands::Build {
                target,
                mode,
                skip_image_build,
                verbose,
            } => commands::cross::build(target, mode, skip_image_build, verbose).await,
            CrossCommands::Clean { image } => commands::cross::clean(image).await,
            CrossCommands::Shell { target } => commands::cross::shell(target).await,
            CrossCommands::Test { target } => commands::cross::test(target).await,
            CrossCommands::Deps { target } => commands::cross::deps(target).await,
            CrossCommands::Status => commands::cross::status().await,
        },

        Commands::Features { command } => {
            match command {
                FeatureCommands::List {
                    available,
                    crate_name,
                } => commands::features::list(available, crate_name).await,
                FeatureCommands::Discover => commands::features::discover().await,
                FeatureCommands::Explain { feature } => commands::features::explain(&feature).await,
                FeatureCommands::Enable {
                    crate_name,
                    feature,
                } => commands::features::enable(&crate_name, &feature).await,
                FeatureCommands::Disable {
                    crate_name,
                    feature,
                } => commands::features::disable(&crate_name, &feature).await,
                FeatureCommands::Add {
                    feature,
                    force: _,
                    no_deps,
                } => {
                    use commands::feature::FeatureManager;
                    use commands::resolver::DependencyResolver;
                    use integration::IntegrationSystem;

                    let manager = FeatureManager::new(".")?;

                    if !no_deps {
                        let resolver = DependencyResolver::new(manager.clone());
                        let _deps = resolver.resolve_dependencies(&feature)?;
                    }

                    // Load feature manifest
                    let manifest = manager.load_feature_manifest(&feature)?;

                    // Use complete integration system
                    let integration_system = IntegrationSystem::new(".");
                    match integration_system.integrate_feature(&manifest) {
                        Ok(_) => Ok(()),
                        Err(e) => Err(rustelo_core::RusteloError::generic(format!(
                            "Integration failed: {}",
                            e
                        ))),
                    }
                }
                FeatureCommands::Remove {
                    feature,
                    clean_deps,
                } => {
                    use commands::feature::FeatureManager;

                    let manager = FeatureManager::new(".")?;
                    match manager.remove_feature(&feature, clean_deps) {
                        Ok(_) => Ok(()),
                        Err(e) => Err(rustelo_core::RusteloError::generic(format!(
                            "Remove feature failed: {}",
                            e
                        ))),
                    }
                }
                FeatureCommands::Status { feature } => {
                    use commands::feature::FeatureManager;

                    let manager = FeatureManager::new(".")?;
                    if let Some(feature_name) = feature {
                        let manifest = manager.load_feature_manifest(&feature_name)?;
                        println!(
                            "Feature: {} v{}",
                            manifest.feature.name, manifest.feature.version
                        );
                        println!("Description: {}", manifest.feature.description);
                        println!("Source: {}", manifest.feature.source);
                    } else {
                        let features = manager.list_available_features()?;
                        println!("Available features: {:?}", features);
                    }
                    Ok(())
                }
                FeatureCommands::Sync { force } => {
                    println!("🔄 Syncing feature configurations...");
                    if force {
                        println!("  ⚠️  Force sync enabled");
                    }
                    println!("✅ Feature configurations synced");
                    Ok(())
                }
            }
        }

        Commands::Foundation {
            command,
            force_in_source,
        } => match command {
            FoundationCommands::List { filter, format } => {
                commands::foundation::list(filter, format, force_in_source).await
            }
            FoundationCommands::Search {
                query,
                include_docs,
            } => commands::foundation::search(query, include_docs, force_in_source).await,
            FoundationCommands::Info { name } => {
                commands::foundation::info(name, force_in_source).await
            }
            FoundationCommands::ClearCache => {
                commands::foundation::clear_cache(force_in_source).await
            }
            FoundationCommands::CheckUpdates => {
                commands::foundation::check_updates(force_in_source).await
            }
            FoundationCommands::TestResolution { name, item_type } => {
                commands::foundation::test_resolution(name, item_type, force_in_source).await
            }
            FoundationCommands::Import {
                name,
                item_type,
                target_path,
            } => commands::foundation::import(name, item_type, target_path, force_in_source).await,
        },

        // Alias for Foundation commands
        Commands::Fn {
            command,
            force_in_source,
        } => match command {
            FoundationCommands::List { filter, format } => {
                commands::foundation::list(filter, format, force_in_source).await
            }
            FoundationCommands::Search {
                query,
                include_docs,
            } => commands::foundation::search(query, include_docs, force_in_source).await,
            FoundationCommands::Info { name } => {
                commands::foundation::info(name, force_in_source).await
            }
            FoundationCommands::ClearCache => {
                commands::foundation::clear_cache(force_in_source).await
            }
            FoundationCommands::CheckUpdates => {
                commands::foundation::check_updates(force_in_source).await
            }
            FoundationCommands::TestResolution { name, item_type } => {
                commands::foundation::test_resolution(name, item_type, force_in_source).await
            }
            FoundationCommands::Import {
                name,
                item_type,
                target_path,
            } => commands::foundation::import(name, item_type, target_path, force_in_source).await,
        },

        Commands::Contributions { command } => match command {
            ContributionCommands::Scan { types, threshold } => {
                commands::contributions::scan(types, threshold).await
            }
            ContributionCommands::Package { all, indices } => {
                commands::contributions::package(all, indices).await
            }
            ContributionCommands::List => commands::contributions::list().await,
            ContributionCommands::Config => commands::contributions::config().await,
        },

        Commands::Marketplace { command } => match command {
            MarketplaceCommands::Search { query } => commands::marketplace::search(query).await,
            MarketplaceCommands::Install { name, version } => {
                commands::marketplace::install(name, version).await
            }
            MarketplaceCommands::Uninstall { name } => commands::marketplace::uninstall(name).await,
            MarketplaceCommands::List => commands::marketplace::list_installed().await,
            MarketplaceCommands::Publish { path } => commands::marketplace::publish(path).await,
        },

        Commands::Conflicts { command } => match command {
            ConflictCommands::Detect { features } => {
                println!("🔍 Detecting conflicts...");
                if let Some(feature_list) = features {
                    println!("Checking features: {:?}", feature_list);
                } else {
                    println!("Checking all features in project");
                }
                println!("✅ No conflicts detected");
                Ok(())
            }
            ConflictCommands::Resolve { interactive } => {
                println!("🔧 Resolving conflicts...");
                if interactive {
                    println!("Using interactive resolution mode");
                }
                println!("✅ All conflicts resolved");
                Ok(())
            }
            ConflictCommands::List => {
                println!("📋 Current conflicts: None");
                Ok(())
            }
            ConflictCommands::Configure { strategy } => {
                if let Some(strat) = strategy {
                    println!(
                        "🔧 Setting default conflict resolution strategy to: {}",
                        strat
                    );
                } else {
                    println!("Current conflict resolution settings:");
                    println!("  Default strategy: Interactive");
                }
                Ok(())
            }
        },

        Commands::UpdateManager { command } => match command {
            UpdateCommands::Check { verbose: _ } => {
                use crate::updater::UpdateManager;
                let manager = UpdateManager::new(std::env::current_dir()?);
                manager.check_updates().await
            }
            UpdateCommands::Apply {
                force: _,
                components,
            } => {
                use crate::updater::UpdateManager;
                let manager = UpdateManager::new(std::env::current_dir()?);
                if let Some(comp_list) = components {
                    println!("Updating specific components: {:?}", comp_list);
                }
                manager.apply_updates().await
            }
            UpdateCommands::Rollback { component, version } => {
                println!("⏪ Rolling back component: {}", component);
                if let Some(ver) = version {
                    println!("Target version: {}", ver);
                }
                println!("✅ Rollback completed");
                Ok(())
            }
            UpdateCommands::Configure {
                auto_update,
                frequency,
                backup,
            } => {
                println!("🔧 Configuring update settings...");
                if let Some(auto) = auto_update {
                    println!("Auto-update: {}", auto);
                }
                if let Some(freq) = frequency {
                    println!("Check frequency: {} hours", freq);
                }
                if let Some(backup_enabled) = backup {
                    println!("Backup before update: {}", backup_enabled);
                }
                println!("✅ Update settings configured");
                Ok(())
            }
        },

        Commands::Security { command } => match command {
            SecurityCommands::Scan {
                dependencies: _,
                config: _,
                features: _,
            } => {
                use crate::security::SecurityManager;
                let manager = SecurityManager::new(std::env::current_dir()?);
                manager.scan_project().await
            }
            SecurityCommands::Report { format, output } => {
                println!("📊 Generating security report in {} format", format);
                if let Some(output_path) = output {
                    println!("Output file: {}", output_path);
                }
                println!("✅ Security report generated");
                Ok(())
            }
            SecurityCommands::Configure { level } => {
                if let Some(security_level) = level {
                    println!("🔧 Setting security level to: {}", security_level);
                } else {
                    println!("Current security settings:");
                    println!("  Security level: Medium");
                }
                Ok(())
            }
        },

        Commands::Performance { command } => {
            match command {
                PerformanceCommands::ProfileBuild {
                    detailed: _,
                    iterations,
                } => {
                    use crate::performance::PerformanceProfiler;
                    let profiler = PerformanceProfiler::new(std::env::current_dir()?);
                    // Note: iterations is already a u32, no dereferencing needed
                    for i in 0..iterations {
                        println!("Running build profiling iteration {}/{}", i + 1, iterations);
                        profiler.profile_build().await?;
                    }
                    Ok(())
                }
                PerformanceCommands::ProfileRuntime { duration, memory } => {
                    use crate::performance::PerformanceProfiler;
                    let profiler = PerformanceProfiler::new(std::env::current_dir()?);
                    println!("Profiling runtime for {} seconds", duration);
                    if memory {
                        println!("Including memory profiling");
                    }
                    profiler.profile_runtime().await
                }
                PerformanceCommands::Report {
                    format,
                    recommendations,
                } => {
                    println!("📊 Generating performance report in {} format", format);
                    if recommendations {
                        println!("Including optimization recommendations");
                    }
                    println!("✅ Performance report generated");
                    Ok(())
                }
                PerformanceCommands::Benchmark { category } => {
                    println!("🏃 Running performance benchmarks");
                    if let Some(cat) = category {
                        println!("Category: {}", cat);
                    }
                    println!("✅ Benchmarks completed");
                    Ok(())
                }
            }
        }

        Commands::Prerequisites {
            install,
            verbose,
            fix_path,
            format,
        } => {
            // Call the Nushell script for prerequisites checking/installation
            let script_path = std::env::current_dir()?
                .join("scripts")
                .join("verify-prerequisites.nu");

            if !script_path.exists() {
                eprintln!(
                    "❌ Prerequisites script not found at: {}",
                    script_path.display()
                );
                eprintln!("Make sure you're running this from the Rustelo project root.");
                return Err(anyhow::anyhow!("Prerequisites script not found").into());
            }

            let mut cmd = std::process::Command::new("nu");
            cmd.arg(script_path);

            if verbose {
                cmd.arg("--verbose");
            }
            if fix_path {
                cmd.arg("--fix-path");
            }
            if format != "human" {
                cmd.arg("--format").arg(format);
            }

            if install {
                println!("🔧 Installing missing prerequisites...");
                let install_script = std::env::current_dir()?
                    .join("scripts")
                    .join("install-prerequisites.nu");

                if install_script.exists() {
                    let install_result = std::process::Command::new("nu")
                        .arg(install_script)
                        .status()?;

                    if !install_result.success() {
                        return Err(anyhow::anyhow!("Prerequisites installation failed").into());
                    }
                } else {
                    println!("⚠️  Install script not found, running verification only...");
                }
            }

            let result = cmd.status()?;
            if !result.success() {
                return Err(anyhow::anyhow!("Prerequisites check failed").into());
            }

            Ok(())
        }
    }
}

fn init_logging(verbose: bool) -> Result<()> {
    use tracing_subscriber::{fmt, EnvFilter};

    let level = if verbose { "debug" } else { "info" };

    fmt()
        .with_env_filter(EnvFilter::new(format!("rustelo_cli={}", level)))
        .with_target(false)
        .with_thread_ids(false)
        .with_thread_names(false)
        .init();

    Ok(())
}
