use arcis_compiler::profile_info::{PerformanceStore, PerformanceTracker, ProfileInfo};
use std::{error::Error, sync::RwLock};

static INSTRUCTION_PERFORMANCE_TRACKER: RwLock<Option<PerformanceStore>> = RwLock::new(None);

pub fn is_performance_tracking_enabled() -> bool {
    INSTRUCTION_PERFORMANCE_TRACKER.read().unwrap().is_enabled()
}

pub fn track_instruction_performance(
    instruction: &str,
    profile_info: ProfileInfo,
) -> Result<(), Box<dyn Error>> {
    INSTRUCTION_PERFORMANCE_TRACKER
        .write()
        .unwrap()
        .track(instruction, profile_info)
}

pub fn load_performance_tracker(strict_mode: bool, csv_file: &str) -> Result<(), Box<dyn Error>> {
    let tracker = PerformanceStore::from_csv(strict_mode, csv_file)?;
    INSTRUCTION_PERFORMANCE_TRACKER
        .write()
        .unwrap()
        .replace(tracker);
    Ok(())
}
pub fn save_performance_tracker(csv_file: &str) -> Result<(), Box<dyn Error>> {
    INSTRUCTION_PERFORMANCE_TRACKER
        .write()
        .unwrap()
        .as_ref()
        .unwrap()
        .to_csv(csv_file)?;
    Ok(())
}

pub fn get_instructions() -> Vec<String> {
    INSTRUCTION_PERFORMANCE_TRACKER
        .read()
        .unwrap()
        .as_ref()
        .unwrap()
        .get_instructions()
}
