use super::registry::{is_known_setting, nearest_setting_key, LEGACY_SETTING_KEYS, SETTING_KEYS};
use super::store::{load_config, save_config};
use crate::errors::AppError;
use crate::i18n::validation;
pub fn get_setting(key: &str) -> Result<Option<String>, AppError> {
let cfg = load_config()?;
if let Some(v) = cfg.settings.get(key) {
return Ok(Some(v.clone()));
}
for (legacy, replacement) in LEGACY_SETTING_KEYS {
if *replacement == key {
if let Some(v) = cfg.settings.get(*legacy) {
return Ok(Some(v.clone()));
}
}
}
Ok(None)
}
pub fn set_setting(key: &str, value: &str) -> Result<(), AppError> {
if key.trim().is_empty() {
return Err(AppError::Validation("config key must be non-empty".into()));
}
if !is_known_setting(key) {
if let Some(replacement) = LEGACY_SETTING_KEYS
.iter()
.find(|(legacy, _)| *legacy == key)
.map(|(_, replacement)| *replacement)
{
return Err(AppError::Validation(validation::config_key_retired(
key,
replacement,
)));
}
return Err(AppError::Validation(validation::config_key_unknown(
key,
nearest_setting_key(key),
)));
}
if let Some(entry) = SETTING_KEYS.iter().find(|entry| entry.key == key) {
if let Some(expectation) = entry.kind.expectation() {
if !entry.kind.accepts(value) {
return Err(AppError::Validation(validation::config_value_invalid(
key,
value,
&expectation,
)));
}
}
}
let mut cfg = load_config()?;
cfg.settings.insert(key.to_string(), value.to_string());
save_config(&cfg)
}
pub fn unset_setting(key: &str) -> Result<bool, AppError> {
let mut cfg = load_config()?;
let removed = cfg.settings.remove(key).is_some();
if removed {
save_config(&cfg)?;
}
Ok(removed)
}
pub fn list_settings() -> Result<std::collections::BTreeMap<String, String>, AppError> {
let cfg = load_config()?;
Ok(cfg.settings)
}