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

/// Generate a `load_config()` function by scanning the given `config_dir`.
/// Writes the generated file to `out_path`.
pub fn generate(config_dir: &Path, out_path: &Path) -> std::io::Result<()> {
    let mut mod_rs = String::new();

    mod_rs.push_str("\n/// Generated by Luminos Config\n/// DO NOT EDIT MANUALLY!\n");

    // Scan all Rust files except mod.rs
    for entry in fs::read_dir(config_dir)? {
        let entry = entry?;
        let path = entry.path();

        // Only process files with .rs extension
        if path.is_file() && path.extension().and_then(|s| s.to_str()) == Some("rs") {
            match path.file_stem().and_then(|s| s.to_str()) {
                Some("mod") | None => {} // skip mod.rs or non-rust files
                Some(name) => {
                    mod_rs.push_str(&format!("pub mod {};\n", name));
                }
            }
        }
    }

    // Generate the load_config function
    mod_rs.push_str("\npub fn load_config() -> luminos_config::Config {\n");
    mod_rs.push_str("    let mut cfg = luminos_config::Config::new();\n");

    for entry in fs::read_dir(config_dir)? {
        let entry = entry?;
        let path = entry.path();

        if path.is_file() && path.extension().and_then(|s| s.to_str()) == Some("rs") {
            match path.file_stem().and_then(|s| s.to_str()) {
                Some("mod") | None => {} // skip mod.rs or non-rust files
                Some(name) => {
                    mod_rs.push_str(&format!("    cfg.insert_section(\"{0}\", &{0}::config());\n", name));
                }
            }
        }
    }

    mod_rs.push_str("    cfg\n}\n");

    // Write to file
    let mut file = File::create(out_path)?;
    file.write_all(mod_rs.as_bytes())?;

    Ok(())
}
