//! Configuration Wizard for Rustelo Template
//!
//! This binary uses Rhai scripting engine to create an interactive
//! configuration wizard that generates config.toml and updates Cargo.toml
//! features based on user preferences.

use std::fs;
use std::io::{self, Write};
use std::path::Path;

use rhai::{Dynamic, Engine, Map, Scope};
use serde::{Deserialize, Serialize};
use toml::Value;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FeatureConfig {
    pub name: String,
    pub description: String,
    pub dependencies: Vec<String>,
    pub enabled: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WizardConfig {
    pub features: Vec<FeatureConfig>,
    pub server: ServerConfig,
    pub database: Option<DatabaseConfig>,
    pub auth: Option<AuthConfig>,
    pub oauth: Option<OAuthConfig>,
    pub email: Option<EmailConfig>,
    pub security: SecurityConfig,
    pub monitoring: Option<MonitoringConfig>,
    pub ssl: Option<SslConfig>,
    pub cache: Option<CacheConfig>,
    pub build_info: BuildInfoConfig,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServerConfig {
    pub host: String,
    pub port: u16,
    pub environment: String,
    pub workers: u32,
    pub protocol: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DatabaseConfig {
    pub url: String,
    pub max_connections: u32,
    pub enable_logging: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuthConfig {
    pub jwt_secret: String,
    pub session_timeout: u32,
    pub max_login_attempts: u32,
    pub require_email_verification: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OAuthConfig {
    pub enabled: bool,
    pub google: Option<OAuthProvider>,
    pub github: Option<OAuthProvider>,
    pub microsoft: Option<OAuthProvider>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OAuthProvider {
    pub client_id: String,
    pub client_secret: String,
    pub redirect_uri: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EmailConfig {
    pub smtp_host: String,
    pub smtp_port: u16,
    pub smtp_username: String,
    pub smtp_password: String,
    pub from_email: String,
    pub from_name: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecurityConfig {
    pub enable_csrf: bool,
    pub rate_limit_requests: u32,
    pub bcrypt_cost: u32,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MonitoringConfig {
    pub enabled: bool,
    pub metrics_port: u16,
    pub prometheus_enabled: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SslConfig {
    pub force_https: bool,
    pub cert_path: String,
    pub key_path: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CacheConfig {
    pub enabled: bool,
    pub cache_type: String,
    pub default_ttl: u32,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BuildInfoConfig {
    pub environment: String,
    pub config_version: String,
}

pub struct ConfigWizard {
    engine: Engine,
    scope: Scope<'static>,
}

impl Default for ConfigWizard {
    fn default() -> Self {
        Self::new()
    }
}

impl ConfigWizard {
    pub fn new() -> Self {
        let mut engine = Engine::new();
        let mut scope = Scope::new();

        // Register custom functions for user input
        engine.register_fn("input", || -> String {
            let mut input = String::new();
            io::stdout().flush().unwrap();
            io::stdin().read_line(&mut input).unwrap();
            input.trim().to_string()
        });

        engine.register_fn("ask_yes_no", |question: &str| -> bool {
            loop {
                print!("{question} (y/n): ");
                io::stdout().flush().unwrap();
                let mut input = String::new();
                io::stdin().read_line(&mut input).unwrap();
                match input.trim().to_lowercase().as_str() {
                    "y" | "yes" => return true,
                    "n" | "no" => return false,
                    _ => println!("Please enter 'y' or 'n'"),
                }
            }
        });

        engine.register_fn("ask_string", |question: &str, default: &str| -> String {
            if !default.is_empty() {
                print!("{question} [{default}]: ");
            } else {
                print!("{question}: ");
            }
            io::stdout().flush().unwrap();
            let mut input = String::new();
            io::stdin().read_line(&mut input).unwrap();
            let input = input.trim();
            if input.is_empty() {
                default.to_string()
            } else {
                input.to_string()
            }
        });

        engine.register_fn("ask_number", |question: &str, default: i64| -> i64 {
            loop {
                print!("{question} [{default}]: ");
                io::stdout().flush().unwrap();
                let mut input = String::new();
                io::stdin().read_line(&mut input).unwrap();
                let input = input.trim();
                if input.is_empty() {
                    return default;
                }
                match input.parse::<i64>() {
                    Ok(num) => return num,
                    Err(_) => println!("Please enter a valid number"),
                }
            }
        });

        // Initialize available features
        let available_features = [
            ("auth", "Authentication and authorization system"),
            ("tls", "TLS/SSL support for secure connections"),
            ("rbac", "Role-based access control"),
            ("crypto", "Cryptographic utilities and encryption"),
            ("content-db", "Content management and database features"),
            ("email", "Email sending capabilities"),
            ("metrics", "Prometheus metrics collection"),
            ("examples", "Include example code and documentation"),
            (
                "production",
                "Production-ready configuration (includes: auth, content-db, crypto, email, \
                 metrics, tls)",
            ),
        ];

        let mut features_map = Map::new();
        for (name, desc) in available_features.iter() {
            features_map.insert(name.to_string().into(), Dynamic::from(desc.to_string()));
        }
        scope.push("available_features", features_map);

        Self { engine, scope }
    }

    pub fn run_wizard(&mut self) -> Result<WizardConfig, Box<dyn std::error::Error>> {
        println!("=== Rustelo Configuration Wizard ===");
        println!("This wizard will help you configure your Rustelo application.\n");

        // Load and execute the Rhai script
        let script_content = self.load_wizard_script()?;
        let ast = self.engine.compile(&script_content)?;

        // Execute the wizard script
        let result: Dynamic = self.engine.eval_ast_with_scope(&mut self.scope, &ast)?;

        // Convert result to WizardConfig
        let config = self.convert_dynamic_to_config(result)?;

        Ok(config)
    }

    fn load_wizard_script(&self) -> Result<String, Box<dyn std::error::Error>> {
        // Try to load external .rhai file first, fallback to embedded script
        let script_path = "scripts/config_wizard.rhai";

        if std::path::Path::new(script_path).exists() {
            return std::fs::read_to_string(script_path)
                .map_err(|e| format!("Failed to read {script_path}: {e}").into());
        }

        // Fallback to embedded script
        let script = r#"
            let config = #{
                features: [],
                server: #{
                    host: "127.0.0.1",
                    port: 3030,
                    environment: "dev",
                    workers: 4,
                    protocol: "http"
                },
                security: #{
                    enable_csrf: true,
                    rate_limit_requests: 100,
                    bcrypt_cost: 12
                },
                build_info: #{
                    environment: "dev",
                    config_version: "1.0.0"
                }
            };

            print("\n--- Feature Selection ---");
            print("Select the features you want to enable:\n");

            let selected_features = [];

            for feature in available_features.keys() {
                let description = available_features[feature];
                if ask_yes_no("Enable " + feature + "? (" + description + ")") {
                    selected_features.push(feature);
                }
            }

            config.features = selected_features;

            // Basic server configuration
            print("\n--- Server Configuration ---");
            config.server.host = ask_string("Server host", config.server.host);
            config.server.port = ask_number("Server port", config.server.port);
            config.server.environment = ask_string("Environment (dev/prod/test)", config.server.environment);
            config.server.workers = ask_number("Number of workers", config.server.workers);

            // Database configuration (if content-db feature is enabled)
            if selected_features.contains("content-db") {
                print("\n--- Database Configuration ---");
                config.database = #{
                    url: ask_string("Database URL", "sqlite:rustelo.db"),
                    max_connections: ask_number("Max database connections", 10),
                    enable_logging: ask_yes_no("Enable database query logging")
                };
            }

            // Authentication configuration (if auth feature is enabled)
            if selected_features.contains("auth") {
                print("\n--- Authentication Configuration ---");
                config.auth = #{
                    jwt_secret: ask_string("JWT secret (leave empty for auto-generation)", ""),
                    session_timeout: ask_number("Session timeout (minutes)", 60),
                    max_login_attempts: ask_number("Max login attempts", 5),
                    require_email_verification: ask_yes_no("Require email verification")
                };

                // OAuth configuration
                if ask_yes_no("Enable OAuth providers?") {
                    config.oauth = #{ enabled: true };

                    if ask_yes_no("Enable Google OAuth?") {
                        config.oauth.google = #{
                            client_id: ask_string("Google OAuth Client ID", ""),
                            client_secret: ask_string("Google OAuth Client Secret", ""),
                            redirect_uri: ask_string("Google OAuth Redirect URI", "http://localhost:3030/auth/google/callback")
                        };
                    }

                    if ask_yes_no("Enable GitHub OAuth?") {
                        config.oauth.github = #{
                            client_id: ask_string("GitHub OAuth Client ID", ""),
                            client_secret: ask_string("GitHub OAuth Client Secret", ""),
                            redirect_uri: ask_string("GitHub OAuth Redirect URI", "http://localhost:3030/auth/github/callback")
                        };
                    }
                }
            }

            // Email configuration (if email feature is enabled)
            if selected_features.contains("email") {
                print("\n--- Email Configuration ---");
                config.email = #{
                    smtp_host: ask_string("SMTP host", "localhost"),
                    smtp_port: ask_number("SMTP port", 587),
                    smtp_username: ask_string("SMTP username", ""),
                    smtp_password: ask_string("SMTP password", ""),
                    from_email: ask_string("From email address", "noreply@localhost"),
                    from_name: ask_string("From name", "Rustelo App")
                };
            }

            // Security configuration
            print("\n--- Security Configuration ---");
            config.security.enable_csrf = ask_yes_no("Enable CSRF protection");
            config.security.rate_limit_requests = ask_number("Rate limit requests per minute", 100);
            config.security.bcrypt_cost = ask_number("BCrypt cost (4-31)", 12);

            // SSL/TLS configuration (if tls feature is enabled)
            if selected_features.contains("tls") {
                print("\n--- SSL/TLS Configuration ---");
                config.ssl = #{
                    force_https: ask_yes_no("Force HTTPS"),
                    cert_path: ask_string("SSL certificate path", ""),
                    key_path: ask_string("SSL private key path", "")
                };
            }

            // Monitoring configuration (if metrics feature is enabled)
            if selected_features.contains("metrics") {
                print("\n--- Monitoring Configuration ---");
                let monitoring_enabled = ask_yes_no("Enable monitoring");
                if monitoring_enabled {
                    config.monitoring = #{
                        enabled: true,
                        metrics_port: ask_number("Metrics port", 9090),
                        prometheus_enabled: ask_yes_no("Enable Prometheus metrics")
                    };
                }
            }

            // Cache configuration
            print("\n--- Cache Configuration ---");
            let cache_enabled = ask_yes_no("Enable caching");
            if cache_enabled {
                config.cache = #{
                    enabled: true,
                    cache_type: ask_string("Cache type (memory/redis)", "memory"),
                    default_ttl: ask_number("Default TTL (seconds)", 3600)
                };
            }

            // Update build info
            config.build_info.environment = config.server.environment;

            config
        "#;

        Ok(script.to_string())
    }

    fn convert_dynamic_to_config(
        &self,
        dynamic: Dynamic,
    ) -> Result<WizardConfig, Box<dyn std::error::Error>> {
        let map = dynamic.cast::<Map>();

        // Extract features
        let features_dynamic = map.get("features").ok_or("Missing features field")?.clone();
        let features_array = features_dynamic.cast::<rhai::Array>();
        let mut features = Vec::new();

        for feature in features_array {
            let feature_name = feature.cast::<String>();
            features.push(FeatureConfig {
                name: feature_name.clone(),
                description: "".to_string(),
                dependencies: vec![],
                enabled: true,
            });
        }

        // Extract server config
        let server_map = map
            .get("server")
            .ok_or("Missing server field")?
            .clone()
            .cast::<Map>();
        let server = ServerConfig {
            host: server_map
                .get("host")
                .ok_or("Missing server.host field")?
                .clone()
                .cast::<String>(),
            port: server_map
                .get("port")
                .ok_or("Missing server.port field")?
                .clone()
                .cast::<i64>() as u16,
            environment: server_map
                .get("environment")
                .ok_or("Missing server.environment field")?
                .clone()
                .cast::<String>(),
            workers: server_map
                .get("workers")
                .ok_or("Missing server.workers field")?
                .clone()
                .cast::<i64>() as u32,
            protocol: server_map
                .get("protocol")
                .ok_or("Missing server.protocol field")?
                .clone()
                .cast::<String>(),
        };

        // Extract security config
        let security_map = map
            .get("security")
            .ok_or("Missing security field")?
            .clone()
            .cast::<Map>();
        let security = SecurityConfig {
            enable_csrf: security_map
                .get("enable_csrf")
                .ok_or("Missing security.enable_csrf field")?
                .clone()
                .cast::<bool>(),
            rate_limit_requests: security_map
                .get("rate_limit_requests")
                .ok_or("Missing security.rate_limit_requests field")?
                .clone()
                .cast::<i64>() as u32,
            bcrypt_cost: security_map
                .get("bcrypt_cost")
                .ok_or("Missing security.bcrypt_cost field")?
                .clone()
                .cast::<i64>() as u32,
        };

        // Extract build info
        let build_info_map = map
            .get("build_info")
            .ok_or("Missing build_info field")?
            .clone()
            .cast::<Map>();
        let build_info = BuildInfoConfig {
            environment: build_info_map
                .get("environment")
                .ok_or("Missing build_info.environment field")?
                .clone()
                .cast::<String>(),
            config_version: build_info_map
                .get("config_version")
                .ok_or("Missing build_info.config_version field")?
                .clone()
                .cast::<String>(),
        };

        // Extract optional configs
        let database = map.get("database").map(|d| {
            let db_map = d.clone().cast::<Map>();
            DatabaseConfig {
                url: db_map
                    .get("url")
                    .unwrap_or(&Dynamic::from(""))
                    .clone()
                    .cast::<String>(),
                max_connections: db_map
                    .get("max_connections")
                    .unwrap_or(&Dynamic::from(10_i64))
                    .clone()
                    .cast::<i64>() as u32,
                enable_logging: db_map
                    .get("enable_logging")
                    .unwrap_or(&Dynamic::from(false))
                    .clone()
                    .cast::<bool>(),
            }
        });

        let auth = map.get("auth").map(|a| {
            let auth_map = a.clone().cast::<Map>();
            AuthConfig {
                jwt_secret: auth_map
                    .get("jwt_secret")
                    .unwrap_or(&Dynamic::from(""))
                    .clone()
                    .cast::<String>(),
                session_timeout: auth_map
                    .get("session_timeout")
                    .unwrap_or(&Dynamic::from(60_i64))
                    .clone()
                    .cast::<i64>() as u32,
                max_login_attempts: auth_map
                    .get("max_login_attempts")
                    .unwrap_or(&Dynamic::from(5_i64))
                    .clone()
                    .cast::<i64>() as u32,
                require_email_verification: auth_map
                    .get("require_email_verification")
                    .unwrap_or(&Dynamic::from(false))
                    .clone()
                    .cast::<bool>(),
            }
        });

        // Extract OAuth config
        let oauth = map.get("oauth").map(|o| {
            let oauth_map = o.clone().cast::<Map>();
            let enabled = oauth_map
                .get("enabled")
                .unwrap_or(&Dynamic::from(false))
                .clone()
                .cast::<bool>();

            let google = oauth_map.get("google").map(|g| {
                let google_map = g.clone().cast::<Map>();
                OAuthProvider {
                    client_id: google_map
                        .get("client_id")
                        .unwrap_or(&Dynamic::from(""))
                        .clone()
                        .cast::<String>(),
                    client_secret: google_map
                        .get("client_secret")
                        .unwrap_or(&Dynamic::from(""))
                        .clone()
                        .cast::<String>(),
                    redirect_uri: google_map
                        .get("redirect_uri")
                        .unwrap_or(&Dynamic::from(""))
                        .clone()
                        .cast::<String>(),
                }
            });

            let github = oauth_map.get("github").map(|g| {
                let github_map = g.clone().cast::<Map>();
                OAuthProvider {
                    client_id: github_map
                        .get("client_id")
                        .unwrap_or(&Dynamic::from(""))
                        .clone()
                        .cast::<String>(),
                    client_secret: github_map
                        .get("client_secret")
                        .unwrap_or(&Dynamic::from(""))
                        .clone()
                        .cast::<String>(),
                    redirect_uri: github_map
                        .get("redirect_uri")
                        .unwrap_or(&Dynamic::from(""))
                        .clone()
                        .cast::<String>(),
                }
            });

            OAuthConfig {
                enabled,
                google,
                github,
                microsoft: None,
            }
        });

        // Extract email config
        let email = map.get("email").map(|e| {
            let email_map = e.clone().cast::<Map>();
            EmailConfig {
                smtp_host: email_map
                    .get("smtp_host")
                    .unwrap_or(&Dynamic::from(""))
                    .clone()
                    .cast::<String>(),
                smtp_port: email_map
                    .get("smtp_port")
                    .unwrap_or(&Dynamic::from(587_i64))
                    .clone()
                    .cast::<i64>() as u16,
                smtp_username: email_map
                    .get("smtp_username")
                    .unwrap_or(&Dynamic::from(""))
                    .clone()
                    .cast::<String>(),
                smtp_password: email_map
                    .get("smtp_password")
                    .unwrap_or(&Dynamic::from(""))
                    .clone()
                    .cast::<String>(),
                from_email: email_map
                    .get("from_email")
                    .unwrap_or(&Dynamic::from(""))
                    .clone()
                    .cast::<String>(),
                from_name: email_map
                    .get("from_name")
                    .unwrap_or(&Dynamic::from(""))
                    .clone()
                    .cast::<String>(),
            }
        });

        // Extract monitoring config
        let monitoring = map.get("monitoring").map(|m| {
            let monitoring_map = m.clone().cast::<Map>();
            MonitoringConfig {
                enabled: monitoring_map
                    .get("enabled")
                    .unwrap_or(&Dynamic::from(false))
                    .clone()
                    .cast::<bool>(),
                metrics_port: monitoring_map
                    .get("metrics_port")
                    .unwrap_or(&Dynamic::from(9090_i64))
                    .clone()
                    .cast::<i64>() as u16,
                prometheus_enabled: monitoring_map
                    .get("prometheus_enabled")
                    .unwrap_or(&Dynamic::from(false))
                    .clone()
                    .cast::<bool>(),
            }
        });

        // Extract SSL config
        let ssl = map.get("ssl").map(|s| {
            let ssl_map = s.clone().cast::<Map>();
            SslConfig {
                force_https: ssl_map
                    .get("force_https")
                    .unwrap_or(&Dynamic::from(false))
                    .clone()
                    .cast::<bool>(),
                cert_path: ssl_map
                    .get("cert_path")
                    .unwrap_or(&Dynamic::from(""))
                    .clone()
                    .cast::<String>(),
                key_path: ssl_map
                    .get("key_path")
                    .unwrap_or(&Dynamic::from(""))
                    .clone()
                    .cast::<String>(),
            }
        });

        // Extract cache config
        let cache = map.get("cache").map(|c| {
            let cache_map = c.clone().cast::<Map>();
            CacheConfig {
                enabled: cache_map
                    .get("enabled")
                    .unwrap_or(&Dynamic::from(false))
                    .clone()
                    .cast::<bool>(),
                cache_type: cache_map
                    .get("cache_type")
                    .unwrap_or(&Dynamic::from("memory"))
                    .clone()
                    .cast::<String>(),
                default_ttl: cache_map
                    .get("default_ttl")
                    .unwrap_or(&Dynamic::from(3600_i64))
                    .clone()
                    .cast::<i64>() as u32,
            }
        });

        Ok(WizardConfig {
            features,
            server,
            database,
            auth,
            oauth,
            email,
            security,
            monitoring,
            ssl,
            cache,
            build_info,
        })
    }

    pub fn generate_config_toml(&self, config: &WizardConfig) -> String {
        let mut toml_content = String::new();

        toml_content.push_str("# Rustelo Configuration File\n");
        toml_content.push_str("# Generated by Configuration Wizard\n\n");
        toml_content.push_str("root_path = \".\"\n\n");

        // Features section
        toml_content.push_str("[features]\n");
        for feature in &config.features {
            if feature.enabled {
                toml_content.push_str(&format!("{} = true\n", feature.name));
            }
        }
        toml_content.push('\n');

        // Server section
        toml_content.push_str("[server]\n");
        toml_content.push_str(&format!("protocol = \"{}\"\n", config.server.protocol));
        toml_content.push_str(&format!("host = \"{}\"\n", config.server.host));
        toml_content.push_str(&format!("port = {}\n", config.server.port));
        toml_content.push_str(&format!(
            "environment = \"{}\"\n",
            config.server.environment
        ));
        toml_content.push_str(&format!("workers = {}\n", config.server.workers));
        toml_content.push('\n');

        // Database section
        if let Some(database) = &config.database {
            toml_content.push_str("[database]\n");
            toml_content.push_str(&format!("url = \"{}\"\n", database.url));
            toml_content.push_str(&format!("max_connections = {}\n", database.max_connections));
            toml_content.push_str(&format!("enable_logging = {}\n", database.enable_logging));
            toml_content.push('\n');
        }

        // Authentication section
        if let Some(auth) = &config.auth {
            toml_content.push_str("[auth.jwt]\n");
            if !auth.jwt_secret.is_empty() {
                toml_content.push_str(&format!("secret = \"{}\"\n", auth.jwt_secret));
            } else {
                toml_content.push_str("secret = \"your-secret-key-here\"\n");
            }
            toml_content.push_str(&format!("expiration = {}\n", auth.session_timeout * 60));
            toml_content.push('\n');

            toml_content.push_str("[auth.security]\n");
            toml_content.push_str(&format!(
                "max_login_attempts = {}\n",
                auth.max_login_attempts
            ));
            toml_content.push_str(&format!(
                "require_email_verification = {}\n",
                auth.require_email_verification
            ));
            toml_content.push('\n');
        }

        // OAuth section
        if let Some(oauth) = &config.oauth {
            if oauth.enabled {
                toml_content.push_str("[oauth]\n");
                toml_content.push_str("enabled = true\n\n");

                if let Some(google) = &oauth.google {
                    toml_content.push_str("[oauth.google]\n");
                    toml_content.push_str(&format!("client_id = \"{}\"\n", google.client_id));
                    toml_content
                        .push_str(&format!("client_secret = \"{}\"\n", google.client_secret));
                    toml_content.push_str(&format!("redirect_uri = \"{}\"\n", google.redirect_uri));
                    toml_content.push('\n');
                }

                if let Some(github) = &oauth.github {
                    toml_content.push_str("[oauth.github]\n");
                    toml_content.push_str(&format!("client_id = \"{}\"\n", github.client_id));
                    toml_content
                        .push_str(&format!("client_secret = \"{}\"\n", github.client_secret));
                    toml_content.push_str(&format!("redirect_uri = \"{}\"\n", github.redirect_uri));
                    toml_content.push('\n');
                }
            }
        }

        // Email section
        if let Some(email) = &config.email {
            toml_content.push_str("[email]\n");
            toml_content.push_str(&format!("smtp_host = \"{}\"\n", email.smtp_host));
            toml_content.push_str(&format!("smtp_port = {}\n", email.smtp_port));
            toml_content.push_str(&format!("smtp_username = \"{}\"\n", email.smtp_username));
            toml_content.push_str(&format!("smtp_password = \"{}\"\n", email.smtp_password));
            toml_content.push_str(&format!("from_email = \"{}\"\n", email.from_email));
            toml_content.push_str(&format!("from_name = \"{}\"\n", email.from_name));
            toml_content.push('\n');
        }

        // Security section
        toml_content.push_str("[security]\n");
        toml_content.push_str(&format!("enable_csrf = {}\n", config.security.enable_csrf));
        toml_content.push_str(&format!(
            "rate_limit_requests = {}\n",
            config.security.rate_limit_requests
        ));
        toml_content.push_str(&format!("bcrypt_cost = {}\n", config.security.bcrypt_cost));
        toml_content.push('\n');

        // SSL section
        if let Some(ssl) = &config.ssl {
            toml_content.push_str("[ssl]\n");
            toml_content.push_str(&format!("force_https = {}\n", ssl.force_https));
            if !ssl.cert_path.is_empty() {
                toml_content.push_str(&format!("cert_path = \"{}\"\n", ssl.cert_path));
            }
            if !ssl.key_path.is_empty() {
                toml_content.push_str(&format!("key_path = \"{}\"\n", ssl.key_path));
            }
            toml_content.push('\n');
        }

        // Monitoring section
        if let Some(monitoring) = &config.monitoring {
            if monitoring.enabled {
                toml_content.push_str("[monitoring]\n");
                toml_content.push_str("enabled = true\n");
                toml_content.push_str(&format!("metrics_port = {}\n", monitoring.metrics_port));
                toml_content.push_str(&format!(
                    "prometheus_enabled = {}\n",
                    monitoring.prometheus_enabled
                ));
                toml_content.push('\n');
            }
        }

        // Cache section
        if let Some(cache) = &config.cache {
            if cache.enabled {
                toml_content.push_str("[cache]\n");
                toml_content.push_str("enabled = true\n");
                toml_content.push_str(&format!("type = \"{}\"\n", cache.cache_type));
                toml_content.push_str(&format!("default_ttl = {}\n", cache.default_ttl));
                toml_content.push('\n');
            }
        }

        // Build info section
        toml_content.push_str("[build_info]\n");
        toml_content.push_str(&format!(
            "environment = \"{}\"\n",
            config.build_info.environment
        ));
        toml_content.push_str(&format!(
            "config_version = \"{}\"\n",
            config.build_info.config_version
        ));

        toml_content
    }

    pub fn generate_cargo_features(&self, config: &WizardConfig) -> String {
        let enabled_features: Vec<String> = config
            .features
            .iter()
            .filter(|f| f.enabled)
            .map(|f| format!("\"{}\"", f.name))
            .collect();

        format!("default = [{}]", enabled_features.join(", "))
    }

    pub fn update_cargo_toml(
        &self,
        config: &WizardConfig,
    ) -> Result<(), Box<dyn std::error::Error>> {
        // Try different possible paths for Cargo.toml
        let possible_paths = [
            Path::new("server/Cargo.toml"), // From project root
            Path::new("Cargo.toml"),        // From server directory
            Path::new("../Cargo.toml"),     // From subdirectory
        ];

        let cargo_path = possible_paths
            .iter()
            .find(|path| path.exists())
            .ok_or("Cargo.toml not found in any expected location")?;

        let cargo_content = fs::read_to_string(cargo_path)?;
        let mut cargo_toml: Value = toml::from_str(&cargo_content)?;

        // Update default features
        if let Some(features) = cargo_toml.get_mut("features") {
            if let Some(features_table) = features.as_table_mut() {
                let enabled_features: Vec<String> = config
                    .features
                    .iter()
                    .filter(|f| f.enabled)
                    .map(|f| f.name.clone())
                    .collect();

                features_table.insert(
                    "default".to_string(),
                    Value::Array(enabled_features.into_iter().map(Value::String).collect()),
                );
            }
        }

        // Write back to file
        let updated_content = toml::to_string_pretty(&cargo_toml)?;
        fs::write(cargo_path, updated_content)?;

        Ok(())
    }
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut wizard = ConfigWizard::new();

    match wizard.run_wizard() {
        Ok(config) => {
            println!("\n=== Configuration Summary ===");
            println!(
                "Selected features: {:?}",
                config.features.iter().map(|f| &f.name).collect::<Vec<_>>()
            );
            println!("Server: {}:{}", config.server.host, config.server.port);
            println!("Environment: {}", config.server.environment);

            print!("\nGenerate configuration files? (y/n): ");
            io::stdout().flush()?;
            let mut input = String::new();
            io::stdin().read_line(&mut input)?;

            if input.trim().to_lowercase() == "y" || input.trim().to_lowercase() == "yes" {
                let toml_content = wizard.generate_config_toml(&config);
                let cargo_features = wizard.generate_cargo_features(&config);

                // Save config.toml in project root
                fs::write("../config.toml", toml_content)?;
                println!("✓ Generated config.toml");

                // Update Cargo.toml
                wizard.update_cargo_toml(&config)?;
                println!("✓ Updated Cargo.toml default features");

                println!("\nConfiguration files generated successfully!");
                println!("Default features: {cargo_features}");
            }
        }
        Err(e) => {
            eprintln!("Error running wizard: {e}");
            return Err(e);
        }
    }

    Ok(())
}
