fn main() {
    // cant have both whois features at the same time
    if cfg!(feature = "system-whois") && cfg!(feature = "builtin-whois") {
        panic!("Cannot enable both 'system-whois' and 'builtin-whois' features at the same time");
    }

    let manifest = std::fs::read_to_string("Cargo.toml").expect("Could not read Cargo.toml");

    let mut whois_cmd = "whois".to_string();
    let mut whois_flags = String::new();
    let mut rdap_bootstrap_url = "https://data.iana.org/rdap/dns.json".to_string();

    let mut in_metadata = false;
    for line in manifest.lines() {
        if line.trim() == "[package.metadata.hoardom]" {
            in_metadata = true;
            continue;
        }
        if line.starts_with('[') {
            in_metadata = false;
            continue;
        }
        if in_metadata {
            if let Some(val) = line.strip_prefix("whois-command") {
                if let Some(val) = val.trim().strip_prefix('=') {
                    whois_cmd = val.trim().trim_matches('"').to_string();
                }
            }
            if let Some(val) = line.strip_prefix("whois-flags") {
                if let Some(val) = val.trim().strip_prefix('=') {
                    whois_flags = val.trim().trim_matches('"').to_string();
                }
            }
            if let Some(val) = line.strip_prefix("rdap-bootstrap-url") {
                if let Some(val) = val.trim().strip_prefix('=') {
                    rdap_bootstrap_url = val.trim().trim_matches('"').to_string();
                }
            }
        }
    }

    println!("cargo:rustc-env=HOARDOM_WHOIS_CMD={}", whois_cmd);
    println!("cargo:rustc-env=HOARDOM_WHOIS_FLAGS={}", whois_flags);
    println!(
        "cargo:rustc-env=HOARDOM_RDAP_BOOTSTRAP_URL={}",
        rdap_bootstrap_url
    );

    // Extract list names from Lists.toml (keys that have array values)
    let lists_toml = std::fs::read_to_string("Lists.toml").expect("Could not read Lists.toml");
    let mut list_names = Vec::new();
    for line in lists_toml.lines() {
        let trimmed = line.trim();
        // Match lines like `standard = [` or `all = [`
        if let Some(eq_pos) = trimmed.find(" = [") {
            let name = trimmed[..eq_pos].trim();
            if !name.is_empty() && !name.starts_with('#') {
                list_names.push(name.to_string());
            }
        }
    }
    println!(
        "cargo:rustc-env=HOARDOM_LIST_NAMES={}",
        list_names.join(",")
    );

    // rerun if Cargo.toml or Lists.toml changes
    println!("cargo:rerun-if-changed=Cargo.toml");
    println!("cargo:rerun-if-changed=Lists.toml");
}
