fyi-core 0.1.0

Core types and traits for fyi
Documentation
//! Configuration generation and conversion utilities.
//!
//! This module contains pure functions for:
//! - Generating hooks configuration
//! - Converting between JSON and TOML formats
//! - Resolving settings paths

use std::path::PathBuf;

use crate::{Config, ConfigFormat, FrameworkAdapter};

use super::options::{InitError, InitOptions};
use super::otel::generate_otel_env;

/// Resolve the settings path for a framework.
///
/// Determines where the hooks configuration should be installed based on
/// the framework and the user's preferences (local vs global, settings_local).
///
/// # Arguments
/// * `adapter` - The framework adapter.
/// * `local` - If true, use project-level config instead of user-level.
/// * `settings_local` - If true, use a `.local` variant (not committed to git).
pub fn get_settings_path(
    adapter: &dyn FrameworkAdapter,
    local: bool,
    settings_local: bool,
) -> Result<PathBuf, InitError> {
    if settings_local {
        // Use project-local path with .local suffix
        let project_path = adapter.project_config_path();
        let file_name = project_path
            .file_stem()
            .and_then(|s| s.to_str())
            .unwrap_or("settings");
        let extension = project_path
            .extension()
            .and_then(|s| s.to_str())
            .unwrap_or("json");
        let local_name = format!("{}.local.{}", file_name, extension);
        Ok(project_path.with_file_name(local_name))
    } else if local {
        Ok(adapter.project_config_path())
    } else {
        adapter
            .user_config_path()
            .ok_or_else(|| InitError::SettingsPath("failed to determine home directory".into()))
    }
}

/// Convert a serde_json::Value to a TOML string.
///
/// Useful for frameworks that use TOML configuration files.
pub fn json_to_toml_string(json: &serde_json::Value) -> Result<String, InitError> {
    // Convert JSON to TOML value via serde
    let toml_value: toml::Value = serde_json::from_value(json.clone())
        .map_err(|e| InitError::Config(format!("failed to convert JSON to TOML: {e}")))?;
    toml::to_string_pretty(&toml_value)
        .map_err(|e| InitError::Config(format!("failed to serialize TOML: {e}")))
}

/// Generate hooks configuration without writing to disk.
///
/// This is useful for previewing what would be installed (e.g., `fyi activate --print`)
/// or for generating configuration to be used elsewhere. The returned JSON includes
/// the `env` key with OTel variables if `options.otel` is true.
///
/// Note: When using [`super::settings::install_settings`] to write config to disk,
/// pass the hooks without the `env` key and instead use
/// [`super::options::InstallSettingsOptions::otel_env`] to provide OTel env vars
/// separately. This allows proper merging with existing env vars.
///
/// # Arguments
/// * `adapter` - The framework adapter.
/// * `config` - The fyi configuration.
/// * `options` - Initialization options.
pub fn generate_config(
    adapter: &dyn FrameworkAdapter,
    config: &Config,
    options: &InitOptions,
) -> serde_json::Value {
    let enabled_events = config.hooks.enabled_hooks();
    let mut hooks_json =
        adapter.generate_hooks_config(&enabled_events, "fyi", options.otel, options.otel_port);

    if options.otel {
        let otel_env = generate_otel_env(options.otel_port);
        hooks_json["env"] = otel_env;
    }

    hooks_json
}

/// Serialize configuration to string in the appropriate format.
///
/// Returns the configuration as a string in either JSON or TOML format,
/// depending on the framework's configuration format.
pub fn config_to_string(
    adapter: &dyn FrameworkAdapter,
    config: &serde_json::Value,
) -> Result<String, InitError> {
    match adapter.config_format() {
        ConfigFormat::Json => serde_json::to_string_pretty(config)
            .map_err(|e| InitError::Config(format!("failed to serialize JSON: {e}"))),
        ConfigFormat::Toml => json_to_toml_string(config),
    }
}

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

    #[test]
    fn test_get_settings_path_global() -> Result<(), String> {
        let adapter = ClaudeAdapter;
        let path = get_settings_path(&adapter, false, false).map_err(|e| e.to_string())?;
        // Should be user config path
        assert!(path.to_string_lossy().contains("settings.json"));
        Ok(())
    }

    #[test]
    fn test_get_settings_path_local() -> Result<(), String> {
        let adapter = ClaudeAdapter;
        let path = get_settings_path(&adapter, true, false).map_err(|e| e.to_string())?;
        // Should be project config path
        assert_eq!(path, adapter.project_config_path());
        Ok(())
    }

    #[test]
    fn test_get_settings_path_settings_local() -> Result<(), String> {
        let adapter = ClaudeAdapter;
        let path = get_settings_path(&adapter, false, true).map_err(|e| e.to_string())?;
        // Should have .local suffix
        assert!(path.to_string_lossy().contains(".local."));
        Ok(())
    }

    #[test]
    fn test_json_to_toml_string() -> Result<(), String> {
        let json = serde_json::json!({
            "key": "value",
            "number": 42
        });
        let toml_str = json_to_toml_string(&json).map_err(|e| e.to_string())?;
        assert!(toml_str.contains("key = \"value\""));
        assert!(toml_str.contains("number = 42"));
        Ok(())
    }

    #[test]
    fn test_generate_config() {
        let config = Config::default();
        let adapter = ClaudeAdapter;
        let options = InitOptions::for_framework("claude")
            .otel(true)
            .otel_port(4318);

        let config_json = generate_config(&adapter, &config, &options);
        assert!(config_json["hooks"].is_object());
        assert!(config_json["env"].is_object());
    }

    #[test]
    fn test_config_to_string_json() -> Result<(), String> {
        let adapter = ClaudeAdapter;
        let config = serde_json::json!({"key": "value"});

        let output = config_to_string(&adapter, &config).map_err(|e| e.to_string())?;
        assert!(output.contains("\"key\""));
        assert!(output.contains("\"value\""));
        Ok(())
    }

    #[test]
    fn test_config_to_string_toml() -> Result<(), String> {
        let adapter = crate::CodexAdapter;
        let config = serde_json::json!({"key": "value"});

        let output = config_to_string(&adapter, &config).map_err(|e| e.to_string())?;
        assert!(output.contains("key = \"value\""));
        Ok(())
    }

    #[test]
    fn test_initialize_result_contains_hooks_with_otel() {
        // Test that generate_config produces correct output with otel
        let config = Config::default();
        let options = InitOptions::for_framework("claude")
            .otel(true)
            .otel_port(9999);

        let hooks_config = generate_config(&ClaudeAdapter, &config, &options);

        // Verify hooks are present
        assert!(hooks_config["hooks"].is_object());

        // Verify otel env is present
        assert_eq!(hooks_config["env"]["CLAUDE_CODE_ENABLE_TELEMETRY"], "1");
        assert_eq!(
            hooks_config["env"]["OTEL_EXPORTER_OTLP_ENDPOINT"],
            "http://127.0.0.1:9999"
        );
    }
}