use std::sync::OnceLock;

use gacha_config::GachaConfiguration;
use jsonc_parser::{parse_to_serde_value, ParseOptions};
use serde::Deserialize;

use crate::{action::ActionConfig, DataLoadError};

pub mod gacha_config;

const GACHA_CONFIG_NAME: &str = "gacha.jsonc";
static GACHACONF: OnceLock<GachaConfiguration> = OnceLock::new();

#[derive(Deserialize, Debug)]
pub struct EventGraphConfig {
    pub event_id: u32,
    pub actions: Vec<ActionConfig>,
}

pub(crate) fn load_gacha_config(path: &str) -> Result<(), DataLoadError> {
    let jsonc_data = std::fs::read_to_string(format!("{path}/{GACHA_CONFIG_NAME}"))
        .map_err(|err| DataLoadError::IoError(err))?;

    let json_value = parse_to_serde_value(
        &jsonc_data,
        &ParseOptions {
            allow_comments: true,
            allow_loose_object_property_names: false,
            allow_trailing_commas: true,
        },
    )
        .map_err(|err| DataLoadError::JsoncParseError(err))?
        .unwrap();

    let mut result = serde_json::from_value::<GachaConfiguration>(json_value)
        .map_err(|err| DataLoadError::FromJsonError(String::from("GachaConfiguration"), err))?;
    result.post_configure();

    GACHACONF.set(result).unwrap();
    Ok(())
}

pub fn global_gacha_config() -> &'static GachaConfiguration {
    GACHACONF.get().unwrap()
}
