use std::{
    collections::HashMap,
    sync::{LazyLock, RwLock, RwLockReadGuard, RwLockWriteGuard},
};

use lunar_lib::{config::Config, log::error};
use serde::{Deserialize, Serialize};

static COMMON_CONFIG: LazyLock<RwLock<CommonConfig>> = LazyLock::new(|| {
    let config = match CommonConfig::load() {
        Ok(config) => config,
        Err(err) => {
            error!(
                "Could not load common config from file, assuming defaults. Reason: {err:?}"
            );
            CommonConfig::default()
        }
    };
    RwLock::new(config)
});

/// Returns a read-only guard to the common config.
///
/// # Panics
///
/// This function will panic if the internal read/write lock is poisoned
pub fn common_config() -> RwLockReadGuard<'static, CommonConfig> {
    COMMON_CONFIG.read().unwrap()
}

/// Returns a mutable guard to the common config.
///
/// # Panics
///
/// This function will panic if the internal read/write lock is poisoned
pub fn common_config_mut() -> RwLockWriteGuard<'static, CommonConfig> {
    COMMON_CONFIG.write().unwrap()
}

#[derive(Debug, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct CommonConfig {
    pub main: MainSettings,
    pub loudnorm: LoudnormSettings,

    #[serde(skip_serializing_if = "HashMap::is_empty")]
    pub export_preset: HashMap<String, ExportConfig>,
}

mod core_impls;

mod main_settings;
pub use main_settings::*;

mod loudnorm_settings;
pub use loudnorm_settings::*;

mod export_config;
pub use export_config::*;
