use std::collections::HashSet;
use std::env;
use std::fs::File;
use std::io::{BufWriter, Write};
use std::path::Path;

fn main() {
    let path = Path::new(&env::var("OUT_DIR").unwrap()).join("entities_generated.rs");
    let mut file = BufWriter::new(File::create(&path).unwrap());

    let mut seen_keys = HashSet::new();
    let mut map = phf_codegen::Map::new();
    let entities: Vec<(String, String)> = entities::ENTITIES
        .iter()
        .filter(|entity| entity.entity.ends_with(";"))
        .filter_map(|entity| {
            let key = entity
                .entity
                .strip_prefix("&")
                .expect("needs to start with ampersand")
                .strip_suffix(";")
                .expect("needs to end with semicolon")
                .to_lowercase();

            if seen_keys.contains(&key) {
                return None;
            }
            seen_keys.insert(key.clone());
            Some((key, format!("{:?}", entity.characters)))
        })
        .collect();

    for (entity, replacement) in entities.iter() {
        map.entry(entity.as_str(), replacement.as_str());
    }

    write!(
        &mut file,
        "#[allow(clippy::pedantic)]\nstatic ENTITY_MAP: phf::Map<&'static str, &'static str> = {}",
        map.build()
    )
    .unwrap();
    writeln!(&mut file, ";").unwrap();
}
