fyi-core 0.1.0

Core types and traits for fyi
Documentation
//! Initialization options and result types.
//!
//! This module contains the configuration structs used for initialization:
//! - [`InitOptions`]: Options for controlling initialization behavior
//! - [`InstallSettingsOptions`]: Options for settings installation
//! - [`InitResult`]: Result of a successful initialization
//! - [`InitError`]: Error types for initialization operations

use std::path::PathBuf;

use super::otel::DEFAULT_OTEL_PORT;

/// Options for core initialization.
///
/// This struct contains all the options needed to initialize fyi programmatically.
/// For CLI usage, the CLI layer adds additional options like `print` and `db_only`.
///
/// This struct is the single source of truth for initialization settings, shared
/// between CLI commands (`init`, `activate`) and programmatic API usage.
#[derive(Debug, Clone)]
pub struct InitOptions {
    /// Frameworks to install hooks for (e.g., "claude", "gemini", "codex").
    /// If empty, auto-detection will be used (CLI behavior).
    #[deprecated(since = "0.2.0", note = "use `frameworks` field instead")]
    pub framework: String,
    /// Frameworks to install hooks for (e.g., `["claude", "gemini", "codex"]`).
    /// If empty, auto-detection will be used (CLI behavior).
    pub frameworks: Vec<String>,
    /// Install hooks to project config instead of global.
    pub local: bool,
    /// Install hooks to project local config (not committed to git).
    pub settings_local: bool,
    /// Configure OpenTelemetry env vars for token tracking.
    pub otel: bool,
    /// Port for OTel server.
    pub otel_port: u16,
    /// Remove OTel configuration (disables token tracking).
    pub remove_otel: bool,
}

impl Default for InitOptions {
    fn default() -> Self {
        #[expect(deprecated)]
        Self {
            framework: String::new(),
            frameworks: vec![],
            local: false,
            settings_local: false,
            otel: false,
            otel_port: DEFAULT_OTEL_PORT,
            remove_otel: false,
        }
    }
}

impl InitOptions {
    /// Create new InitOptions with default values.
    pub fn new() -> Self {
        Self::default()
    }

    /// Create InitOptions for a single framework.
    pub fn for_framework(framework: impl Into<String>) -> Self {
        let framework = framework.into();
        #[expect(deprecated)]
        Self {
            framework: framework.clone(),
            frameworks: vec![framework],
            ..Default::default()
        }
    }

    /// Create InitOptions for multiple frameworks.
    pub fn for_frameworks(frameworks: Vec<String>) -> Self {
        #[expect(deprecated)]
        Self {
            framework: frameworks.first().cloned().unwrap_or_default(),
            frameworks,
            ..Default::default()
        }
    }

    /// Get the list of frameworks to initialize.
    /// Returns frameworks if non-empty, otherwise returns a single-element vec with framework.
    pub fn get_frameworks(&self) -> Vec<String> {
        if self.frameworks.is_empty() {
            #[expect(deprecated)]
            if self.framework.is_empty() {
                vec![]
            } else {
                vec![self.framework.clone()]
            }
        } else {
            self.frameworks.clone()
        }
    }

    /// Set install location to project config instead of global.
    pub fn local(mut self, local: bool) -> Self {
        self.local = local;
        self
    }

    /// Set install location to project local config (not committed to git).
    pub fn settings_local(mut self, settings_local: bool) -> Self {
        self.settings_local = settings_local;
        self
    }

    /// Enable OpenTelemetry configuration for token tracking.
    pub fn otel(mut self, otel: bool) -> Self {
        self.otel = otel;
        self
    }

    /// Set the port for OTel server.
    pub fn otel_port(mut self, port: u16) -> Self {
        self.otel_port = port;
        self
    }

    /// Remove OTel configuration (disables token tracking).
    pub fn remove_otel(mut self, remove: bool) -> Self {
        self.remove_otel = remove;
        self
    }
}

/// Options for installing settings.
#[derive(Debug, Clone, Default)]
pub struct InstallSettingsOptions {
    /// OTel environment variables to add.
    pub otel_env: Option<serde_json::Value>,
    /// Whether to remove existing OTel configuration.
    pub remove_otel: bool,
}

/// Result of initialization.
///
/// Contains information about what was initialized and where.
#[derive(Debug, Clone)]
pub struct InitResult {
    /// Path to the database (if database initialization was requested).
    pub db_path: Option<PathBuf>,
    /// Path where settings/hooks were installed.
    pub settings_path: PathBuf,
    /// The hooks configuration that was generated.
    pub hooks_config: serde_json::Value,
}

/// Error types for initialization operations.
#[derive(Debug, thiserror::Error)]
pub enum InitError {
    /// Unknown framework name.
    #[error("unknown framework: {0}")]
    UnknownFramework(String),

    /// Failed to determine settings path.
    #[error("failed to determine settings path: {0}")]
    SettingsPath(String),

    /// Failed to read or write settings file.
    #[error("settings file error: {0}")]
    SettingsFile(#[from] std::io::Error),

    /// Failed to parse or serialize configuration.
    #[error("configuration error: {0}")]
    Config(String),
}

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

    #[test]
    #[expect(deprecated)]
    fn test_init_options_default() {
        let opts = InitOptions::default();
        // Default has empty framework/frameworks, relies on CLI or for_framework()
        assert_eq!(opts.framework, "");
        assert!(opts.frameworks.is_empty());
        assert!(!opts.local);
        assert!(!opts.settings_local);
        assert!(!opts.otel);
        // otel_port defaults to 4318 (standard OTel HTTP/JSON port)
        assert_eq!(opts.otel_port, 4318);
        assert!(!opts.remove_otel);
    }

    #[test]
    fn test_init_options_for_framework() {
        let opts = InitOptions::for_framework("claude");
        assert_eq!(opts.get_frameworks(), vec!["claude"]);
        assert!(!opts.local);
        assert!(!opts.otel);
    }

    #[test]
    fn test_init_options_for_frameworks() {
        let opts = InitOptions::for_frameworks(vec!["claude".into(), "gemini".into()]);
        assert_eq!(opts.get_frameworks(), vec!["claude", "gemini"]);
    }

    #[test]
    fn test_init_options_builder() {
        let opts = InitOptions::for_framework("claude")
            .local(true)
            .otel(true)
            .otel_port(9999);
        assert_eq!(opts.get_frameworks(), vec!["claude"]);
        assert!(opts.local);
        assert!(opts.otel);
        assert_eq!(opts.otel_port, 9999);
    }
}