KiThe 0.3.24

A numerical suite for chemical kinetics and thermodynamics, combustion, TGA, heat and mass transfer,chemical equilibrium, chemical engeneering
use crate::gui::experimental_kinetics_gui::model::TGAGUIError;
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::{Path, PathBuf};

const DEFAULT_N_POINTS: usize = 1000;
const DEFAULT_SYMBOLIC_EXPRESSION: &str = "mass";

#[derive(Debug, Clone, Copy, Deserialize, Serialize)]
pub struct CalibrationLine {
    k: f64,
    b: f64,
}

impl CalibrationLine {
    pub fn new(k: f64, b: f64) -> Self {
        Self { k, b }
    }

    pub fn k(&self) -> f64 {
        self.k
    }

    pub fn b(&self) -> f64 {
        self.b
    }

    pub fn set_k(&mut self, k: f64) {
        self.k = k;
    }

    pub fn set_b(&mut self, b: f64) {
        self.b = b;
    }
}

impl Default for CalibrationLine {
    fn default() -> Self {
        //m = k*U+b
        Self { k: -1.0, b: 40.0 }
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Settings {
    calibration_line: Option<CalibrationLine>,
    #[serde(default)]
    default_instrument_name: Option<String>,
    #[serde(default)]
    default_operator_name: Option<String>,
    n_points: Option<usize>,
    symbolic_expression: Option<String>,
    log_level: Option<String>,
    #[serde(default)]
    catalog: CatalogSettings,
}

#[derive(Debug, Deserialize, Serialize)]
struct SettingsFile {
    calibration_line: Option<CalibrationLine>,
    #[serde(default)]
    default_instrument_name: Option<String>,
    #[serde(default)]
    default_operator_name: Option<String>,
    n_points: Option<usize>,
    symbolic_expression: Option<String>,
    log_level: Option<String>,
    #[serde(default)]
    catalog: CatalogSettings,
}

/// User-selected catalog locations and non-secret server connection profiles.
/// Authentication tokens/passwords must be stored in the OS credential store.
#[derive(Debug, Clone, Default, Deserialize, Serialize, PartialEq, Eq)]
pub struct CatalogSettings {
    pub local_library_id: Option<String>,
    pub local_library_path: Option<PathBuf>,
    pub active_server_profile: Option<String>,
    #[serde(default)]
    pub server_profiles: Vec<CatalogServerProfile>,
}

#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub struct CatalogServerProfile {
    pub id: String,
    pub display_name: String,
    pub base_url: String,
}

impl Default for Settings {
    fn default() -> Self {
        Self {
            calibration_line: Some(CalibrationLine::default()),
            default_instrument_name: None,
            default_operator_name: None,
            n_points: Some(DEFAULT_N_POINTS),
            symbolic_expression: Some(DEFAULT_SYMBOLIC_EXPRESSION.to_string()),
            log_level: Some("info".to_string()),
            catalog: CatalogSettings::default(),
        }
    }
}

impl Settings {
    pub fn new() -> Result<Self, TGAGUIError> {
        Self::load_from_default_locations()
    }

    pub fn calibration_line(&self) -> Option<CalibrationLine> {
        self.calibration_line
    }

    pub fn default_instrument_name(&self) -> Option<&str> {
        self.default_instrument_name.as_deref()
    }

    pub fn default_operator_name(&self) -> Option<&str> {
        self.default_operator_name.as_deref()
    }

    pub fn n_points(&self) -> Option<usize> {
        self.n_points
    }

    pub fn symbolic_expression(&self) -> Option<&str> {
        self.symbolic_expression.as_deref()
    }

    pub fn log_level(&self) -> Option<&str> {
        self.log_level.as_deref()
    }

    pub fn catalog(&self) -> &CatalogSettings {
        &self.catalog
    }

    pub fn set_catalog(&mut self, catalog: CatalogSettings) {
        self.catalog = catalog;
    }

    pub fn set_calibration_line(&mut self, calibration_line: Option<CalibrationLine>) {
        self.calibration_line = calibration_line;
    }

    pub fn set_calibration_coeffs(&mut self, k: f64, b: f64) {
        self.calibration_line = Some(CalibrationLine::new(k, b));
    }

    pub fn set_acquisition_defaults(
        &mut self,
        instrument_name: Option<String>,
        operator_name: Option<String>,
    ) {
        self.default_instrument_name = normalize_optional_text(instrument_name);
        self.default_operator_name = normalize_optional_text(operator_name);
    }

    pub fn set_n_points(&mut self, n_points: Option<usize>) {
        self.n_points = n_points;
    }

    pub fn set_symbolic_expression<S: Into<String>>(&mut self, symbolic_expression: Option<S>) {
        self.symbolic_expression = symbolic_expression.map(Into::into);
    }

    pub fn set_log_level<S: Into<String>>(&mut self, log_level: Option<S>) {
        self.log_level = log_level.map(Into::into);
    }

    pub fn load_from_path(path: &Path) -> Result<Self, TGAGUIError> {
        let raw = fs::read_to_string(path).map_err(|e| {
            TGAGUIError::SettingsErrors(format!(
                "failed to read settings file '{}': {e}",
                path.display()
            ))
        })?;

        let parsed: SettingsFile = serde_json::from_str(&raw).map_err(|e| {
            TGAGUIError::SettingsErrors(format!(
                "failed to parse settings json '{}': {e}",
                path.display()
            ))
        })?;

        let mut settings = Self::default();
        if let Some(calibration_line) = parsed.calibration_line {
            settings.calibration_line = Some(calibration_line);
        }
        settings.default_instrument_name = normalize_optional_text(parsed.default_instrument_name);
        settings.default_operator_name = normalize_optional_text(parsed.default_operator_name);
        if let Some(n_points) = parsed.n_points {
            settings.n_points = Some(n_points);
        }
        if let Some(symbolic_expression) = parsed.symbolic_expression {
            settings.symbolic_expression = Some(symbolic_expression);
        }
        if let Some(log_level) = parsed.log_level {
            settings.log_level = Some(log_level);
        }
        settings.catalog = parsed.catalog;
        Ok(settings)
    }

    pub fn load_from_default_locations() -> Result<Self, TGAGUIError> {
        for candidate in Self::default_config_candidates() {
            if candidate.is_file() {
                return Self::load_from_path(&candidate);
            }
        }
        Ok(Self::default())
    }

    fn default_config_candidates() -> Vec<PathBuf> {
        let names = [
            "tgasettings",
            "tgasettings.json",
            "tga_settings",
            "tga_settings.json",
            "tga-settings",
            "tga-settings.json",
            "TGASettings",
            "TGASettings.json",
        ];

        names.into_iter().map(PathBuf::from).collect()
    }

    /// Saves settings to a JSON file at the specified path
    pub fn save_to_file(&self, path: &Path) -> Result<(), TGAGUIError> {
        let json = serde_json::to_string_pretty(self).map_err(|e| {
            TGAGUIError::SettingsErrors(format!("Failed to serialize settings: {e}"))
        })?;

        fs::write(path, json).map_err(|e| {
            TGAGUIError::SettingsErrors(format!(
                "Failed to write settings to '{}': {e}",
                path.display()
            ))
        })?;

        Ok(())
    }

    /// Saves settings to the default location (tgasettings.json in current directory)
    pub fn save_to_default_location(&self) -> Result<(), TGAGUIError> {
        self.save_to_file(Path::new("tgasettings.json"))
    }

    /// Creates or recreates the settings file with current settings
    pub fn create_or_recreate_config(&self) -> Result<(), TGAGUIError> {
        self.save_to_default_location()
    }
}

fn normalize_optional_text(value: Option<String>) -> Option<String> {
    value.and_then(|value| {
        let value = value.trim();
        (!value.is_empty()).then(|| value.to_string())
    })
}

#[cfg(test)]
mod catalog_settings_tests {
    use super::*;

    #[test]
    fn legacy_settings_without_catalog_still_load() {
        let legacy = r#"{
            "calibration_line": {"k": -1.0, "b": 40.0},
            "n_points": 1000,
            "symbolic_expression": "mass",
            "log_level": "info"
        }"#;
        let file: SettingsFile = serde_json::from_str(legacy).unwrap();
        assert_eq!(file.catalog, CatalogSettings::default());
    }

    #[test]
    fn catalog_settings_round_trip_without_credentials_or_default_paths() {
        let settings = CatalogSettings {
            local_library_id: Some("library-123".into()),
            local_library_path: Some(PathBuf::from("E:/lab/archive")),
            active_server_profile: Some("lab-server".into()),
            server_profiles: vec![CatalogServerProfile {
                id: "lab-server".into(),
                display_name: "Lab catalog".into(),
                base_url: "https://catalog.example.org/api".into(),
            }],
        };
        let json = serde_json::to_string(&settings).unwrap();
        let restored: CatalogSettings = serde_json::from_str(&json).unwrap();
        assert_eq!(restored, settings);
        assert!(!json.to_ascii_lowercase().contains("password"));
        assert!(!json.to_ascii_lowercase().contains("token"));
        assert_eq!(CatalogSettings::default().local_library_path, None);
    }

    #[test]
    fn acquisition_defaults_round_trip_and_legacy_settings_use_empty_defaults() {
        let legacy = r#"{"calibration_line":{"k":-1.0,"b":40.0}}"#;
        let path = tempfile::NamedTempFile::new().unwrap();
        std::fs::write(path.path(), legacy).unwrap();
        let legacy_settings = Settings::load_from_path(path.path()).unwrap();
        assert_eq!(legacy_settings.default_instrument_name(), None);
        assert_eq!(legacy_settings.default_operator_name(), None);

        let mut settings = Settings::default();
        settings.set_acquisition_defaults(Some("TGA-04 / INV-882".into()), Some("A. User".into()));
        settings.save_to_file(path.path()).unwrap();
        let restored = Settings::load_from_path(path.path()).unwrap();
        assert_eq!(restored.default_instrument_name(), Some("TGA-04 / INV-882"));
        assert_eq!(restored.default_operator_name(), Some("A. User"));

        settings.set_acquisition_defaults(Some("  ".into()), None);
        assert_eq!(settings.default_instrument_name(), None);
    }
}