//! Codex local config reader.
//!
//! The Codex CLI keeps its primary config in `~/.codex/config.toml` (an
//! `[mcp_servers.<name>]` TOML table). This reader targets the JSON
//! `~/.codex/mcp.json` companion that mirrors the `mcpServers` shape the other
//! clients use, so discovery stays a single JSON code path with no TOML
//! dependency. Reading the TOML config directly is a documented follow-up; if
//! Codex consolidates on one path or format, this module is the single place to
//! update. Read-only.

use std::path::PathBuf;

use super::{parse_mcp_servers_file, ClientSource, DiscoveredServer, DiscoveryError};

/// Discover servers declared in `~/.codex/mcp.json`.
///
/// Empty vec when the file does not exist (Codex is not installed, or only its
/// TOML config is present).
pub fn discover_servers() -> Result<Vec<DiscoveredServer>, DiscoveryError> {
    let Some(path) = config_path() else {
        return Ok(Vec::new());
    };
    parse_mcp_servers_file(&path, ClientSource::Codex)
}

/// Resolve `~/.codex/mcp.json`, or `None` when `$HOME` is unset.
pub(super) fn config_path() -> Option<PathBuf> {
    let home = std::env::var_os("HOME")?;
    Some(PathBuf::from(home).join(".codex").join("mcp.json"))
}

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

    #[test]
    fn config_path_lands_under_dot_codex() {
        if std::env::var_os("HOME").is_none() {
            return;
        }
        let path = config_path().expect("HOME is set");
        assert!(path.ends_with(".codex/mcp.json"), "{path:?}");
    }

    #[test]
    fn discover_is_empty_when_the_file_is_absent() {
        assert!(discover_servers().is_ok());
    }
}
