use colored::Colorize;
use lmrc_config_validator::LmrcConfig;
use std::path::PathBuf;

use crate::error::{CliError, Result};
use crate::generator::ProjectGenerator;
use crate::prompts::InteractivePrompt;

pub async fn execute(
    name: Option<String>,
    path: Option<String>,
    config: Option<String>,
) -> Result<()> {
    println!("{}\n", "Creating new LMRC Stack project...".green().bold());

    // Determine project configuration
    let mut project_config = if let Some(config_path) = config {
        // Load from config file
        println!("Loading configuration from: {}", config_path.cyan());
        let config_file = PathBuf::from(&config_path);
        LmrcConfig::from_file(&config_file)?
    } else {
        // Run interactive prompts
        InteractivePrompt::run()?
    };

    // Override project name if provided as argument
    if let Some(name) = name {
        project_config.project.name = name;
    }

    // Determine target path
    let target_path = if let Some(p) = path {
        PathBuf::from(p)
    } else {
        std::env::current_dir()?
    };

    let project_path = target_path.join(&project_config.project.name);

    // Check if project already exists
    if project_path.exists() {
        return Err(CliError::ProjectExists(project_path.display().to_string()));
    }

    println!(
        "\n{} {}",
        "Creating project at:".green(),
        project_path.display().to_string().cyan()
    );

    // Generate project structure
    let generator = ProjectGenerator::new(project_config, project_path);
    generator.generate().await?;

    println!("\n{}", "Project created successfully!".green().bold());
    println!("\nNext steps:");
    println!("  1. cd {}", generator.project_path().display());
    println!("  2. Review and update the configuration in lmrc.toml");
    println!("  3. Configure GitLab CI/CD variables (see docs/SECRETS.md)");
    println!("  4. Run: cargo build");
    println!("\nFor more information, see docs/README.md\n");

    Ok(())
}
