use thiserror::Error;

const DEFAULT_DEEPSEEK_BASE_URL: &str = "https://api.deepseek.com";
const DEFAULT_DEEPSEEK_MODEL: &str = "deepseek-chat";

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DeepSeekSettings {
    pub api_key: String,
    pub base_url: String,
    pub model: String,
}

impl DeepSeekSettings {
    pub fn from_env() -> Result<Self, ConfigError> {
        let api_key = std::env::var("DEEPSEEK_API_KEY")
            .map_err(|_| ConfigError::MissingEnv("DEEPSEEK_API_KEY"))?;
        let base_url = std::env::var("DEEPSEEK_BASE_URL")
            .unwrap_or_else(|_| DEFAULT_DEEPSEEK_BASE_URL.to_string());
        let model =
            std::env::var("DEEPSEEK_MODEL").unwrap_or_else(|_| DEFAULT_DEEPSEEK_MODEL.to_string());

        if api_key.trim().is_empty() {
            return Err(ConfigError::EmptyValue("DEEPSEEK_API_KEY"));
        }
        if base_url.trim().is_empty() {
            return Err(ConfigError::EmptyValue("DEEPSEEK_BASE_URL"));
        }
        if model.trim().is_empty() {
            return Err(ConfigError::EmptyValue("DEEPSEEK_MODEL"));
        }

        Ok(Self {
            api_key,
            base_url,
            model,
        })
    }
}

#[derive(Debug, Error, Clone, PartialEq, Eq)]
pub enum ConfigError {
    #[error("missing environment variable: {0}")]
    MissingEnv(&'static str),
    #[error("environment variable must not be empty: {0}")]
    EmptyValue(&'static str),
}
