//! Agent configuration system (L7).
//!
//! Provides granular control over the agent's cognitive thresholds,
//! linear algebra precision, and HA cluster parameters.

use serde::{Deserialize, Serialize};

/// Configuration for MimirsWell agent.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentConfig {
    /// Agent identifier.
    pub agent_id: String,
    /// Storage backend type (e.g. "urdarbrunnr").
    pub backend: String,
    /// Enable high availability via Raft consensus.
    pub ha_enabled: bool,

    /// Session ID for source tracking. Generated automatically if not set.
    pub session_id: Option<String>,

    /// --- Model Parameters ---

    /// Path to the Sleipnir LFM2.5 GGUF model file.
    /// Default: ./models/sleipnir.gguf
    pub model_path: String,

    /// --- Cognitive Parameters ---

    /// Contradiction threshold (Ginnunga).
    pub contradiction_threshold: f32,
    /// Coherence threshold for consolidation (Hugin).
    pub coherence_threshold: f32,
    /// Memory decay rate lambda (Exponential).
    pub decay_rate: f32,
    /// Metastability target (Edge of Chaos).
    pub target_metastability: f32,

    /// --- Encoding Parameters ---

    /// Use local semantic encoder if available.
    pub use_local_encoder: bool,
    /// Dimensionality of the density manifold.
    pub manifold_dim: usize,
}

impl AgentConfig {
    /// Loads configuration from environment variables with sensible defaults.
    pub fn load() -> Self {
        Self {
            agent_id: std::env::var("MIMIRS_AGENT_ID").unwrap_or_else(|_| "mimir-01".to_string()),
            backend: std::env::var("MIMIRS_BACKEND").unwrap_or_else(|_| "urdarbrunnr".to_string()),
            ha_enabled: std::env::var("MIMIRS_HA_ENABLED")
                .map(|v| v == "true")
                .unwrap_or(true),
            session_id: std::env::var("MIMIRS_SESSION_ID").ok(),
            model_path: std::env::var("MIMIRS_MODEL_PATH")
                .unwrap_or_else(|_| "./models/sleipnir.gguf".to_string()),

            contradiction_threshold: 0.8,
            coherence_threshold: 0.3,
            decay_rate: 1e-5,
            target_metastability: 0.8,

            use_local_encoder: true,
            manifold_dim: 384,
        }
    }
}

impl Default for AgentConfig {
    fn default() -> Self {
        Self::load()
    }
}
