#![allow(dead_code)] // Config::save is consumed by `/bell`, `/voice`, `/public` slash commands in v0.2.

//! Local config file at `~/.kranth/config.toml`. Stores non-secret preferences
//! (default mode, bell on/off, public-by-default flag). The API key lives in
//! the OS keyring — see `auth.rs`. Never write secrets here.

use std::path::PathBuf;

use anyhow::Context;
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct Config {
    #[serde(default)]
    pub mode: Option<String>, // "1v1" | "panel" | "press" | "pre-mortem"
    #[serde(default)]
    pub bell: bool,
    #[serde(default)]
    pub public_by_default: bool,
    #[serde(default)]
    pub voice_by_default: bool,
}

impl Config {
    pub fn load() -> anyhow::Result<Self> {
        let path = config_path()?;
        if !path.exists() {
            return Ok(Self::default());
        }
        let body = std::fs::read_to_string(&path)
            .with_context(|| format!("reading {}", path.display()))?;
        let cfg: Self = toml::from_str(&body)
            .with_context(|| format!("parsing {}", path.display()))?;
        Ok(cfg)
    }

    pub fn save(&self) -> anyhow::Result<()> {
        let path = config_path()?;
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)?;
        }
        let body = toml::to_string_pretty(self)?;
        std::fs::write(&path, body)
            .with_context(|| format!("writing {}", path.display()))?;
        Ok(())
    }
}

pub fn config_path() -> anyhow::Result<PathBuf> {
    let home = dirs::home_dir().ok_or_else(|| anyhow::anyhow!("could not resolve $HOME"))?;
    Ok(home.join(".kranth").join("config.toml"))
}
