use crate::{common::config::Config, core::error::TookaError, rules::rules_file::RulesFile};
use anyhow::{Context, Result};
use std::sync::{Arc, Mutex, OnceLock};
pub const CONFIG_VERSION: usize = 0;
pub const CONFIG_FILE_NAME: &str = "tooka.yaml";
pub const RULES_FILE_NAME: &str = "rules.yaml";
pub const DEFAULT_LOGS_FOLDER: &str = "logs";
pub const APP_QUALIFIER: &str = "io";
pub const APP_ORG: &str = "github.benji377";
pub const APP_NAME: &str = "tooka";
static CONFIG: OnceLock<Arc<Mutex<Config>>> = OnceLock::new();
static RULES_FILE: OnceLock<Arc<Mutex<RulesFile>>> = OnceLock::new();
pub fn init_config() -> Result<()> {
let config = Config::load().context("Failed to load configuration")?;
CONFIG
.set(Arc::new(Mutex::new(config)))
.map_err(|_| TookaError::ConfigAlreadyInitialized.into())
}
pub fn init_rules_file() -> Result<()> {
let rules_file = RulesFile::load().context("Failed to load rules file")?;
RULES_FILE
.set(Arc::new(Mutex::new(rules_file)))
.map_err(|_| TookaError::RulesFileAlreadyInitialized.into())
}
pub fn get_locked_rules_file() -> Result<std::sync::MutexGuard<'static, RulesFile>> {
let rules_file = RULES_FILE
.get()
.ok_or_else(|| anyhow::anyhow!("Rules file not initialized"))?;
rules_file
.lock()
.map_err(|e| anyhow::anyhow!("Failed to acquire lock on rules file: {}", e))
}
pub fn get_locked_config() -> Result<std::sync::MutexGuard<'static, Config>> {
let config = CONFIG
.get()
.ok_or_else(|| anyhow::anyhow!("Config not initialized"))?;
config
.lock()
.map_err(|e| anyhow::anyhow!("Failed to acquire lock on config: {}", e))
}