use crate::schema::{ConfigItem, ConfigType};
use anyhow::Result;
use std::collections::HashMap;
use std::fmt::Write;

pub fn generate_consts(
    items: &[ConfigItem],
    values: &HashMap<String, toml::Value>,
) -> Result<String> {
    let mut buffer = String::new();

    writeln!(buffer, "// Generated by anaxa-config")?;
    writeln!(buffer)?;
    write!(buffer, "pub const ANAXA_BUILDER_VERSION: &str = ")?;
    writeln!(buffer, "\"{}\";", env!("CARGO_PKG_VERSION"))?;

    for item in items {
        if let Some(val) = values.get(&item.name) {
            if let Some(formatted) = item.config_type.format_value_rust(val) {
                let rust_type = item
                    .rust_type
                    .as_deref()
                    .unwrap_or_else(|| item.config_type.rust_type());
                writeln!(
                    buffer,
                    "#[allow(dead_code)]\n/// {}\npub const {}: {} = {};",
                    item.name, item.desc, rust_type, formatted
                )?;
            }
        }
    }

    Ok(buffer)
}

/// Generates a vector of strings suitable for `--cfg` flags.
pub fn generate_rust_cfgs(
    items: &[ConfigItem],
    values: &HashMap<String, toml::Value>,
) -> Result<Vec<String>> {
    let mut cfgs = Vec::new();

    for item in items {
        if let Some(val) = values.get(&item.name) {
            if item.config_type == ConfigType::Bool && val.as_bool() == Some(true) {
                cfgs.push(item.name.clone());
            }
        }
    }

    Ok(cfgs)
}
