//! Configuration management handler

use anyhow::{anyhow, Context, Result};
use colored::Colorize;
use syntaxis_core::ProjectConfig;
use tools_shared::find_config_path_warn_conflicts;

/// Handler for configuration operations
#[derive(Debug)]
pub struct ConfigHandler;

impl ConfigHandler {
    /// Show project configuration
    pub fn show_config() -> Result<()> {
        let config_path = Self::find_config()?;
        let config = ProjectConfig::load_from_file(&config_path)
            .context("Failed to load project configuration")?;

        println!("⚙️  Project Configuration\n");

        println!("  {}", "Project Settings".bold().underline());
        println!("    Name: {}", config.project.name);
        println!("    Version: {}", config.project.version);
        println!("    Type: {:?}", config.project_type);
        println!("    Mode: {:?}", config.mode);

        println!("\n  {}", "Description".bold().underline());
        println!("    {}", config.project.description);

        println!("\n  {}", "Environment".bold().underline());
        println!("    Primary Language: {}", config.primary_language);
        println!("    Languages: {}", config.languages.join(", "));

        println!("\n  {}", "Current Phase".bold().underline());
        println!("    Phase: {}", format!("{:?}", config.phase).cyan().bold());

        println!("\n  {}", "Tools".bold().underline());
        for (name, tool) in &config.tools.tools {
            let status = if tool.enabled {
                "enabled".green()
            } else {
                "disabled".red()
            };
            println!("    {:<15} {}", name, status);
        }

        println!("\n  {}", "Metadata".bold().underline());
        println!("    Created: {}", config.project.created);
        println!("    Updated: {}", config.project.last_updated);
        println!("    Author: {}", config.project.authors.join(", "));
        println!("    License: {}", config.project.license);

        println!("\n  {}", "Configuration File".bold().underline());
        println!(
            "    Path: {}",
            format!("{}", config_path.display()).dimmed()
        );

        Ok(())
    }

    /// Validate configuration
    pub fn validate_config() -> Result<()> {
        let config_path = Self::find_config()?;
        let config = ProjectConfig::load_from_file(&config_path)
            .context("Failed to load project configuration")?;

        println!("🔍 Validating Configuration...\n");

        println!("  {} Checking project metadata", "•".cyan());
        println!("    ✓ Name: {}", &config.project.name);
        println!("    ✓ Version: {}", &config.project.version);
        println!("    ✓ Type: {:?}", &config.project_type);

        println!("\n  {} Checking phase", "•".cyan());
        println!("    ✓ Current phase: {:?}", config.phase);

        println!("\n  {} Checking tool configuration", "•".cyan());
        let tool_count = config.tools.tools.len();
        let enabled_count = config.tools.tools.iter().filter(|(_, t)| t.enabled).count();
        println!("    ✓ Total tools: {}", tool_count);
        println!("    ✓ Enabled tools: {}", enabled_count);

        println!("\n  {} Validating...", "•".cyan());
        config
            .validate()
            .context("Configuration validation failed")?;
        println!("    ✓ All validation checks passed");

        println!("\n✅ Configuration is valid!");
        println!("  All settings are properly configured and consistent.");

        Ok(())
    }

    // Helper: Find config file
    fn find_config() -> Result<std::path::PathBuf> {
        find_config_path_warn_conflicts("config.toml", None).ok_or_else(|| {
            anyhow!(
                "Configuration not found. Please create:\n\
                 - .project/lifecycle.toml, or\n\
                 - .vapora/lifecycle.toml"
            )
        })
    }
}

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

    #[test]
    fn test_config_handler_creation() {
        let handler = ConfigHandler;
        assert_eq!(format!("{:?}", handler), "ConfigHandler");
    }
}
