// Configuration Wizard Script for Rustelo Template
// This script interactively generates config.toml and sets Cargo.toml features

// Configuration structure
let config = #{
    features: #{},
    server: #{},
    database: #{},
    auth: #{},
    oauth: #{},
    email: #{},
    security: #{},
    monitoring: #{},
    ssl: #{},
    cache: #{},
    build_info: #{}
};

// Available features with descriptions
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)"
};

// Helper function to ask yes/no questions
fn ask_yes_no(question) {
    print(question + " (y/n): ");
    let answer = input();
    return answer.to_lower() == "y" || answer.to_lower() == "yes";
}

// Helper function to ask for string input
fn ask_string(question, default_value) {
    if default_value != "" {
        print(question + " [" + default_value + "]: ");
    } else {
        print(question + ": ");
    }
    let answer = input();
    return if answer == "" { default_value } else { answer };
}

// Helper function to ask for numeric input
fn ask_number(question, default_value) {
    print(question + " [" + default_value + "]: ");
    let answer = input();
    return if answer == "" { default_value } else { parse_int(answer) };
}

// Main configuration wizard
fn run_wizard() {
    print("=== Rustelo Configuration Wizard ===\n");
    print("This wizard will help you configure your Rustelo application.\n");

    // Ask about features
    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", "127.0.0.1");
    config.server.port = ask_number("Server port", 3030);
    config.server.environment = ask_string("Environment (dev/prod/test)", "dev");
    config.server.workers = ask_number("Number of workers", 4);

    // 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");
        config.database.max_connections = ask_number("Max database connections", 10);
        config.database.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)", "");
        config.auth.session_timeout = ask_number("Session timeout (minutes)", 60);
        config.auth.max_login_attempts = ask_number("Max login attempts", 5);
        config.auth.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");
        config.email.smtp_port = ask_number("SMTP port", 587);
        config.email.smtp_username = ask_string("SMTP username", "");
        config.email.smtp_password = ask_string("SMTP password", "");
        config.email.from_email = ask_string("From email address", "noreply@localhost");
        config.email.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");
        config.ssl.cert_path = ask_string("SSL certificate path", "");
        config.ssl.key_path = ask_string("SSL private key path", "");
    }

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

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

    // Build information
    config.build_info.environment = config.server.environment;
    config.build_info.config_version = "1.0.0";

    return config;
}

// Generate TOML configuration
fn generate_toml(config) {
    let toml_content = "";

    // Root configuration
    toml_content += "# Rustelo Configuration File\n";
    toml_content += "# Generated by Configuration Wizard\n\n";
    toml_content += "root_path = \".\"\n\n";

    // Features section
    toml_content += "[features]\n";
    if config.features.contains("auth") {
        toml_content += "auth = true\n";
    }
    toml_content += "\n";

    // Server section
    toml_content += "[server]\n";
    toml_content += "protocol = \"http\"\n";
    toml_content += "host = \"" + config.server.host + "\"\n";
    toml_content += "port = " + config.server.port + "\n";
    toml_content += "environment = \"" + config.server.environment + "\"\n";
    toml_content += "workers = " + config.server.workers + "\n";
    toml_content += "\n";

    // Database section
    if config.database != () {
        toml_content += "[database]\n";
        toml_content += "url = \"" + config.database.url + "\"\n";
        toml_content += "max_connections = " + config.database.max_connections + "\n";
        toml_content += "enable_logging = " + config.database.enable_logging + "\n";
        toml_content += "\n";
    }

    // Authentication section
    if config.auth != () {
        toml_content += "[auth]\n";
        if config.auth.jwt_secret != "" {
            toml_content += "jwt_secret = \"" + config.auth.jwt_secret + "\"\n";
        }
        toml_content += "session_timeout = " + config.auth.session_timeout + "\n";
        toml_content += "max_login_attempts = " + config.auth.max_login_attempts + "\n";
        toml_content += "require_email_verification = " + config.auth.require_email_verification + "\n";
        toml_content += "\n";
    }

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

        if config.oauth.google != () {
            toml_content += "[oauth.google]\n";
            toml_content += "client_id = \"" + config.oauth.google.client_id + "\"\n";
            toml_content += "client_secret = \"" + config.oauth.google.client_secret + "\"\n";
            toml_content += "redirect_uri = \"" + config.oauth.google.redirect_uri + "\"\n\n";
        }

        if config.oauth.github != () {
            toml_content += "[oauth.github]\n";
            toml_content += "client_id = \"" + config.oauth.github.client_id + "\"\n";
            toml_content += "client_secret = \"" + config.oauth.github.client_secret + "\"\n";
            toml_content += "redirect_uri = \"" + config.oauth.github.redirect_uri + "\"\n\n";
        }
    }

    // Email section
    if config.email != () {
        toml_content += "[email]\n";
        toml_content += "smtp_host = \"" + config.email.smtp_host + "\"\n";
        toml_content += "smtp_port = " + config.email.smtp_port + "\n";
        toml_content += "smtp_username = \"" + config.email.smtp_username + "\"\n";
        toml_content += "smtp_password = \"" + config.email.smtp_password + "\"\n";
        toml_content += "from_email = \"" + config.email.from_email + "\"\n";
        toml_content += "from_name = \"" + config.email.from_name + "\"\n";
        toml_content += "\n";
    }

    // Security section
    toml_content += "[security]\n";
    toml_content += "enable_csrf = " + config.security.enable_csrf + "\n";
    toml_content += "rate_limit_requests = " + config.security.rate_limit_requests + "\n";
    toml_content += "bcrypt_cost = " + config.security.bcrypt_cost + "\n";
    toml_content += "\n";

    // SSL section
    if config.ssl != () {
        toml_content += "[ssl]\n";
        toml_content += "force_https = " + config.ssl.force_https + "\n";
        if config.ssl.cert_path != "" {
            toml_content += "cert_path = \"" + config.ssl.cert_path + "\"\n";
        }
        if config.ssl.key_path != "" {
            toml_content += "key_path = \"" + config.ssl.key_path + "\"\n";
        }
        toml_content += "\n";
    }

    // Monitoring section
    if config.monitoring != () && config.monitoring.enabled {
        toml_content += "[monitoring]\n";
        toml_content += "enabled = true\n";
        toml_content += "metrics_port = " + config.monitoring.metrics_port + "\n";
        toml_content += "prometheus_enabled = " + config.monitoring.prometheus_enabled + "\n";
        toml_content += "\n";
    }

    // Cache section
    if config.cache != () && config.cache.enabled {
        toml_content += "[cache]\n";
        toml_content += "enabled = true\n";
        toml_content += "type = \"" + config.cache.type + "\"\n";
        toml_content += "default_ttl = " + config.cache.default_ttl + "\n";
        toml_content += "\n";
    }

    // Build info section
    toml_content += "[build_info]\n";
    toml_content += "environment = \"" + config.build_info.environment + "\"\n";
    toml_content += "config_version = \"" + config.build_info.config_version + "\"\n";

    return toml_content;
}

// Generate Cargo.toml features
fn generate_cargo_features(selected_features) {
    let features_line = "default = [";

    for i in 0..selected_features.len() {
        features_line += "\"" + selected_features[i] + "\"";
        if i < selected_features.len() - 1 {
            features_line += ", ";
        }
    }

    features_line += "]";

    return features_line;
}

// Main execution
fn main() {
    let config = run_wizard();

    print("\n=== Configuration Summary ===");
    print("Selected features: " + config.features);
    print("Server: " + config.server.host + ":" + config.server.port);
    print("Environment: " + config.server.environment);

    if ask_yes_no("\nGenerate configuration files?") {
        let toml_content = generate_toml(config);
        let cargo_features = generate_cargo_features(config.features);

        print("\n=== Generated config.toml ===");
        print(toml_content);

        print("\n=== Cargo.toml default features ===");
        print(cargo_features);

        print("\nConfiguration generated successfully!");
        print("Copy the above content to your config.toml and update your Cargo.toml accordingly.");
    }
}

// Run the wizard
main();
