fyi-core 0.1.0

Core types and traits for fyi
Documentation
//! Core initialization logic for fyi.
//!
//! This module provides programmatic access to fyi initialization,
//! allowing Rust code to initialize fyi without going through the CLI.
//!
//! # Module Structure
//!
//! The initialization logic is split into focused submodules:
//! - `config`: Configuration generation and conversion utilities
//! - `options`: Initialization options and result types
//! - `otel`: OpenTelemetry configuration utilities
//! - `settings`: Settings file installation logic
//!
//! # Example
//!
//! ```ignore
//! use fyi_core::{Config, init::{InitOptions, initialize}};
//!
//! let config = Config::load()?;
//!
//! // Initialize for a single framework
//! let options = InitOptions::for_framework("claude")
//!     .otel(true)
//!     .otel_port(4318);
//!
//! let result = initialize(&config, options)?;
//! println!("Hooks installed to: {}", result.settings_path.display());
//!
//! // Or initialize for multiple frameworks
//! let options = InitOptions::for_frameworks(vec!["claude".into(), "gemini".into()])
//!     .local(true);
//!
//! let results = initialize_all(&config, options)?;
//! for result in results {
//!     println!("Hooks installed to: {}", result.settings_path.display());
//! }
//! ```

mod config;
mod options;
mod otel;
mod settings;

// Re-export public API from submodules
pub use config::{config_to_string, generate_config, get_settings_path, json_to_toml_string};
pub use options::{InitError, InitOptions, InitResult, InstallSettingsOptions};
pub use otel::{DEFAULT_OTEL_PORT, OTEL_ENV_KEYS, generate_otel_env};
pub use settings::install_settings;

use crate::{Config, get_adapter};

/// Initialize fyi for a single framework.
///
/// This is the main entry point for programmatic initialization of a single
/// framework. It:
/// 1. Resolves the framework adapter
/// 2. Generates the hooks configuration
/// 3. Installs the configuration to the appropriate settings file
///
/// Unlike the CLI command, this function does not:
/// - Print output to stderr
/// - Check for port collisions
/// - Handle the `--print` flag
///
/// Those concerns are handled by the CLI layer.
///
/// # Arguments
/// * `config` - The fyi configuration.
/// * `options` - Initialization options. Uses the first framework from the list,
///   or falls back to the deprecated `framework` field.
///
/// # Returns
/// An `InitResult` containing information about what was initialized.
pub fn initialize(config: &Config, options: InitOptions) -> Result<InitResult, InitError> {
    let frameworks = options.get_frameworks();
    let framework = frameworks
        .first()
        .cloned()
        .unwrap_or_else(|| "claude".to_string());

    initialize_framework(config, &framework, &options)
}

/// Initialize fyi for multiple frameworks.
///
/// This function initializes fyi for all specified frameworks, returning
/// a result for each one.
///
/// # Arguments
/// * `config` - The fyi configuration.
/// * `options` - Initialization options.
///
/// # Returns
/// A vector of `InitResult` for each initialized framework, or an error
/// if any framework fails to initialize.
pub fn initialize_all(config: &Config, options: InitOptions) -> Result<Vec<InitResult>, InitError> {
    let frameworks = options.get_frameworks();
    let mut results = Vec::with_capacity(frameworks.len());

    for framework in &frameworks {
        let result = initialize_framework(config, framework, &options)?;
        results.push(result);
    }

    Ok(results)
}

/// Initialize fyi for a specific framework.
///
/// This is the internal implementation used by both `initialize` and `initialize_all`.
///
/// # Arguments
/// * `config` - The fyi configuration.
/// * `framework` - The framework name to initialize.
/// * `options` - Initialization options.
fn initialize_framework(
    config: &Config,
    framework: &str,
    options: &InitOptions,
) -> Result<InitResult, InitError> {
    // Get the framework adapter
    let adapter =
        get_adapter(framework).ok_or_else(|| InitError::UnknownFramework(framework.to_string()))?;

    // Resolve settings path
    let settings_path = get_settings_path(adapter, options.local, options.settings_local)?;

    // Generate hooks config (without env - install_settings will handle otel env separately)
    let enabled_events = config.hooks.enabled_hooks();
    let hooks_json =
        adapter.generate_hooks_config(&enabled_events, "fyi", options.otel, options.otel_port);

    // Prepare OTel env vars (passed separately to install_settings for proper merging)
    let otel_env = if options.otel {
        Some(generate_otel_env(options.otel_port))
    } else {
        None
    };

    // Install settings (handles merging with existing config and otel env vars)
    install_settings(
        adapter,
        &settings_path,
        &hooks_json,
        &InstallSettingsOptions {
            otel_env: otel_env.clone(),
            remove_otel: options.remove_otel,
        },
    )?;

    // Build final hooks_config for return value (include env if otel enabled)
    let mut hooks_config = hooks_json;
    if let Some(env) = otel_env {
        hooks_config["env"] = env;
    }

    // Get database path
    let db_path = config.db_path().ok();

    Ok(InitResult {
        db_path,
        settings_path,
        hooks_config,
    })
}

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

    #[test]
    fn test_init_error_unknown_framework() {
        let config = Config::default();
        let options = InitOptions::for_framework("unknown");

        let result = initialize(&config, options);
        assert!(matches!(result, Err(InitError::UnknownFramework(_))));
    }
}