//! {{tool_name}} - CLI with shared utilities integration
//!
//! This tool demonstrates best practices for integrating with the Tools ecosystem
//! shared utilities library, including:
//! - Project auto-detection from .project/
//! - Interactive project selection with inquire
//! - Database migration management
//! - XDG directory support
//!
//! # Quick Start
//!
//! ```bash
//! # Build the tool
//! cargo build
//!
//! # Detect current project
//! ./target/debug/{{tool_name_kebab}} detect
//!
//! # Interactively select a project
//! ./target/debug/{{tool_name_kebab}} select-project
//!
//! # Find migration files
//! ./target/debug/{{tool_name_kebab}} find-migrations --path .
//! ```

use anyhow::Result;
use clap::{Parser, Subcommand};
use tools_shared::{detect_project_from_cwd, select_project, SelectableProject, find_migration_files};
use colored::Colorize;

#[derive(Parser)]
#[command(name = "{{tool_name_kebab}}")]
#[command(about = "{{tool_name}} - Your tool description")]
#[command(long_about = r#"{{tool_name}} - Detailed description

FEATURES:
  - Feature 1 description
  - Feature 2 description
  - Feature 3 description

PROJECT DETECTION:
  Automatically detects projects from .project/lifecycle.toml or .vapora/lifecycle.toml
  Use --project flag to override, or run: {{tool_name_kebab}} detect

DIRECTORIES:
  .project/  - Tools installation
  .vapora/         - VAPORA platform configuration
  .coder/          - Project tracking & agent interaction
  .claude/         - Claude Code integration
"#)]
#[command(version)]
struct Cli {
    /// Project name (auto-detected if omitted)
    #[arg(short = 'p', long, global = true)]
    project: Option<String>,

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

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

#[derive(Subcommand)]
enum Commands {
    /// Your main feature/command
    Main {
        /// Input description
        #[arg(default_value = ".")]
        path: String,
    },

    /// Detect current project from .project/lifecycle.toml
    ///
    /// Demonstrates shared project detection utility
    Detect,

    /// Interactively select a project
    ///
    /// Demonstrates shared project selection utility
    SelectProject,

    /// Find migration files in data/migration/
    ///
    /// Demonstrates shared database migration utility
    FindMigrations {
        /// Root path to search for migrations (default: current directory)
        #[arg(long, default_value = ".")]
        path: String,
    },
}

#[tokio::main]
async fn main() -> Result<()> {
    let cli = Cli::parse();

    // Initialize logging
    if cli.verbose {
        tracing_subscriber::fmt()
            .with_max_level(tracing::Level::DEBUG)
            .init();
    }

    // Handle commands that don't need expensive initialization
    match &cli.command {
        Commands::Detect => {
            detect_current_project();
            return Ok(());
        }
        Commands::SelectProject => {
            select_project_interactive().await?;
            return Ok(());
        }
        Commands::FindMigrations { path } => {
            find_migrations(path)?;
            return Ok(());
        }
        _ => {}
    }

    // For other commands, you would initialize your tool's state here
    // (database, config, etc.)

    match cli.command {
        Commands::Main { path } => {
            main_command(&path)?;
        }
        // Handled above with early return
        Commands::Detect | Commands::SelectProject | Commands::FindMigrations { .. } => {
            unreachable!("These commands should be handled in the early return block");
        }
    }

    Ok(())
}

/// Your main command implementation
fn main_command(path: &str) -> Result<()> {
    println!("Processing: {}", path);
    // Your implementation here
    Ok(())
}

/// Demonstrate project auto-detection
fn detect_current_project() {
    println!("{}\\n", "🔍 Detecting Current Project".cyan().bold());

    match detect_project_from_cwd("config.toml") {
        Some(project) => {
            println!("  {} Project detected!", "✅".green());
            println!("  {:<15} {}", "Name:", project.name.cyan());
            println!("  {:<15} {}", "Config:", project.config_path.display());
            println!("  {:<15} {}", "Root:", project.root_path.display());
        }
        None => {
            println!("  {} No project detected", "✗".red());
            println!("\\n  To create a project here, run:");
            println!("    project-lifecycle init .");
        }
    }
}

/// Demonstrate interactive project selection
async fn select_project_interactive() -> Result<()> {
    println!("{}\\n", "🔍 Selecting Project".cyan().bold());

    // Create sample projects for demo
    let projects = vec![
        SelectableProject {
            id: "proj-1".to_string(),
            name: "Project Alpha".to_string(),
            path: Some("~/projects/alpha".to_string()),
            metadata: Some("Status: Active".to_string()),
        },
        SelectableProject {
            id: "proj-2".to_string(),
            name: "Project Beta".to_string(),
            path: Some("~/projects/beta".to_string()),
            metadata: Some("Status: Active".to_string()),
        },
        SelectableProject {
            id: "proj-3".to_string(),
            name: "Project Gamma".to_string(),
            path: Some("~/projects/gamma".to_string()),
            metadata: Some("Status: Archived".to_string()),
        },
    ];

    match select_project(projects, "Select a project:", None) {
        Ok(selected_id) => {
            println!("\\n  {} Selected: {}", "✅".green(), selected_id.cyan());
        }
        Err(e) => {
            println!("  {} Selection cancelled: {}", "✗".red(), e);
        }
    }

    Ok(())
}

/// Demonstrate migration file discovery
fn find_migrations(path: &str) -> Result<()> {
    println!("{}\\n", "🔍 Finding Migration Files".cyan().bold());

    match find_migration_files(path) {
        Ok(migrations) => {
            if migrations.is_empty() {
                println!("  {} No migration files found", "ℹ️ ".normal());
            } else {
                println!("  {} Found {} migration file(s):", "✅".green(), migrations.len());
                for (idx, migration) in migrations.iter().enumerate() {
                    if let Some(file_name) = migration.file_name() {
                        if let Some(name) = file_name.to_str() {
                            println!("    {}. {}", idx + 1, name.cyan());
                        }
                    }
                }
            }
        }
        Err(e) => {
            println!("  {} Error: {}", "✗".red(), e);
        }
    }

    Ok(())
}

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

    #[test]
    fn test_main_command() {
        assert!(main_command(".").is_ok());
    }
}
