//! Implementation initialization command with remote templates and requirement checking

use crate::commands::remote::{
    RemoteAssetFetcher, RemoteAssetSource, RequirementCheckResult, TemplateVariant,
};
use crate::embedded::apply_template_vars;
use chrono::Utc;
use rustelo_core::{Result, RusteloError};
use serde::{Deserialize, Serialize};
use serde_json;
use std::collections::HashMap;
use std::fs;
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use toml;
use walkdir::WalkDir;

#[cfg(feature = "generate")]
use tera::{Context, Tera};

/// Asset configuration for project creation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AssetConfiguration {
    pub source: String,
    pub download_location: String,
    pub framework_path: Option<String>,
    pub cache_enabled: bool,
    pub auto_update: bool,
    pub notification_methods: Vec<String>,
}

/// Dependency configuration for local development
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DependencyConfig {
    /// Use local path dependencies instead of git
    pub use_local_paths: Option<bool>,
    /// Base path to rustelo framework
    pub rustelo_path: Option<String>,
    /// Rustelo framework configuration
    pub rustelo: Option<RusteloDepConfig>,
    /// Specific dependency overrides
    pub overrides: Option<std::collections::HashMap<String, DependencyOverride>>,
}

/// Rustelo framework dependency configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RusteloDepConfig {
    /// Source type: "local", "git", or "crates.io"
    pub source: Option<String>,
    /// Base path for local dependencies
    pub base_path: Option<String>,
}

/// Individual dependency override
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DependencyOverride {
    /// Local path to the dependency
    pub path: Option<String>,
    /// Git repository URL
    pub git: Option<String>,
    /// Version specification
    pub version: Option<String>,
    /// Branch for git dependencies
    pub branch: Option<String>,
}

/// Configuration file structure for non-interactive initialization
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InitConfig {
    /// Template to use for initialization
    pub template: Option<String>,
    /// Asset configuration settings
    pub assets: AssetConfiguration,
    /// Directory handling when target exists
    pub existing_directory_action: Option<String>, // "merge", "replace", "cancel"
    /// Skip all confirmations (assume yes)
    pub auto_confirm: Option<bool>,
    /// Dependency configuration
    pub dependencies: Option<DependencyConfig>,
}

/// Initialize a new Rustelo implementation with interactive configuration
pub async fn run(
    name: String,
    path: Option<PathBuf>,
    template: String,
    config_file: Option<PathBuf>,
    local_deps: bool,
    rustelo_path: String,
) -> Result<()> {
    println!("🎯 **Rustelo Implementation Setup**");
    println!();

    // Load configuration file if provided
    let config = if let Some(config_path) = config_file {
        println!("📄 Loading configuration from: {}", config_path.display());
        load_config_file(&config_path)?
    } else {
        None
    };

    // Determine template to use
    let selected_template = if let Some(ref cfg) = config {
        // Use template from config file or default
        cfg.template.clone().unwrap_or(template)
    } else if template == "basic" {
        // Show available templates and let user choose
        select_template_interactive(&rustelo_path).await?
    } else {
        // Validate specified template
        if is_valid_template(&template, &rustelo_path).await? {
            template
        } else {
            println!(
                "⚠️  Template '{}' not found. Let's choose from available templates:",
                template
            );
            select_template_interactive(&rustelo_path).await?
        }
    };

    // Get template information and check requirements
    let template_info = get_template_info(&selected_template, &rustelo_path).await?;
    println!("\n📋 **Selected Template: {}**", template_info.display_name);
    println!("{}", template_info.description);
    println!(
        "⏱️  Estimated setup time: {}",
        template_info.estimated_setup_time
    );

    // Check requirements
    let requirements_result = check_template_requirements(&template_info).await?;

    if !requirements_result.satisfied {
        println!("\n❌ **Missing Requirements**:");
        for req in &requirements_result.missing_requirements {
            println!("  • {}", req);
        }

        if !prompt_user("\nDo you want to continue anyway?")? {
            println!("Setup cancelled. Please install missing requirements and try again.");
            return Ok(());
        }
    }

    if !requirements_result.warnings.is_empty() {
        println!("\n⚠️  **Warnings**:");
        for warning in &requirements_result.warnings {
            println!("  • {}", warning);
        }
    }

    if !requirements_result.suggestions.is_empty() {
        println!("\n💡 **Suggestions**:");
        for suggestion in &requirements_result.suggestions {
            println!("  • {}", suggestion);
        }
    }

    // Asset configuration - use config file, rustelo_path, or interactive
    let asset_config = if let Some(ref cfg) = config {
        println!("📦 Using asset configuration from config file");
        cfg.assets.clone()
    } else if rustelo_path != "./rustelo" {
        // If user specified a custom --rustelo-path, use it automatically without prompting
        println!("📦 Using local templates from: {}", rustelo_path);
        AssetConfiguration {
            source: "local".to_string(),
            framework_path: Some(rustelo_path.clone()),
            download_location: ".rustelo-assets/".to_string(),
            cache_enabled: true,
            auto_update: true,
            notification_methods: vec!["console".to_string()],
        }
    } else {
        configure_assets_interactive(&name).await?
    };

    println!("\n🚀 **Starting project creation...**");

    // Create the project
    let project_path = create_project_with_template(
        &name,
        &path,
        &selected_template,
        &asset_config,
        config.as_ref(),
        local_deps,
        &rustelo_path,
    )
    .await?;

    // Save configuration (always)
    save_rustelo_config(&project_path, &name, &selected_template, &asset_config)?;

    // Generate final documentation and summary
    generate_setup_summary(&project_path, &selected_template, &asset_config).await?;

    println!(
        "✅ **Rustelo implementation '{}' created successfully!**",
        name
    );
    println!();
    println!("📁 **Project location**: {}", project_path.display());
    println!("🏷️  **Template**: {}", selected_template);
    println!("🎨 **Asset source**: {}", asset_config.source);
    println!();
    println!("🚀 **Next steps**:");
    println!("  1. cd {}", project_path.display());
    println!("  2. just setup    # Install dependencies");
    println!("  3. just dev      # Start development server");
    println!();
    println!("📚 **Documentation**: Check RUSTELO-HOWTO.md in your project");
    println!("💡 **Features**: Run 'cargo rustelo features discover' to see available features");
    println!();
    println!("Happy coding! 🦀✨");

    Ok(())
}

/// Interactive template selection
async fn select_template_interactive(rustelo_path: &str) -> Result<String> {
    // Get available templates from local or remote source
    let templates = get_available_templates(Some(rustelo_path)).await?;

    loop {
        println!("🎨 **Available Template Variants**:");

        // Display simplified template list
        for (i, template) in templates.iter().enumerate() {
            println!("{}. {}", i + 1, template.display_name);
        }

        println!("\n💡 **Choose an option**:");
        println!(
            "   • Enter a number (1-{}) to select a template",
            templates.len()
        );
        println!("   • Enter 'details' or 'd' to see detailed information about all templates");
        println!("   • Enter 'help' or 'h' for more information");

        print!("\nChoice: ");
        io::stdout().flush().map_err(RusteloError::Io)?;

        let mut input = String::new();
        io::stdin()
            .read_line(&mut input)
            .map_err(RusteloError::Io)?;
        let choice = input.trim().to_lowercase();

        // Handle help request
        if choice == "h" || choice == "help" {
            println!("\n📚 **Template Selection Help**:");
            println!(
                "   • Numbers 1-{}: Select that template directly",
                templates.len()
            );
            println!("   • 'details'/'d': Show detailed information about each template");
            println!("   • 'help'/'h': Show this help message");
            println!("   • Templates include features like auth, content management, etc.");
            println!("   • You can always change features later with 'cargo rustelo features'");
            continue;
        }

        // Handle detailed view request
        if choice == "d" || choice == "details" {
            println!("\n📋 **Detailed Template Information**:");

            for (i, template) in templates.iter().enumerate() {
                let icon = template.icon.as_deref().unwrap_or("📦");
                println!("\n{}. {} {}", i + 1, icon, template.display_name);
                println!("   📝 Description: {}", template.description);
                println!("   🎯 Use cases: {}", template.use_cases.join(", "));
                println!(
                    "   ⚡ Complexity: {} | ⏱️  Setup time: {}",
                    template.complexity, template.estimated_setup_time
                );

                // Show requirements summary
                let mut requirements = Vec::new();
                if let Some(node_ver) = &template.requirements.node_version {
                    requirements.push(format!("Node.js {}", node_ver));
                }
                if let Some(rust_ver) = &template.requirements.rust_version {
                    requirements.push(format!("Rust {}", rust_ver));
                }
                for dep in &template.requirements.system_dependencies {
                    requirements.push(dep.clone());
                }

                if !requirements.is_empty() {
                    println!("   🔧 Requirements: {}", requirements.join(", "));
                }
            }

            println!("\n📚 **For more information**, visit: https://docs.rustelo.dev/templates");
            println!("\n💡 Enter the number of your preferred template:");
            print!("Selection (1-{}): ", templates.len());
            io::stdout().flush().map_err(RusteloError::Io)?;

            let mut selection_input = String::new();
            io::stdin()
                .read_line(&mut selection_input)
                .map_err(RusteloError::Io)?;

            if let Ok(selection) = selection_input.trim().parse::<usize>() {
                if (1..=templates.len()).contains(&selection) {
                    return Ok(templates[selection - 1].name.clone());
                }
            }

            println!("❌ Invalid selection. Please try again.");
            continue;
        }

        // Handle direct template selection
        if let Ok(selection) = choice.parse::<usize>() {
            if (1..=templates.len()).contains(&selection) {
                return Ok(templates[selection - 1].name.clone());
            }
        }

        println!(
            "❌ Invalid input '{}'. Please enter a number 1-{}, 'details', or 'help'.",
            choice,
            templates.len()
        );
    }
}

/// Configure assets interactively
async fn configure_assets_interactive(_project_name: &str) -> Result<AssetConfiguration> {
    println!("\n⚙️  **Asset Configuration**");

    // Template source selection - where to get templates FROM
    println!("\n📥 Template source - where to get templates from:");

    // Check for current environment variable
    let current_source = std::env::var("RUSTELO_ASSET_SOURCE").ok();
    let current_display = match &current_source {
        Some(source) if source.starts_with("file://") => {
            format!(
                "Current: Local ({})",
                source.strip_prefix("file://").unwrap_or(source)
            )
        }
        Some(source) if source.starts_with("http") => {
            format!("Current: Remote ({})", source)
        }
        Some(source) => {
            format!("Current: Local path ({})", source)
        }
        None => "Current: Default remote".to_string(),
    };

    println!("   {}", current_display);
    println!("   1. Remote (GitHub: https://github.com/your-org/rustelo)");
    println!("   2. Local framework development (../rustelo)");
    println!("   3. Custom URL");
    println!("   4. Keep current setting [default]");
    print!("Choice (1-4, Enter=4): ");
    io::stdout().flush().map_err(RusteloError::Io)?;

    let mut source_input = String::new();
    io::stdin()
        .read_line(&mut source_input)
        .map_err(RusteloError::Io)?;
    let source_choice = source_input.trim();

    let (source, framework_path) = match source_choice {
        "1" => ("remote".to_string(), None),
        "2" => ("local".to_string(), Some("../rustelo".to_string())),
        "3" => {
            print!("Enter custom URL: ");
            io::stdout().flush().map_err(RusteloError::Io)?;
            let mut custom_url = String::new();
            io::stdin()
                .read_line(&mut custom_url)
                .map_err(RusteloError::Io)?;
            (custom_url.trim().to_string(), None)
        }
        "4" | "" => {
            // Keep current setting
            match current_source {
                Some(source) if source.starts_with("file://") => (
                    "local".to_string(),
                    Some(source.strip_prefix("file://").unwrap().to_string()),
                ),
                Some(source) if source.starts_with("http") => (source, None),
                Some(source) => ("local".to_string(), Some(source)),
                None => ("remote".to_string(), None),
            }
        }
        _ => ("remote".to_string(), None),
    };

    // Download location selection - where to store assets in the project
    println!("\n📁 Download location - where to store assets in your project:");
    println!("   1. .rustelo-assets/ (recommended)");
    println!("   2. ./templates/");
    println!("   3. Custom path");
    print!("Choice (1-3, Enter=1): ");
    io::stdout().flush().map_err(RusteloError::Io)?;

    let mut input = String::new();
    io::stdin()
        .read_line(&mut input)
        .map_err(RusteloError::Io)?;
    let choice = input.trim();

    let download_location = match choice {
        "1" | "" => ".rustelo-assets".to_string(),
        "2" => "templates".to_string(),
        "3" => {
            print!("Enter custom path: ");
            io::stdout().flush().map_err(RusteloError::Io)?;
            let mut custom_path = String::new();
            io::stdin()
                .read_line(&mut custom_path)
                .map_err(RusteloError::Io)?;
            custom_path.trim().to_string()
        }
        _ => ".rustelo-assets".to_string(),
    };

    // Update mode selection
    println!("\n🔄 How should assets be updated?");
    println!("   1. Manual (you control all updates)");
    println!("   2. Prompt (ask before updating)");
    println!("   3. Automatic (update on build) [default]");
    print!("Choice (1-3, Enter=3): ");
    io::stdout().flush().map_err(RusteloError::Io)?;

    let mut update_input = String::new();
    io::stdin()
        .read_line(&mut update_input)
        .map_err(RusteloError::Io)?;
    let update_choice = update_input.trim();

    let auto_update = match update_choice {
        "1" => false,
        "2" => false,
        "3" | "" => true, // Default to automatic
        _ => true,
    };

    // Notification preferences
    println!("\n📢 Update notifications:");
    let console_notify = prompt_user("Enable console output? [Y/n]")?;
    let file_notify = prompt_user("Enable file notifications (.rustelo-updates.json)? [y/N]")?;
    let webhook_notify = prompt_user("Enable webhook notifications? [y/N]")?;

    let mut notification_methods = Vec::new();
    if console_notify {
        notification_methods.push("console".to_string());
    }
    if file_notify {
        notification_methods.push("file".to_string());
    }
    if webhook_notify {
        notification_methods.push("webhook".to_string());
    }

    // Configuration will be saved automatically to enable framework features
    println!("✅ Configuration will be saved to rustelo-deps.toml");

    let asset_config = AssetConfiguration {
        source,
        download_location,
        framework_path,
        cache_enabled: true,
        auto_update,
        notification_methods,
    };

    // Configuration will be saved automatically
    Ok(asset_config)
}

/// Create project with selected template and configuration
async fn create_project_with_template(
    name: &str,
    path: &Option<PathBuf>,
    template: &str,
    asset_config: &AssetConfiguration,
    config: Option<&InitConfig>,
    local_deps: bool,
    rustelo_path: &str,
) -> Result<PathBuf> {
    let project_path = path.clone().unwrap_or_else(|| PathBuf::from(name));

    // Handle existing directory
    if project_path.exists() {
        if !handle_existing_directory(&project_path, config)? {
            return Err(RusteloError::generic("Operation cancelled by user"));
        }
    } else {
        // Create project directory if it doesn't exist
        fs::create_dir_all(&project_path).map_err(RusteloError::Io)?;
    }

    // Download and apply template
    if asset_config.source == "remote" {
        download_remote_template(template, &project_path, asset_config).await?;
    } else if asset_config.source == "local" {
        copy_local_template(template, &project_path, asset_config).await?;
    } else {
        // Custom URL or fallback to embedded
        download_custom_template(template, &project_path, asset_config).await?;
    }

    // Apply template variables
    apply_template_variables(&project_path, name, template, asset_config)?;

    // Generate Cargo.toml
    generate_cargo_toml(
        &project_path,
        name,
        template,
        asset_config,
        config.cloned(),
        local_deps,
        rustelo_path,
    )?;

    // Create local overrides directory
    create_local_overrides(&project_path, name, template, asset_config)?;

    Ok(project_path)
}

/// Download template from remote source
async fn download_remote_template(
    template: &str,
    project_path: &Path,
    asset_config: &AssetConfiguration,
) -> Result<()> {
    println!("📡 Downloading template from source...");

    // Check environment variable or use default
    let base_url = if let Ok(source) = std::env::var("RUSTELO_ASSET_SOURCE") {
        if source.starts_with("http") || source.starts_with("file://") {
            source
        } else {
            let path = PathBuf::from(&source);
            if path.exists() {
                let absolute_path = path.canonicalize().unwrap_or(path);
                format!("file://{}", absolute_path.display())
            } else {
                "https://raw.githubusercontent.com/your-org/rustelo/main/templates".to_string()
            }
        }
    } else {
        "https://raw.githubusercontent.com/your-org/rustelo/main/templates".to_string()
    };

    let remote_config = RemoteAssetSource {
        base_url,
        template_variant: Some(template.to_string()),
        cache_enabled: asset_config.cache_enabled,
        cache_ttl_hours: 24,
        cache_directory: PathBuf::from(&asset_config.download_location),
        fallback_to_embedded: true,
        requirements_check: true,
    };

    let fetcher = RemoteAssetFetcher::new(remote_config);

    // Get template variant info for asset-based download
    let template_variants = fetcher.discover_templates().await?;
    let template_variant = template_variants
        .into_iter()
        .find(|t| t.name == template)
        .ok_or_else(|| RusteloError::generic(format!("Template '{}' not found", template)))?;

    let result = fetcher
        .download_template_with_assets(&template_variant, project_path)
        .await?;

    println!(
        "✅ Downloaded {} files ({} from cache, {} templates processed)",
        result.total_files,
        result.cached_files.len(),
        result.template_files_processed.len()
    );

    Ok(())
}

/// Copy template from local framework development
async fn copy_local_template(
    template: &str,
    project_path: &Path,
    asset_config: &AssetConfiguration,
) -> Result<()> {
    println!("📁 Copying template from local framework...");

    let framework_path = asset_config
        .framework_path
        .as_ref()
        .ok_or_else(|| RusteloError::generic("Local framework path not configured"))?;

    // If framework_path already ends with "templates", don't add it again
    let template_path = if framework_path.ends_with("templates") {
        PathBuf::from(framework_path).join(template)
    } else {
        // For framework_path = ".", look in ../rustelo/templates relative to current dir
        if framework_path == "." {
            PathBuf::from("../rustelo").join("templates").join(template)
        } else {
            PathBuf::from(framework_path)
                .join("templates")
                .join(template)
        }
    };

    if !template_path.exists() {
        return Err(RusteloError::generic(format!(
            "Template '{}' not found at {}",
            template,
            template_path.display()
        )));
    }

    // Create template variables for processing
    let project_name = project_path
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or("rustelo-project");

    let mut template_vars = std::collections::HashMap::new();
    template_vars.insert("project_name".to_string(), project_name.to_string());
    template_vars.insert("project_author".to_string(), "Developer".to_string()); // TODO: Get from git config
    template_vars.insert("author".to_string(), "Developer".to_string()); // For justfile templates

    // Add assets configuration for template access
    template_vars.insert(
        "download_location".to_string(),
        asset_config.download_location.clone(),
    );

    // Add dependencies configuration for template access
    template_vars.insert(
        "dependencies.rustelo_path".to_string(),
        asset_config
            .framework_path
            .as_deref()
            .unwrap_or("../rustelo")
            .to_string(),
    );

    // Copy template files with variable processing
    copy_directory_with_vars(&template_path, project_path, &template_vars)?;

    println!("✅ Template copied from local framework");
    Ok(())
}

/// Download from custom URL or fallback to embedded
async fn download_custom_template(
    template: &str,
    project_path: &Path,
    asset_config: &AssetConfiguration,
) -> Result<()> {
    if asset_config.source.starts_with("http") {
        println!("🌐 Downloading from custom URL: {}", asset_config.source);

        let remote_config = RemoteAssetSource {
            base_url: asset_config.source.clone(),
            template_variant: Some(template.to_string()),
            cache_enabled: asset_config.cache_enabled,
            cache_ttl_hours: 24,
            cache_directory: PathBuf::from(&asset_config.download_location),
            fallback_to_embedded: true,
            requirements_check: true,
        };

        let fetcher = RemoteAssetFetcher::new(remote_config);

        // Get template variant info for asset-based download
        let template_variants = fetcher.discover_templates().await?;
        let template_variant = template_variants
            .into_iter()
            .find(|t| t.name == template)
            .ok_or_else(|| RusteloError::generic(format!("Template '{}' not found", template)))?;

        let result = fetcher
            .download_template_with_assets(&template_variant, project_path)
            .await?;

        println!(
            "✅ Downloaded {} files from custom source",
            result.total_files
        );
    } else {
        println!("📦 Using embedded template...");
        create_embedded_template(template, project_path)?;
    }

    Ok(())
}

/// Generate setup summary documentation using Tera templates
async fn generate_setup_summary(
    project_path: &Path,
    template: &str,
    asset_config: &AssetConfiguration,
) -> Result<()> {
    let project_name = project_path
        .file_name()
        .unwrap()
        .to_string_lossy()
        .to_string();

    let content =
        load_and_render_tera_template("setup-summary.md", &project_name, template, asset_config)?;

    fs::write(project_path.join("SETUP-SUMMARY.md"), content).map_err(RusteloError::Io)?;
    println!("📄 Created SETUP-SUMMARY.md from Tera template");

    Ok(())
}

// Helper functions...

/// Check if a template is valid
async fn is_valid_template(template: &str, rustelo_path: &str) -> Result<bool> {
    let templates = get_available_templates(Some(rustelo_path)).await?;
    Ok(templates.iter().any(|t| t.name == template))
}

/// Get template information
async fn get_template_info(template: &str, rustelo_path: &str) -> Result<TemplateVariant> {
    let templates = get_available_templates(Some(rustelo_path)).await?;
    templates
        .into_iter()
        .find(|t| t.name == template)
        .ok_or_else(|| RusteloError::generic(format!("Template '{}' not found", template)))
}

/// Get available templates (with fallback)
async fn get_available_templates(rustelo_path: Option<&str>) -> Result<Vec<TemplateVariant>> {
    // Priority order: 1. Provided rustelo_path, 2. Environment variable, 3. Default paths, 4. Remote
    let base_url = if let Some(provided_path) = rustelo_path {
        // Use provided rustelo_path - highest priority
        let template_path = PathBuf::from(provided_path).join("templates");
        if template_path.exists() {
            let absolute_path = template_path.canonicalize().unwrap_or(template_path);
            format!("file://{}", absolute_path.display())
        } else {
            return Err(RusteloError::generic(format!(
                "Templates not found at: {}",
                template_path.display()
            )));
        }
    } else if let Ok(source) = std::env::var("RUSTELO_ASSET_SOURCE") {
        // Environment variable takes precedence when no path provided
        if source.starts_with("http") || source.starts_with("file://") {
            source
        } else {
            // Assume it's a local path
            let path = PathBuf::from(&source);
            if path.exists() {
                let absolute_path = path.canonicalize().unwrap_or(path);
                format!("file://{}", absolute_path.display())
            } else {
                return Err(RusteloError::generic(format!(
                    "RUSTELO_ASSET_SOURCE path does not exist: {}",
                    source
                )));
            }
        }
    } else {
        // Try multiple possible local paths
        let possible_paths = vec![
            PathBuf::from("/Users/Akasha/Development/evol-rustelo/rustelo/templates"),
            PathBuf::from("../rustelo/templates"),
            PathBuf::from("../../rustelo/templates"),
            PathBuf::from("./templates"),
        ];

        let mut local_path = None;
        for path in possible_paths {
            if path.exists() {
                local_path = Some(path);
                break;
            }
        }

        if let Some(path) = local_path {
            // Use local templates if available
            let absolute_path = path.canonicalize().unwrap_or(path);
            format!("file://{}", absolute_path.display())
        } else {
            // Fall back to remote
            "https://raw.githubusercontent.com/your-org/rustelo/main/templates".to_string()
        }
    };

    let remote_config = RemoteAssetSource {
        base_url: base_url.clone(),
        template_variant: None,
        cache_enabled: !base_url.starts_with("file://"),
        cache_ttl_hours: 24,
        cache_directory: PathBuf::from(".rustelo-cache"),
        fallback_to_embedded: true,
        requirements_check: true,
    };

    let fetcher = RemoteAssetFetcher::new(remote_config);
    match fetcher.discover_templates().await {
        Ok(templates) => Ok(templates),
        Err(_) => {
            // Fallback to basic embedded template
            Ok(vec![TemplateVariant {
                name: "basic".to_string(),
                display_name: "Basic".to_string(),
                description: "Standard web application template".to_string(),
                icon: Some("🏗️".to_string()),
                complexity: "simple".to_string(),
                use_cases: vec!["websites".to_string()],
                requirements: crate::commands::remote::TemplateRequirements {
                    node_version: Some(">=18.0.0".to_string()),
                    rust_version: Some(">=1.70.0".to_string()),
                    system_dependencies: vec!["git".to_string()],
                    optional_dependencies: vec![],
                    framework_features: vec!["rustelo-web".to_string()],
                    minimum_disk_space_mb: Some(500),
                    supported_platforms: vec![
                        "linux".to_string(),
                        "macos".to_string(),
                        "windows".to_string(),
                    ],
                },
                estimated_setup_time: "5 minutes".to_string(),
                assets: None, // Fallback template has no assets configuration
            }])
        }
    }
}

/// Check template requirements
async fn check_template_requirements(template: &TemplateVariant) -> Result<RequirementCheckResult> {
    let remote_config = RemoteAssetSource {
        base_url: "".to_string(),
        template_variant: None,
        cache_enabled: false,
        cache_ttl_hours: 0,
        cache_directory: PathBuf::new(),
        fallback_to_embedded: true,
        requirements_check: true,
    };

    let fetcher = RemoteAssetFetcher::new(remote_config);
    fetcher.check_requirements(&template.requirements).await
}

/// Apply template variables to all files
fn apply_template_variables(
    project_path: &Path,
    name: &str,
    template: &str,
    asset_config: &AssetConfiguration,
) -> Result<()> {
    let mut vars = HashMap::new();
    vars.insert("project_name".to_string(), name.to_string());
    vars.insert("project_name_snake".to_string(), name.replace('-', "_"));
    vars.insert("template_variant".to_string(), template.to_string());
    vars.insert("asset_source".to_string(), asset_config.source.clone());
    vars.insert(
        "download_location".to_string(),
        asset_config.download_location.clone(),
    );
    vars.insert("generation_timestamp".to_string(), Utc::now().to_rfc3339());
    vars.insert(
        "rustelo_version".to_string(),
        env!("CARGO_PKG_VERSION").to_string(),
    );

    // Process all template files
    for entry in WalkDir::new(project_path) {
        let entry = entry.map_err(|e| RusteloError::generic(format!("Walk error: {}", e)))?;

        if entry.file_type().is_file() {
            let path = entry.path();
            if let Some(ext) = path.extension() {
                if ext == "template" {
                    // Process template file
                    let content = fs::read_to_string(path).map_err(RusteloError::Io)?;
                    let processed = apply_template_vars(&content, &vars);

                    // Remove .template extension and write
                    let new_path = path.with_extension("");
                    fs::write(&new_path, processed).map_err(RusteloError::Io)?;
                    fs::remove_file(path).map_err(RusteloError::Io)?;
                }
            }
        }
    }

    Ok(())
}

/// Generate Cargo.toml based on configuration and template type
fn generate_cargo_toml(
    project_path: &Path,
    name: &str,
    template: &str,
    asset_config: &AssetConfiguration,
    config: Option<InitConfig>,
    cli_local_deps: bool,
    cli_rustelo_path: &str,
) -> Result<()> {
    // Extract project name from path if it contains path separators
    let project_name = if name.contains('/') || name.contains('\\') {
        project_path
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or(name)
    } else {
        name
    };

    // Determine if this template needs workspace structure
    let needs_workspace = matches!(
        template,
        "cms" | "enterprise" | "saas" | "ecommerce" | "ai-powered"
    );

    if needs_workspace {
        generate_workspace_cargo_toml(
            project_path,
            project_name,
            template,
            asset_config,
            &config,
            cli_local_deps,
            cli_rustelo_path,
        )
    } else {
        generate_single_crate_cargo_toml(
            project_path,
            project_name,
            asset_config,
            &config,
            cli_local_deps,
            cli_rustelo_path,
        )
    }
}

/// Generate rustelo framework dependencies based on configuration
fn generate_rustelo_dependencies(
    config: &Option<InitConfig>,
    cli_local_deps: bool,
    cli_rustelo_path: &str,
) -> String {
    // Check if we should use local dependencies (CLI overrides config)
    let use_local = cli_local_deps
        || config
            .as_ref()
            .and_then(|c| c.dependencies.as_ref())
            .and_then(|d| d.use_local_paths)
            .unwrap_or(false);

    let rustelo_base_path = if cli_local_deps {
        format!("{}/crates", cli_rustelo_path)
    } else {
        config
            .as_ref()
            .and_then(|c| c.dependencies.as_ref())
            .and_then(|d| d.rustelo.as_ref())
            .and_then(|r| r.base_path.as_ref())
            .cloned()
            .unwrap_or_else(|| "./rustelo/crates".to_string())
    };

    if use_local {
        format!(
            r#"# Rustelo Framework (local development)
rustelo-core = {{ path = "{rustelo_base_path}/rustelo-core" }}
rustelo-web = {{ path = "{rustelo_base_path}/rustelo-web" }}
rustelo-content = {{ path = "{rustelo_base_path}/rustelo-content" }}
rustelo-auth = {{ path = "{rustelo_base_path}/rustelo-auth" }}"#,
            rustelo_base_path = rustelo_base_path
        )
    } else {
        r#"# Rustelo Framework
rustelo-core = { version = "0.1.0", git = "https://github.com/your-org/rustelo.git" }
rustelo-web = { version = "0.1.0", git = "https://github.com/your-org/rustelo.git" }
rustelo-content = { version = "0.1.0", git = "https://github.com/your-org/rustelo.git" }
rustelo-auth = { version = "0.1.0", git = "https://github.com/your-org/rustelo.git" }"#
            .to_string()
    }
}

/// Generate workspace-based Cargo.toml for complex templates
fn generate_workspace_cargo_toml(
    project_path: &Path,
    project_name: &str,
    template: &str,
    _asset_config: &AssetConfiguration,
    config: &Option<InitConfig>,
    cli_local_deps: bool,
    cli_rustelo_path: &str,
) -> Result<()> {
    let snake_case_name = project_name.replace('-', "_");
    let rustelo_deps = generate_rustelo_dependencies(config, cli_local_deps, cli_rustelo_path);

    let cargo_toml = format!(
        r#"# {project_name} - Rustelo {template} Implementation
# Generated by cargo rustelo
# Workspace structure for complex applications

[workspace]
resolver = "2"
members = [
    "server",
    "client",
    "shared"
]

[workspace.dependencies]
# Local crates
{snake_case_name}-server = {{ path = "server" }}
{snake_case_name}-client = {{ path = "client" }}
{snake_case_name}-shared = {{ path = "shared" }}

{rustelo_deps}

# Leptos Framework
leptos = {{ version = "0.8.6" }}
leptos_axum = {{ version = "0.8.5" }}
leptos_router = {{ version = "0.8.5" }}
leptos_meta = {{ version = "0.8.5" }}

# Server Dependencies
axum = {{ version = "0.8.4", features = ["macros", "tracing"] }}
tower = {{ version = "0.5.2", features = ["util"] }}
tower-http = {{ version = "0.6.6", features = ["fs", "cors"] }}
tokio = {{ version = "1.47.1", features = ["rt-multi-thread", "macros", "signal"] }}

# Shared Dependencies
serde = {{ version = "1.0", features = ["derive"] }}
serde_json = "1.0"
uuid = {{ version = "1.18", features = ["v4", "serde"] }}
chrono = {{ version = "0.4", features = ["serde"] }}
thiserror = "2.0"
anyhow = "1.0"

# WASM Dependencies
web-sys = {{ version = "0.3.77" }}
wasm-bindgen = "0.2.100"
console_error_panic_hook = "0.1"

[profile.release]
codegen-units = 1
lto = true
opt-level = 'z'
panic = 'abort'
strip = true

[[workspace.metadata.leptos]]
name = "{project_name}"
bin-package = "{snake_case_name}-server"
lib-package = "{snake_case_name}-client"
bin-target = "{project_name}-server"
output-name = "{project_name}"
site-root = "target/site"
site-pkg-dir = "pkg"
assets-dir = "public"
site-addr = "127.0.0.1:3000"
reload-port = 3001
env = "DEV"
bin-features = ["ssr"]
lib-features = ["hydrate"]
watch = true
"#
    );

    fs::write(project_path.join("Cargo.toml"), cargo_toml).map_err(RusteloError::Io)?;

    // Create workspace crates
    create_workspace_crates(project_path, project_name)?;

    Ok(())
}

/// Generate single-crate Cargo.toml for simple templates
fn generate_single_crate_cargo_toml(
    project_path: &Path,
    project_name: &str,
    _asset_config: &AssetConfiguration,
    config: &Option<InitConfig>,
    cli_local_deps: bool,
    cli_rustelo_path: &str,
) -> Result<()> {
    let rustelo_deps = generate_rustelo_dependencies(config, cli_local_deps, cli_rustelo_path);

    let cargo_toml = format!(
        r#"[package]
name = "{project_name}"
version = "0.1.0"
edition = "2021"
authors = ["Your Name <your@email.com>"]
description = "{project_name} from Rustelo framework"

[dependencies]
leptos = {{ version = "0.8.6", features = ["csr", "hydrate", "ssr"] }}
console_error_panic_hook = "0.1"
{rustelo_deps}

[lib]

[[bin]]
name = "{project_name}"
path = "src/main.rs"
"#,
        project_name = project_name,
        rustelo_deps = rustelo_deps
    );

    fs::write(project_path.join("Cargo.toml"), cargo_toml).map_err(RusteloError::Io)?;
    Ok(())
}

/// Create workspace crate directories and their Cargo.toml files
fn create_workspace_crates(project_path: &Path, project_name: &str) -> Result<()> {
    let snake_case_name = project_name.replace('-', "_");

    // Create server crate
    let server_dir = project_path.join("server");
    fs::create_dir_all(server_dir.join("src")).map_err(RusteloError::Io)?;

    let server_cargo = format!(
        r#"[package]
name = "{}-server"
version = "0.1.0"
edition = "2021"
description = "{} server from Rustelo framework"

[[bin]]
name = "{}-server"
path = "src/main.rs"

[dependencies]
# Workspace crates
{}-shared = {{ workspace = true }}
{}-client = {{ workspace = true }}

# Rustelo Framework
rustelo-core = {{ workspace = true }}
rustelo-web = {{ workspace = true }}
rustelo-content = {{ workspace = true }}
rustelo-auth = {{ workspace = true }}

# Leptos SSR
leptos = {{ workspace = true, features = ["ssr"] }}
leptos_axum = {{ workspace = true }}
leptos_router = {{ workspace = true, features = ["ssr"] }}
leptos_meta = {{ workspace = true, features = ["ssr"] }}

# Web Server
axum = {{ workspace = true }}
tower = {{ workspace = true }}
tower-http = {{ workspace = true }}
tokio = {{ workspace = true }}

# Data
serde = {{ workspace = true }}
serde_json = {{ workspace = true }}
uuid = {{ workspace = true }}
chrono = {{ workspace = true }}
anyhow = {{ workspace = true }}
thiserror = {{ workspace = true }}

[features]
default = ["ssr"]
ssr = [
    "leptos/ssr",
    "leptos_axum/ssr",
    "{}-shared/ssr"
]
"#,
        project_name, project_name, project_name, snake_case_name, snake_case_name, snake_case_name
    );

    fs::write(server_dir.join("Cargo.toml"), server_cargo).map_err(RusteloError::Io)?;

    // Create client crate
    let client_dir = project_path.join("client");
    fs::create_dir_all(client_dir.join("src")).map_err(RusteloError::Io)?;

    let client_cargo = format!(
        r#"[package]
name = "{}-client"
version = "0.1.0"
edition = "2021"
description = "{} client from Rustelo framework"

[lib]
crate-type = ["cdylib"]

[dependencies]
# Workspace crates
{}-shared = {{ workspace = true }}

# Rustelo Framework (client features)
rustelo-web = {{ workspace = true }}
rustelo-content = {{ workspace = true }}

# Leptos Client
leptos = {{ workspace = true, features = ["hydrate"] }}
leptos_router = {{ workspace = true }}
leptos_meta = {{ workspace = true }}

# WASM
web-sys = {{ workspace = true }}
wasm-bindgen = {{ workspace = true }}
console_error_panic_hook = {{ workspace = true }}

# Data
serde = {{ workspace = true }}
serde_json = {{ workspace = true }}
uuid = {{ workspace = true, features = ["js"] }}
chrono = {{ workspace = true }}

[features]
default = ["hydrate"]
hydrate = [
    "leptos/hydrate",
    "{}-shared/hydrate"
]
csr = [
    "leptos/csr",
    "{}-shared/csr"
]
"#,
        project_name, project_name, snake_case_name, snake_case_name, snake_case_name
    );

    fs::write(client_dir.join("Cargo.toml"), client_cargo).map_err(RusteloError::Io)?;

    // Create shared crate
    let shared_dir = project_path.join("shared");
    fs::create_dir_all(shared_dir.join("src")).map_err(RusteloError::Io)?;

    let shared_cargo = format!(
        r#"[package]
name = "{}-shared"
version = "0.1.0"
edition = "2021"
description = "{} shared components from Rustelo framework"

[dependencies]
# Rustelo Framework (shared features)
rustelo-core = {{ workspace = true }}
rustelo-web = {{ workspace = true }}
rustelo-content = {{ workspace = true }}

# Leptos (isomorphic)
leptos = {{ workspace = true }}
leptos_router = {{ workspace = true }}
leptos_meta = {{ workspace = true }}

# Data
serde = {{ workspace = true }}
serde_json = {{ workspace = true }}
uuid = {{ workspace = true }}
chrono = {{ workspace = true }}

[features]
default = []
ssr = [
    "leptos/ssr",
    "leptos_router/ssr",
    "leptos_meta/ssr"
]
hydrate = ["leptos/hydrate"]
csr = ["leptos/csr"]
"#,
        project_name, project_name
    );

    fs::write(shared_dir.join("Cargo.toml"), shared_cargo).map_err(RusteloError::Io)?;

    // Create basic source files
    fs::write(
        server_dir.join("src/main.rs"),
        r#"//! Server main entry point

use axum::Router;
use leptos::*;
use leptos_axum::{generate_route_list, LeptosRoutes};

#[tokio::main]
async fn main() {
    println!("🚀 Starting server...");

    let conf = get_configuration(None).await.unwrap();
    let leptos_options = conf.leptos_options;
    let addr = leptos_options.site_addr;

    // Generate the list of routes in your Leptos App
    let routes = generate_route_list(|| view! { <p>"Hello from Rustelo!"</p> });

    let app = Router::new()
        .leptos_routes(&leptos_options, routes, || view! { <p>"Hello from Rustelo!"</p> })
        .fallback(|| async { "Page not found" });

    println!("🌐 Server running at http://{}", &addr);

    axum::serve(
        tokio::net::TcpListener::bind(&addr).await.unwrap(),
        app.into_make_service(),
    )
    .await
    .unwrap();
}
"#,
    )
    .map_err(RusteloError::Io)?;

    fs::write(
        client_dir.join("src/lib.rs"),
        r#"//! Client-side WASM entry point

use leptos::*;
use wasm_bindgen::prelude::wasm_bindgen;

#[wasm_bindgen]
pub fn hydrate() {
    console_error_panic_hook::set_once();

    mount_to_body(|| {
        view! {
            <div>
                <h1>"Hello from Rustelo Client!"</h1>
                <p>"This is running in WASM"</p>
            </div>
        }
    });
}
"#,
    )
    .map_err(RusteloError::Io)?;

    fs::write(
        shared_dir.join("src/lib.rs"),
        r#"//! Shared components and utilities

use leptos::*;

/// Shared component that works on both server and client
#[component]
pub fn SharedComponent() -> impl IntoView {
    view! {
        <div class="shared-component">
            <h2>"Shared Component"</h2>
            <p>"This component works on both server and client"</p>
        </div>
    }
}

/// Shared data structures
#[cfg(feature = "ssr")]
pub mod server {
    //! Server-only code
}

#[cfg(not(feature = "ssr"))]
pub mod client {
    //! Client-only code
}
"#,
    )
    .map_err(RusteloError::Io)?;

    Ok(())
}

/// Create local override structure
fn create_local_overrides(
    project_path: &Path,
    project_name: &str,
    template: &str,
    asset_config: &AssetConfiguration,
) -> Result<()> {
    // Create asset directory based on configuration
    let asset_dir = project_path.join(&asset_config.download_location);
    fs::create_dir_all(&asset_dir).map_err(RusteloError::Io)?;
    println!("📁 Created asset directory: {}", asset_dir.display());

    // Create asset directory readme from template
    create_readme_from_template(&asset_dir, project_name, asset_config)?;

    // Create modular justfile system (only for complex templates without their own justfile template)
    // Skip if template already provides a justfile.template
    let justfile_exists = project_path.join("justfile").exists();
    if template != "basic" && !justfile_exists {
        create_modular_justfile_system(project_path, project_name, asset_config)?;
    }

    // Create essential implementation directories
    create_implementation_directories(project_path, project_name)?;

    // Create local-tasks.just for user customizations (only for basic template)
    if template == "basic" {
        let local_tasks_path = project_path.join("local-tasks.just");
        if !local_tasks_path.exists() {
            let local_tasks = r#"# Local custom tasks for basic template
# Add your project-specific just tasks here
# These will be included by the main justfile

# Example custom task
hello:
    @echo "Hello from your local tasks!"

# Custom build targets
my-build:
    @echo "Running custom build..."

# Add your own tasks below this line
# Examples:
#
# deploy-staging:
#     @echo "Deploying to staging..."
#
# backup-db:
#     @echo "Creating database backup..."
"#;

            fs::write(&local_tasks_path, local_tasks).map_err(RusteloError::Io)?;
            println!("📄 Created local-tasks.just for custom tasks");
        }
    }

    // Create .rustelo directory
    let rustelo_dir = project_path.join(".rustelo");
    fs::create_dir_all(&rustelo_dir).map_err(RusteloError::Io)?;
    fs::create_dir_all(rustelo_dir.join("logs")).map_err(RusteloError::Io)?;
    fs::create_dir_all(rustelo_dir.join("backups")).map_err(RusteloError::Io)?;

    // Create .rustelo/config.toml for project-specific settings
    let rustelo_config = format!(
        r#"# Rustelo Project Configuration
# Generated on: {}

[project]
name = "{}"
template = "basic"
created = "{}"

[assets]
source = "{}"
download_location = "{}"
auto_update = {}
cache_enabled = {}

[development]
# Add development-specific settings here
hot_reload = true
debug_mode = true

[build]
# Add build-specific settings here
optimize = true
"#,
        Utc::now().format("%Y-%m-%d %H:%M:%S UTC"),
        project_path
            .file_name()
            .unwrap_or_default()
            .to_string_lossy(),
        Utc::now().to_rfc3339(),
        asset_config.source,
        asset_config.download_location,
        asset_config.auto_update,
        asset_config.cache_enabled
    );

    fs::write(rustelo_dir.join("config.toml"), rustelo_config).map_err(RusteloError::Io)?;

    Ok(())
}

/// Create embedded template (fallback)
fn create_embedded_template(_template: &str, project_path: &Path) -> Result<()> {
    // Create basic structure
    fs::create_dir_all(project_path.join("src")).map_err(RusteloError::Io)?;
    fs::create_dir_all(project_path.join("content")).map_err(RusteloError::Io)?;
    fs::create_dir_all(project_path.join("public")).map_err(RusteloError::Io)?;

    // Write minimal template files as fallback
    let main_rs = r#"fn main() {
    println!("Hello from Rustelo!");
}
"#;

    let lib_rs = r#"//! Rustelo application library
"#;

    fs::write(project_path.join("src/main.rs"), main_rs).map_err(RusteloError::Io)?;
    fs::write(project_path.join("src/lib.rs"), lib_rs).map_err(RusteloError::Io)?;

    Ok(())
}

/// Copy directory recursively with template variable processing
fn copy_directory_with_vars(
    src: &std::path::Path,
    dst: &std::path::Path,
    vars: &std::collections::HashMap<String, String>,
) -> Result<()> {
    if !src.is_dir() {
        return Err(RusteloError::generic("Source is not a directory"));
    }

    fs::create_dir_all(dst).map_err(RusteloError::Io)?;

    for entry in fs::read_dir(src).map_err(RusteloError::Io)? {
        let entry = entry.map_err(RusteloError::Io)?;
        let src_path = entry.path();
        let dst_path = dst.join(entry.file_name());

        if src_path.is_dir() {
            copy_directory_with_vars(&src_path, &dst_path, vars)?;
        } else {
            // Check if this is a template file
            if let Some(ext) = src_path.extension() {
                if ext == "template" {
                    // Process template file with variable substitution
                    let content = fs::read_to_string(&src_path).map_err(RusteloError::Io)?;
                    let processed_content = apply_template_vars(&content, vars);
                    let final_dst_path = dst_path.with_extension("");
                    fs::write(&final_dst_path, processed_content).map_err(RusteloError::Io)?;
                    continue;
                }
            }
            // Regular file copy
            fs::copy(&src_path, &dst_path).map_err(RusteloError::Io)?;
        }
    }

    Ok(())
}

/// Load configuration from TOML file
fn load_config_file(config_path: &Path) -> Result<Option<InitConfig>> {
    if !config_path.exists() {
        return Err(RusteloError::generic(format!(
            "Configuration file not found: {}",
            config_path.display()
        )));
    }

    let content = fs::read_to_string(config_path).map_err(RusteloError::Io)?;
    let config: InitConfig = toml::from_str(&content)
        .map_err(|e| RusteloError::generic(format!("Failed to parse config file: {}", e)))?;

    Ok(Some(config))
}

/// Handle existing directory with user interaction
fn handle_existing_directory(project_path: &Path, config: Option<&InitConfig>) -> Result<bool> {
    println!("\n⚠️  **Directory Already Exists**");
    println!("📁 Path: {}", project_path.display());

    // Check if we have a predefined action from config
    if let Some(cfg) = config {
        if let Some(ref action) = cfg.existing_directory_action {
            println!("🔧 Using configured action: {}", action);
            match action.as_str() {
                "merge" => {
                    println!("🔄 Merging template into existing directory...");
                    return Ok(true);
                }
                "replace" => {
                    println!("🗑️  Removing existing directory...");
                    if project_path.exists() {
                        fs::remove_dir_all(project_path).map_err(RusteloError::Io)?;
                    }
                    fs::create_dir_all(project_path).map_err(RusteloError::Io)?;
                    println!("✅ Directory cleared and recreated");
                    return Ok(true);
                }
                "cancel" => {
                    println!("Operation cancelled by configuration");
                    return Ok(false);
                }
                _ => {
                    println!(
                        "⚠️  Unknown action '{}', falling back to interactive mode",
                        action
                    );
                }
            }
        }
    }

    // Check if it looks like a Rustelo project
    let is_rustelo_project = project_path.join("Cargo.toml").exists()
        || project_path.join("rustelo-deps.toml").exists()
        || project_path.join(".rustelo").exists();

    if is_rustelo_project {
        println!("🦀 This appears to be an existing Rustelo project.");
        println!("\n💡 What would you like to do?");
        println!("   1. Update/merge with existing project [recommended]");
        println!("   2. Remove existing and create fresh");
        println!("   3. Cancel operation");
        print!("Choice (1-3, Enter=1): ");
    } else {
        println!("📂 This directory contains other files.");
        println!("\n💡 What would you like to do?");
        println!("   1. Merge Rustelo template into existing directory");
        println!("   2. Remove existing and create fresh");
        println!("   3. Cancel operation");
        print!("Choice (1-3, Enter=1): ");
    }

    io::stdout().flush().map_err(RusteloError::Io)?;

    let mut input = String::new();
    io::stdin()
        .read_line(&mut input)
        .map_err(RusteloError::Io)?;
    let choice = input.trim();

    match choice {
        "1" | "" => {
            if is_rustelo_project {
                println!("🔄 Updating existing Rustelo project...");
            } else {
                println!("🔄 Merging template into existing directory...");
                if !prompt_user("⚠️  Files may be overwritten. Continue? [y/N]")? {
                    return Ok(false);
                }
            }
            Ok(true)
        }
        "2" => {
            println!("⚠️  This will permanently delete all files in the directory!");
            if prompt_user("Are you absolutely sure? [y/N]")? {
                println!("🗑️  Removing existing directory...");
                if project_path.exists() {
                    fs::remove_dir_all(project_path).map_err(RusteloError::Io)?;
                }
                fs::create_dir_all(project_path).map_err(RusteloError::Io)?;
                println!("✅ Directory cleared and recreated");
                Ok(true)
            } else {
                println!("Operation cancelled");
                Ok(false)
            }
        }
        "3" => {
            println!("Operation cancelled");
            Ok(false)
        }
        _ => {
            println!("Invalid choice. Operation cancelled");
            Ok(false)
        }
    }
}

/// Simple user prompt
fn prompt_user(question: &str) -> Result<bool> {
    print!("{} ", question);
    io::stdout().flush().map_err(RusteloError::Io)?;

    let mut input = String::new();
    io::stdin()
        .read_line(&mut input)
        .map_err(RusteloError::Io)?;
    let response = input.trim().to_lowercase();

    Ok(matches!(response.as_str(), "y" | "yes" | ""))
}

/// Save rustelo configuration to rustelo-deps.toml using proper template processing
fn save_rustelo_config(
    project_path: &Path,
    project_name: &str,
    template: &str,
    asset_config: &AssetConfiguration,
) -> Result<()> {
    // Try to use the proper template file from templates
    let config_content =
        if let Ok(template_content) = try_load_rustelo_deps_template(template, asset_config) {
            // Use template file with Tera processing
            render_rustelo_deps_template(&template_content, project_name, template, asset_config)?
        } else {
            // Fallback to the working hardcoded structure (for backwards compatibility)
            generate_rustelo_deps_fallback(project_name, template, asset_config)
        };

    let config_path = project_path.join("rustelo-deps.toml");
    fs::write(&config_path, config_content).map_err(RusteloError::Io)?;

    println!("💾 Saved configuration to: {}", config_path.display());

    Ok(())
}

/// Try to load the rustelo-deps.toml template from templates
fn try_load_rustelo_deps_template(
    template: &str,
    asset_config: &AssetConfiguration,
) -> Result<String> {
    // First try to find the template files directly in the templates directory
    if let Some(framework_path) = &asset_config.framework_path {
        let implementation_templates_path = PathBuf::from(framework_path).join("templates");

        // Try template-specific file first, then shared template
        let direct_paths = vec![
            implementation_templates_path.join(format!("{}/rustelo-deps.toml.template", template)),
            implementation_templates_path.join("shared/rustelo-deps.toml.template"),
        ];

        for path in direct_paths {
            if path.exists() {
                if let Ok(content) = fs::read_to_string(&path) {
                    println!(
                        "✅ Loading rustelo-deps.toml.template from: {}",
                        path.display()
                    );
                    return Ok(content);
                }
            }
        }
    }

    // Fallback to the asset loading system
    let template_paths = vec![
        format!("rustelo-deps.toml.template"),
        format!("{}/rustelo-deps.toml.template", template),
        format!("shared/rustelo-deps.toml.template"),
    ];

    for template_path in template_paths {
        if let Ok(content) = load_template(&template_path, asset_config) {
            return Ok(content);
        }
    }

    Err(RusteloError::generic("No rustelo-deps.toml.template found"))
}

/// Render the template using Tera with proper variable substitution
fn render_rustelo_deps_template(
    template_content: &str,
    project_name: &str,
    template: &str,
    asset_config: &AssetConfiguration,
) -> Result<String> {
    use chrono::Utc;
    use tera_templates::*;

    // Create template configuration
    let config = TemplateConfig {
        project: ProjectConfig {
            name: project_name.to_string(),
            title: None,
            description: None,
            version: "0.1.0".to_string(),
            template: template.to_string(),
            created: Utc::now().format("%Y-%m-%d %H:%M:%S UTC").to_string(),
            author: None,
            license: None,
        },
        assets: AssetConfig {
            source: asset_config.source.clone(),
            download_location: asset_config.download_location.clone(),
            auto_update: asset_config.auto_update,
            cache_enabled: asset_config.cache_enabled,
            framework_path: asset_config.framework_path.clone(),
            notification_methods: asset_config.notification_methods.clone(),
        },
        features: HashMap::new(),
        development: DevelopmentConfig {
            hot_reload: true,
            port: 3030,
            log_level: "debug".to_string(),
            debug_mode: true,
        },
        build: BuildConfig {
            optimize: true,
            compress_assets: true,
            generate_sourcemaps: false,
            target: None,
        },
        custom: None,
    };

    // Create context
    let context = create_template_context(&config)?;

    // Add additional template variables that the template expects
    let mut context = context.clone();
    context.insert("dependency_strategy", "path");
    context.insert(
        "framework_path",
        asset_config
            .framework_path
            .as_deref()
            .unwrap_or("../rustelo"),
    );
    context.insert("rustelo_core_version", "0.1.0");
    context.insert("rustelo_web_version", "0.1.0");
    context.insert("rustelo_auth_version", "0.1.0");
    context.insert("rustelo_content_version", "0.1.0");
    context.insert("dev_mode", &asset_config.auto_update);
    context.insert("asset_source", &asset_config.source);
    context.insert("download_location", &asset_config.download_location);
    context.insert("cache_enabled", &asset_config.cache_enabled);
    context.insert("auto_update", &asset_config.auto_update);

    // Additional template variables for advanced templates
    context.insert("automation_enabled", &asset_config.auto_update);
    context.insert("check_frequency", "weekly");
    context.insert(
        "notify_methods",
        &format!(
            "[{}]",
            asset_config
                .notification_methods
                .iter()
                .map(|s| format!("\"{}\"", s))
                .collect::<Vec<_>>()
                .join(", ")
        ),
    );
    context.insert("contributions_enabled", &asset_config.auto_update);
    context.insert("file_notifications", &asset_config.cache_enabled);
    context.insert("ci_cd_enabled", &false);
    context.insert(
        "description",
        &format!("{} - Generated by Rustelo", project_name),
    );
    context.insert("template_variant", template);
    context.insert("rustelo_version", "0.1.0");

    // Render template
    render_template(template_content, &context, "rustelo-deps.toml.template")
}

/// Fallback hardcoded generation (backwards compatibility)
fn generate_rustelo_deps_fallback(
    _project_name: &str,
    _template: &str,
    asset_config: &AssetConfiguration,
) -> String {
    format!(
        r#"# Rustelo Project Configuration
# Generated by cargo rustelo init

# Dependency configuration
[dependencies]
strategy = "path"

[dependencies.path]
base_path = "{}"

# Framework versions
[versions]
rustelo-core = "0.1.0"
rustelo-web = "0.1.0"
rustelo-auth = "0.1.0"
rustelo-content = "0.1.0"

# Features configuration
[features]
auth = []
content-db = []
content-static = []
email = []
metrics = []
tls = []

# Asset configuration
[assets]
source = "{}"

[assets.local]
framework_path = "{}"
watch_changes = {}
sync_assets = ["templates", "configs", "scripts"]

# Development configuration
[development]
enabled = true
auto_detect_changes = true
auto_sync_assets = {}
validate_assets = true

# Update configuration
[update]
policy = "manual"
backup = true
backup_dir = ".rustelo-backups"
regenerate = []
protected = []
"#,
        asset_config
            .framework_path
            .as_deref()
            .unwrap_or("../rustelo"),
        asset_config.source,
        asset_config
            .framework_path
            .as_deref()
            .unwrap_or("../rustelo"),
        asset_config.auto_update,
        asset_config.auto_update,
    )
}

/// Create modular justfile system for implementation
fn create_modular_justfile_system(
    project_path: &Path,
    project_name: &str,
    asset_config: &AssetConfiguration,
) -> Result<()> {
    let justfile_path = project_path.join("justfile");
    let justfiles_dir = project_path.join("justfiles");

    // Create justfiles directory
    fs::create_dir_all(&justfiles_dir).map_err(RusteloError::Io)?;

    // Create main justfile with modular imports
    let justfile_content = format!(
        r#"# =============================================================================
# {} - RUSTELO FRAMEWORK IMPLEMENTATION
# =============================================================================
# {} implementation using Rustelo modular justfile system
#
# This justfile uses the framework fallback pattern:
# 1. Try to load local implementation-specific task files
# 2. Fall back to framework defaults if local versions don't exist
#
# This allows {} to:
# - Override any framework task with custom implementation
# - Use framework defaults for common tasks
# - Add {}-specific tasks in local justfile modules

# Set shell for commands
set shell := ["bash", "-c"]

# =============================================================================
# IMPLEMENTATION MODULE IMPORTS WITH FRAMEWORK FALLBACK
# =============================================================================
# Local implementation-specific modules take precedence over framework defaults

mod? local-base 'justfiles/base.just'                                    # Local {} base tasks
mod? base '{}/justfiles/base.just'             # Framework from assets

mod? local-database 'justfiles/database.just'                           # Local {} database tasks
mod? database '{}/justfiles/database.just'    # Framework from assets

mod? local-quality 'justfiles/quality.just'                             # Local {} quality tasks
mod? quality '{}/justfiles/quality.just'      # Framework from assets

mod? local-docs 'justfiles/docs.just'                                   # Local {} docs tasks
mod? docs '{}/justfiles/docs.just'            # Framework from assets

mod? local-content 'justfiles/content.just'                             # Local {} content tasks
mod? content '{}/justfiles/content.just'      # Framework from assets

mod? local-testing 'justfiles/testing.just'                             # Local {} testing tasks
mod? testing '{}/justfiles/testing.just'      # Framework from assets

mod? local-build 'justfiles/build.just'                                 # Local {} build tasks
mod? build-tasks '{}/justfiles/build.just'    # Framework from assets

# Note: Framework aliases temporarily disabled due to broken references
# mod? local-aliases 'justfiles/aliases.just'               # Local {} aliases
# mod? aliases '../rustelo/justfiles/aliases.just'          # Framework fallback

# =============================================================================
# IMPLEMENTATION-SPECIFIC COMMANDS
# =============================================================================

# Default recipe to display help
default:
    @just --list

# =============================================================================
# LOCAL CUSTOMIZATION
# =============================================================================
# Custom {}-specific tasks can be added to justfiles/ directory
# They will take precedence over framework defaults via the fallback pattern
"#,
        project_name.to_uppercase(),
        project_name,
        project_name,
        project_name,
        project_name,
        &asset_config.download_location,
        project_name,
        &asset_config.download_location,
        project_name,
        &asset_config.download_location,
        project_name,
        &asset_config.download_location,
        project_name,
        &asset_config.download_location,
        project_name,
        &asset_config.download_location,
        project_name,
        &asset_config.download_location,
        project_name,
        project_name
    );

    fs::write(&justfile_path, justfile_content).map_err(RusteloError::Io)?;
    println!("📄 Created modular justfile with framework fallback system");

    // Create basic local base tasks
    let base_just_path = justfiles_dir.join("base.just");
    let base_content = format!(
        r#"# =============================================================================
# {} IMPLEMENTATION - BASE TASKS
# =============================================================================
# Implementation-specific base tasks for {}
# These override framework defaults

# {}-specific setup
setup:
    @echo "🔧 Setting up {} implementation..."
    @echo "📦 Installing dependencies..."
    cargo build
    @if [ -f "package.json" ]; then npm install; fi
    @echo "📁 Ensuring .rustelo-assets directory exists..."
    @mkdir -p .rustelo-assets/{{cache,templates,components,styles}}
    @echo "✅ {} setup complete!"

# {}-specific development server
dev:
    @echo "🚀 Starting {} development server..."
    @echo "🏷️  Implementation: {}"
    cargo leptos watch

# Clean with {}-specific artifacts
clean:
    @echo "🧹 Cleaning {} build artifacts..."
    cargo clean
    rm -rf dist/
    rm -rf .rustelo-assets/cache/
    @echo "✅ {} cleanup complete!"
"#,
        project_name.to_uppercase(),
        project_name,
        project_name,
        project_name,
        project_name,
        project_name,
        project_name,
        project_name,
        project_name,
        project_name,
        project_name
    );

    fs::write(&base_just_path, base_content).map_err(RusteloError::Io)?;
    println!("📄 Created local base tasks in justfiles/base.just");

    Ok(())
}

/// Create README from template file using Tera engine
fn create_readme_from_template(
    asset_dir: &Path,
    project_name: &str,
    asset_config: &AssetConfiguration,
) -> Result<()> {
    let content = load_and_render_tera_template(
        "readme/rustelo-assets.md",
        project_name,
        "basic",
        asset_config,
    )?;

    fs::write(asset_dir.join("README.md"), content).map_err(RusteloError::Io)?;
    println!("📄 Created README.md from Tera template");

    Ok(())
}

/// Create essential directory structure for implementation
fn create_implementation_directories(project_path: &Path, project_name: &str) -> Result<()> {
    println!("📁 Creating implementation directory structure...");

    // Create assets directory structure
    let assets_dir = project_path.join("assets");
    fs::create_dir_all(assets_dir.join("images")).map_err(RusteloError::Io)?;
    fs::create_dir_all(assets_dir.join("scripts")).map_err(RusteloError::Io)?;
    fs::create_dir_all(assets_dir.join("styles")).map_err(RusteloError::Io)?;

    // Create content directory structure
    let content_dir = project_path.join("content");
    fs::create_dir_all(content_dir.join("blog")).map_err(RusteloError::Io)?;
    fs::create_dir_all(content_dir.join("pages")).map_err(RusteloError::Io)?;
    fs::create_dir_all(content_dir.join("locales/en")).map_err(RusteloError::Io)?;
    fs::create_dir_all(content_dir.join("locales/es")).map_err(RusteloError::Io)?;

    // Create basic locale files
    let en_common = r#"# English translations for {{project_name}}

# Common phrases
loading = Loading...
error = Error
success = Success
cancel = Cancel
submit = Submit
"#
    .replace("{{project_name}}", project_name);

    fs::write(content_dir.join("locales/en/common.ftl"), en_common).map_err(RusteloError::Io)?;

    let es_common = r#"# Spanish translations for {{project_name}}

# Common phrases
loading = Cargando...
error = Error
success = Éxito
cancel = Cancelar
submit = Enviar
"#
    .replace("{{project_name}}", project_name);

    fs::write(content_dir.join("locales/es/common.ftl"), es_common).map_err(RusteloError::Io)?;

    // Enhanced public directory structure
    let public_dir = project_path.join("public");
    fs::create_dir_all(public_dir.join("images")).map_err(RusteloError::Io)?;
    fs::create_dir_all(public_dir.join("scripts")).map_err(RusteloError::Io)?;
    fs::create_dir_all(public_dir.join("styles")).map_err(RusteloError::Io)?;
    fs::create_dir_all(public_dir.join("documents")).map_err(RusteloError::Io)?;

    // Create public README
    let public_readme = format!(
        r#"# {} Public Assets

This directory contains static assets served directly by the web server.

## Directory Structure

```
public/
├── images/       # Static images (logos, icons, etc.)
├── scripts/      # Client-side JavaScript
├── styles/       # Public CSS files
├── documents/    # Downloadable documents
└── README.md     # This file
```

## Usage

Files in this directory are served at the root URL:
- `public/logo.png` → `https://yoursite.com/logo.png`
- `public/styles/custom.css` → `https://yoursite.com/styles/custom.css`

## Guidelines

- Keep file sizes optimized for web delivery
- Use descriptive filenames
- Organize by type (images, scripts, styles, documents)
- Consider CDN deployment for production
"#,
        project_name
    );

    fs::write(public_dir.join("README.md"), public_readme).map_err(RusteloError::Io)?;

    println!("✅ Created directory structure: assets/, content/, public/");

    Ok(())
}

/// Load template file using dynamic asset resolution
fn load_template(template_path: &str, asset_config: &AssetConfiguration) -> Result<String> {
    // Build possible template locations in priority order
    let template_locations = get_template_search_paths(template_path, asset_config);

    if cfg!(debug_assertions) {
        println!(
            "🔍 Searching for template '{}' in {} locations:",
            template_path,
            template_locations.len()
        );
        for (i, location) in template_locations.iter().enumerate() {
            println!(
                "   {}. {} (exists: {})",
                i + 1,
                location.display(),
                location.exists()
            );
        }
    }

    // Try each location until we find the template
    for location in &template_locations {
        if location.exists() {
            if cfg!(debug_assertions) {
                println!("✅ Loading template from: {}", location.display());
            }
            return fs::read_to_string(location).map_err(RusteloError::Io);
        }
    }

    // If no template found, provide a basic fallback
    println!(
        "⚠️  Template not found at any location, using fallback for: {}",
        template_path
    );
    Ok(create_fallback_template_content(template_path))
}

#[cfg(feature = "generate")]
/// Load and render template using Tera engine with JSON configuration
fn load_and_render_tera_template(
    template_path: &str,
    project_name: &str,
    template_name: &str,
    asset_config: &AssetConfiguration,
) -> Result<String> {
    use tera_templates::*;

    // Load template content
    let template_content = load_template(template_path, asset_config)?;

    // Load template configuration
    let config = load_template_config(project_name, template_name, asset_config)?;

    // Create Tera context
    let context = create_template_context(&config)?;

    // Render template
    render_template(&template_content, &context, template_path)
}

#[cfg(not(feature = "generate"))]
/// Fallback template rendering using simple string replacement
fn load_and_render_tera_template(
    template_path: &str,
    project_name: &str,
    template_name: &str,
    asset_config: &AssetConfiguration,
) -> Result<String> {
    // Fall back to simple string replacement when Tera is not available
    let template_content = load_template(template_path, asset_config)?;

    let mut content = template_content;
    content = content.replace("{{project_name}}", project_name);
    content = content.replace("{{asset_source}}", &asset_config.source);
    content = content.replace("{{auto_update}}", &asset_config.auto_update.to_string());
    content = content.replace("{{cache_enabled}}", &asset_config.cache_enabled.to_string());
    content = content.replace(
        "{{framework_path}}",
        asset_config.framework_path.as_deref().unwrap_or(""),
    );
    content = content.replace(
        "{{generation_timestamp}}",
        &Utc::now().format("%Y-%m-%d %H:%M:%S UTC").to_string(),
    );
    content = content.replace("{{template}}", template_name);

    Ok(content)
}

/// Get template search paths in priority order
fn get_template_search_paths(
    template_path: &str,
    asset_config: &AssetConfiguration,
) -> Vec<PathBuf> {
    let mut paths = Vec::new();

    // 1. Local .rustelo-assets (highest priority - user customizations)
    paths.push(
        PathBuf::from(&asset_config.download_location)
            .join("templates")
            .join(template_path),
    );

    // 2. Framework path from configuration
    if let Some(framework_path) = &asset_config.framework_path {
        // If framework_path points to templates, look in parent for assets
        if framework_path.ends_with("templates") {
            let parent_path = PathBuf::from(framework_path)
                .parent()
                .map(|p| p.join("assets/templates").join(template_path));
            if let Some(path) = parent_path {
                if cfg!(debug_assertions) {
                    println!(
                        "🔧 Framework path ends with 'templates', using parent: {}",
                        path.display()
                    );
                }
                paths.push(path);
            }
        } else {
            paths.push(
                PathBuf::from(framework_path)
                    .join("assets/templates")
                    .join(template_path),
            );
        }
    }

    // 3. Relative to current project (framework development)
    paths.push(PathBuf::from("../rustelo/assets/templates").join(template_path));
    paths.push(PathBuf::from("../../rustelo/assets/templates").join(template_path));

    // 4. Handle common templates path scenarios
    paths.push(PathBuf::from("../assets/templates").join(template_path));
    paths.push(PathBuf::from("../../assets/templates").join(template_path));

    // 4. Absolute paths (common framework locations)
    if let Ok(home) = std::env::var("HOME") {
        paths.push(
            PathBuf::from(home)
                .join(".rustelo/framework/assets/templates")
                .join(template_path),
        );
    }
    paths.push(PathBuf::from("/opt/rustelo/assets/templates").join(template_path));
    paths.push(PathBuf::from("/usr/local/rustelo/assets/templates").join(template_path));

    paths
}

/// Create fallback template content when no template file is found
fn create_fallback_template_content(template_path: &str) -> String {
    match template_path {
        "readme/rustelo-assets.md" => {
            r#"# Rustelo Assets Directory

This directory contains downloaded framework assets and templates for the {{project_name}} implementation.

## Configuration

- **Source**: {{asset_source}}
- **Auto-update**: {{auto_update}}
- **Cache enabled**: {{cache_enabled}}

## Usage

This directory is managed automatically by the Rustelo CLI:

```bash
cargo rustelo assets sync
cargo rustelo assets list
cargo rustelo update --check
```

## Notes

Files in this directory may be overwritten during updates.
"#.to_string()
        },
        "setup-summary.md" => {
            r#"# {{project_name}} - Setup Summary

**Generated**: {{generation_timestamp}}
**Template**: {{template}}

## Next Steps

1. Install dependencies: `just setup`
2. Start development: `just dev`
3. Check for updates: `cargo rustelo update --check`

## Documentation

- Configuration: `rustelo-deps.toml`
- Local tasks: `local-tasks.just`
"#.to_string()
        },
        _ => {
            format!("# Template: {}\n\nThis is a fallback template for {{{{project_name}}}}.\n", template_path)
        }
    }
}

#[cfg(feature = "generate")]
/// Tera-based template rendering system with JSON context
mod tera_templates {
    use super::*;

    /// Template configuration loaded from JSON
    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct TemplateConfig {
        pub project: ProjectConfig,
        pub assets: AssetConfig,
        pub features: HashMap<String, bool>,
        pub development: DevelopmentConfig,
        pub build: BuildConfig,
        pub custom: Option<serde_json::Value>,
    }

    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct ProjectConfig {
        pub name: String,
        pub title: Option<String>,
        pub description: Option<String>,
        pub version: String,
        pub template: String,
        pub created: String,
        pub author: Option<String>,
        pub license: Option<String>,
    }

    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct AssetConfig {
        pub source: String,
        pub download_location: String,
        pub auto_update: bool,
        pub cache_enabled: bool,
        pub framework_path: Option<String>,
        pub notification_methods: Vec<String>,
    }

    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct DevelopmentConfig {
        pub hot_reload: bool,
        pub port: u16,
        pub log_level: String,
        pub debug_mode: bool,
    }

    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct BuildConfig {
        pub optimize: bool,
        pub compress_assets: bool,
        pub generate_sourcemaps: bool,
        pub target: Option<String>,
    }

    /// Create template context from configuration
    pub fn create_template_context(config: &TemplateConfig) -> Result<Context> {
        let mut context = Context::new();

        // Add all configuration sections
        context.insert("project", &config.project);
        context.insert("assets", &config.assets);
        context.insert("features", &config.features);
        context.insert("development", &config.development);
        context.insert("build", &config.build);

        // Add convenience variables
        context.insert("project_name", &config.project.name);
        context.insert("project_name_snake", &config.project.name.replace('-', "_"));
        context.insert(
            "project_name_upper",
            &config.project.name.to_uppercase().replace('-', "_"),
        );
        context.insert("generation_timestamp", &config.project.created);

        // Add custom context if provided
        if let Some(custom) = &config.custom {
            context.insert("custom", custom);
        }

        Ok(context)
    }

    /// Render template using Tera engine
    pub fn render_template(
        template_content: &str,
        context: &Context,
        template_name: &str,
    ) -> Result<String> {
        let mut tera = Tera::default();

        // Add template to Tera
        tera.add_raw_template(template_name, template_content)
            .map_err(|e| {
                println!("❌ Template parse error for '{}': {}", template_name, e);
                println!(
                    "📄 Template content preview: {}",
                    template_content.chars().take(200).collect::<String>()
                );
                RusteloError::generic(format!(
                    "Template parse error in '{}': {}",
                    template_name, e
                ))
            })?;

        // Debug context (only in debug mode)
        if cfg!(debug_assertions) {
            println!(
                "🔍 Template context keys: {:?}",
                context
                    .clone()
                    .into_json()
                    .as_object()
                    .map(|o| o.keys().collect::<Vec<_>>())
            );
        }

        // Render template
        tera.render(template_name, context).map_err(|e| {
            println!("❌ Template render error for '{}': {}", template_name, e);
            println!(
                "🔍 Available context: {}",
                serde_json::to_string_pretty(&context.clone().into_json())
                    .unwrap_or_else(|_| "{}".to_string())
            );
            RusteloError::generic(format!(
                "Template render error in '{}': {}",
                template_name, e
            ))
        })
    }

    /// Load template configuration from JSON file
    pub fn load_template_config(
        project_name: &str,
        template: &str,
        asset_config: &AssetConfiguration,
    ) -> Result<TemplateConfig> {
        // Try to load custom config first
        let config_paths = get_template_config_paths(project_name);

        for config_path in &config_paths {
            if config_path.exists() {
                let config_content = fs::read_to_string(config_path).map_err(RusteloError::Io)?;

                if let Ok(config) = serde_json::from_str::<TemplateConfig>(&config_content) {
                    println!("📄 Loaded template config from: {}", config_path.display());
                    return Ok(config);
                }
            }
        }

        // Create default configuration
        Ok(create_default_template_config(
            project_name,
            template,
            asset_config,
        ))
    }

    /// Get possible template configuration file paths
    fn get_template_config_paths(project_name: &str) -> Vec<PathBuf> {
        vec![
            PathBuf::from(format!("{}.rustelo-config.json", project_name)),
            PathBuf::from(".rustelo-config.json"),
            PathBuf::from("rustelo-template.json"),
            PathBuf::from(".rustelo/template-config.json"),
        ]
    }

    /// Create default template configuration
    fn create_default_template_config(
        project_name: &str,
        template: &str,
        asset_config: &AssetConfiguration,
    ) -> TemplateConfig {
        TemplateConfig {
            project: ProjectConfig {
                name: project_name.to_string(),
                title: Some(project_name.replace('-', " ").to_title_case()),
                description: Some(format!("A Rustelo {} implementation", template)),
                version: "0.1.0".to_string(),
                template: template.to_string(),
                created: Utc::now().format("%Y-%m-%d %H:%M:%S UTC").to_string(),
                author: std::env::var("USER")
                    .ok()
                    .or_else(|| std::env::var("USERNAME").ok()),
                license: Some("MIT".to_string()),
            },
            assets: AssetConfig {
                source: asset_config.source.clone(),
                download_location: asset_config.download_location.clone(),
                auto_update: asset_config.auto_update,
                cache_enabled: asset_config.cache_enabled,
                framework_path: asset_config.framework_path.clone(),
                notification_methods: asset_config.notification_methods.clone(),
            },
            features: get_default_features(template),
            development: DevelopmentConfig {
                hot_reload: true,
                port: 3030,
                log_level: "debug".to_string(),
                debug_mode: true,
            },
            build: BuildConfig {
                optimize: true,
                compress_assets: true,
                generate_sourcemaps: false,
                target: None,
            },
            custom: None,
        }
    }

    /// Get default features for template type
    fn get_default_features(template: &str) -> HashMap<String, bool> {
        let mut features = HashMap::new();

        match template {
            "cms" => {
                features.insert("auth".to_string(), true);
                features.insert("content-db".to_string(), true);
                features.insert("email".to_string(), true);
            }
            "enterprise" | "saas" => {
                features.insert("auth".to_string(), true);
                features.insert("content-db".to_string(), true);
                features.insert("email".to_string(), true);
                features.insert("metrics".to_string(), true);
                features.insert("tls".to_string(), true);
            }
            "ecommerce" => {
                features.insert("auth".to_string(), true);
                features.insert("content-db".to_string(), true);
                features.insert("email".to_string(), true);
                features.insert("metrics".to_string(), true);
            }
            _ => {
                features.insert("content-static".to_string(), true);
            }
        }

        features
    }
}

/// Helper trait for string case conversion
trait StringExt {
    fn to_title_case(&self) -> String;
}

impl StringExt for str {
    fn to_title_case(&self) -> String {
        self.split_whitespace()
            .map(|word| {
                let mut chars = word.chars();
                match chars.next() {
                    None => String::new(),
                    Some(first) => {
                        first.to_uppercase().collect::<String>() + &chars.as_str().to_lowercase()
                    }
                }
            })
            .collect::<Vec<_>>()
            .join(" ")
    }
}
