//! File-based configuration example.
//!
//! This example creates a config file and then loads it using cfgmatic-files.
//!
//! Run with:
//! ```bash
//! cargo run --example file_config --features files
//! ```

use serde::Deserialize;
use std::fs;
use std::path::PathBuf;

#[derive(Debug, Default, Deserialize)]
struct AppConfig {
    app_name: String,
    version: String,
    debug: bool,
    server: ServerConfig,
}

#[derive(Debug, Default, Deserialize)]
struct ServerConfig {
    port: u16,
    host: String,
}

fn main() {
    println!("File-based Configuration Example");
    println!();

    // Create a temporary config directory
    let config_dir = PathBuf::from("/tmp/cfgmatic_example");
    fs::create_dir_all(&config_dir).expect("Failed to create config dir");

    // Create a sample config file
    let config_file = config_dir.join("config.toml");
    let config_content = r#"
app_name = "My Awesome App"
version = "1.0.0"
debug = true

[server]
port = 3000
host = "0.0.0.0"
"#;

    fs::write(&config_file, config_content).expect("Failed to write config file");
    println!("Created config file: {}", config_file.display());

    // Load configuration directly from file
    let config: AppConfig = match fs::read_to_string(&config_file) {
        Ok(content) => match toml::from_str(&content) {
            Ok(cfg) => {
                println!("\nConfiguration loaded from file:");
                cfg
            }
            Err(e) => {
                println!("\nFailed to parse config: {e}");
                return;
            }
        },
        Err(e) => {
            println!("\nFailed to read config file: {e}");
            return;
        }
    };

    println!("  App: {} v{}", config.app_name, config.version);
    println!("  Debug: {}", config.debug);
    println!("  Server: {}:{}", config.server.host, config.server.port);

    // Cleanup
    let _ = fs::remove_dir_all(&config_dir);
    println!("\nCleaned up temporary files.");
}
