use std::{collections::HashMap, io::Read, sync::OnceLock};

use serde::Deserialize;

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ConfigAvatarAbilityEntry {
    #[serde(rename = "abilityID")]
    pub ability_id: String,
    pub ability_name: String,
    pub ability_override: String,
}

#[derive(Deserialize)]
pub struct ConfigAvatar {
    pub abilities: Vec<ConfigAvatarAbilityEntry>,
}

static AVATAR_CONFIG_MAP: OnceLock<HashMap<String, ConfigAvatar>> = OnceLock::new();

pub fn load_all_config_avatar() -> Result<(), Box<dyn std::error::Error>> {
    let mut map = HashMap::new();

    let mut read_dir = std::fs::read_dir("data/json/avatar/")?;
    while let Some(entry) = read_dir.next() {
        if let Ok(entry) = entry {
            let path = entry.path();
            if path.is_file() {
                let name = path
                    .to_str()
                    .unwrap()
                    .replace("data/json/avatar/ConfigAvatar_", "")
                    .replace(".json", "");
                let mut file = std::fs::File::open(path)?;

                let mut data = String::new();
                file.read_to_string(&mut data)?;

                map.insert(name, serde_json::from_str(&data)?);
            }
        }
    }

    let _ = AVATAR_CONFIG_MAP.set(map);
    Ok(())
}

pub fn get_config_avatar(name: &str) -> Option<&ConfigAvatar> {
    AVATAR_CONFIG_MAP.get().unwrap().get(name)
}
