use std::collections::HashMap;
use std::path::Path;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let manifest = rustelo_utils::ManifestResolver::load()?;
    let root = manifest.root();
    let out_dir = std::env::var("OUT_DIR")?;
    let out = Path::new(&out_dir);

    println!("cargo:rerun-if-changed=site/config/");
    println!("cargo:rerun-if-changed=site/i18n/");
    println!("cargo:rerun-if-changed=site/content/");
    println!("cargo:rerun-if-changed=src/");

    // ── Config constants (asset paths, server host/port, content root) ───────
    rustelo_tools::build::config_constants::generate_config_constants(&out_dir)?;

    // ── Route components + content types (routes/*.ncl → generated_routes.rs) ─
    rustelo_tools::build::generate_shared_resources()?;

    // ── Resource contributor (menus, FTL, themes → resource_contributor.rs) ───
    //
    // Load your site configuration here and pass the resource maps.
    // Replace this block with calls to your config loader (e.g. build_config).
    let (menus, footers, themes, ftl, routes) = load_site_resources(root)?;
    rustelo_tools::build::generate_resource_contributor_code(
        "SiteResourceContributor",
        &menus,
        &footers,
        &themes,
        &ftl,
        &routes,
        out,
    )?;

    Ok(())
}

/// Minimal resource loader — replace with your site's Nickel/TOML config loading.
fn load_site_resources(
    root: &Path,
) -> Result<
    (
        HashMap<String, String>,
        HashMap<String, String>,
        HashMap<String, String>,
        HashMap<String, String>,
        HashMap<String, String>,
    ),
    Box<dyn std::error::Error>,
> {
    let mut ftl = HashMap::new();

    // Walk site/i18n/locales/ and collect FTL files
    let locales_dir = root.join("site/i18n/locales");
    if locales_dir.exists() {
        for entry in walkdir::WalkDir::new(&locales_dir)
            .into_iter()
            .filter_map(|e| e.ok())
            .filter(|e| e.path().extension().is_some_and(|x| x == "ftl"))
        {
            let path = entry.path();
            let rel = path.strip_prefix(&locales_dir).unwrap_or(path);
            let key = rel
                .to_string_lossy()
                .replace(['/', '\\'], "_")
                .trim_end_matches(".ftl")
                .to_string();
            let content = std::fs::read_to_string(path)?;
            ftl.insert(key, content);
        }
    }

    // Menus, footers, themes: load from site/config/ as needed.
    // For the minimal template, start with empty maps — add real loading
    // once you have a site config format.
    Ok((
        HashMap::new(), // menus
        HashMap::new(), // footers
        HashMap::new(), // themes
        ftl,
        HashMap::new(), // routes
    ))
}
