//! Advanced PostgreSQL installation with comprehensive checks
//!
//! This example demonstrates all the advanced installation features:
//! - Platform detection
//! - System requirements checking
//! - Version availability verification
//! - Comprehensive post-installation verification
//! - System information gathering

use lmrc_postgres::{PostgresConfig, PostgresManager, SystemRequirements};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Initialize logging
    tracing_subscriber::fmt::init();

    println!("=== Advanced PostgreSQL Installation ===\n");

    // Build configuration
    let config = PostgresConfig::builder()
        .version("15")
        .database_name("production_db")
        .username("app_user")
        .password("secure_password_789")
        .max_connections(150)
        .shared_buffers("384MB")
        .build()?;

    // Create manager
    let manager = PostgresManager::builder()
        .config(config)
        .server_ip("192.168.1.100")
        .ssh_user("root")
        .ssh_password("your_ssh_password")
        .build()?;

    // Step 1: Detect platform
    println!("Step 1: Detecting platform...");
    let platform = manager.detect_platform().await?;
    println!("✓ Platform detected: {}", platform.as_str());

    if !platform.is_supported() {
        eprintln!("❌ Platform not supported!");
        return Ok(());
    }

    // Step 2: Get system information
    println!("\nStep 2: Gathering system information...");
    let sys_info = manager.get_system_info().await?;
    println!("✓ System Information:");
    println!("  - Platform: {}", sys_info.platform.as_str());
    println!("  - OS Version: {}", sys_info.os_version);
    println!("  - RAM: {}MB", sys_info.total_ram_mb);
    println!("  - Free Disk: {}MB", sys_info.free_disk_mb);
    println!("  - CPU Cores: {}", sys_info.cpu_cores);

    // Step 3: Check system requirements
    println!("\nStep 3: Checking system requirements...");
    let requirements = SystemRequirements {
        min_ram_mb: 2048,   // Require 2GB RAM
        min_disk_mb: 10240, // Require 10GB disk
        min_cpu_cores: 2,   // Require 2 CPU cores
    };

    match manager.check_requirements(Some(requirements)).await {
        Ok(_) => println!("✓ System requirements met!"),
        Err(e) => {
            eprintln!("❌ System requirements not met: {}", e);
            eprintln!("You can still proceed, but performance may be impacted.");
            // In production, you might want to return here
        }
    }

    // Step 4: Check PostgreSQL version availability
    println!("\nStep 4: Checking PostgreSQL version availability...");
    if manager.check_version_available("15").await? {
        println!("✓ PostgreSQL 15 is available for installation");
    } else {
        eprintln!("❌ PostgreSQL 15 is not available in repositories");
        return Ok(());
    }

    // Step 5: Check if already installed
    println!("\nStep 5: Checking if PostgreSQL is already installed...");
    if manager.is_installed().await? {
        let version = manager.get_installed_version().await?;
        println!(
            "⚠️  PostgreSQL is already installed (version: {:?})",
            version
        );

        // Example: Upgrade if needed
        if let Some(current) = version
            && current != "15"
        {
            println!("Would you like to upgrade from {} to 15? (y/n)", current);
            // In a real application, get user input here
            // manager.upgrade("15").await?;
        }
    } else {
        println!("✓ PostgreSQL not installed, proceeding with installation");

        // Step 6: Install PostgreSQL
        println!("\nStep 6: Installing PostgreSQL...");
        manager.install().await?;
        println!("✓ PostgreSQL installed");
    }

    // Step 7: Verify installation comprehensively
    println!("\nStep 7: Verifying installation...");
    manager.verify_installation().await?;
    println!("✓ Installation verified successfully!");

    // Step 8: Configure database and server
    println!("\nStep 8: Configuring database and server...");
    manager.configure().await?;
    println!("✓ Configuration complete");

    // Step 9: Test connection
    println!("\nStep 9: Testing database connection...");
    manager.test_connection().await?;
    println!("✓ Connection test successful!");

    println!("\n=== Installation Complete ===");
    println!("PostgreSQL is ready for use!");

    // Print connection string
    println!("\nConnection details:");
    println!("  Host: {}", manager.server_ip());
    println!("  Port: {}", manager.config().port);
    println!("  Database: {}", manager.config().database_name);
    println!("  Username: {}", manager.config().username);

    Ok(())
}
