//! @docs ARCHITECTURE:Networking
//!
//! ### AI Assist Note
//! **Engine Health (Static Heartbeat)**: Orchestrates the lightweight
//! verification of the Tadpole OS engine's operational status.
//! Features **Real-Time Telemetry Summary**: returns the current
//! engine version, server timestamp, and active agent count.
//! Implements **Low-Overhead Monitoring**: designed for
//! high-frequency polling by load balancers and dashboard health
//! indicators without impacting systemic performance. AI agents
//! should distinguish between this static heartbeat and deep
//! diagnostic scans provided by the `/v1/oversight/security/health`
//! endpoint (SYS-01).
//!
//! ### 🔍 Debugging & Observability
//! - **Failure Path**: 503 Service Unavailable if the Axum router
//!   is saturated, incorrect agent counts due to registry sync delays,
//!   or timestamp drift across distributed bunkers.
//! - **Telemetry Link**: Search for `tadpole_online_rust` in health
//!   dashboard logs for uptime verification.
//! - **Trace Scope**: `server-rs::routes::health`
//!

use crate::error::AppError;
use crate::state::AppState;
use axum::http::StatusCode;
use axum::response::IntoResponse;
use axum::{extract::State, Json};
use serde::Serialize;
use std::sync::Arc;

/// Heartbeat status response containing system telemetry and feature flags.
#[derive(Serialize)]
pub struct HealthResponse {
    /// Operational status string.
    pub status: String,
    /// Overall health state of the engine.
    pub health_state: crate::types::SystemHealthState,
    /// Current engine version from Cargo.toml.
    pub version: String,
    /// ISO 8601 server timestamp.
    pub heartbeat: String,
    /// Count of currently registered agent nodes.
    pub active_agents: usize,
    /// List of enabled compile-time features (e.g., "neural-audio", "vector-memory").
    pub features: Vec<String>,
}

/// A simple heartbeat endpoint that mirrors the old `router.get("/health")` in Express.
#[tracing::instrument(skip(state), fields(trace_id = tracing::field::Empty, request_id = tracing::field::Empty, http_status = tracing::field::Empty), name = "system::health")]
pub async fn health_check(
    State(state): State<Arc<AppState>>,
) -> Result<impl IntoResponse, AppError> {
    #[allow(unused_mut)]
    let mut features = Vec::new();

    #[cfg(feature = "neural-audio")]
    features.push("neural-audio".to_string());

    #[cfg(feature = "vector-memory")]
    features.push("vector-memory".to_string());

    let health_state = state.health_state();
    let status = match health_state {
        crate::types::SystemHealthState::Ready => "tadpole_online_rust".to_string(),
        crate::types::SystemHealthState::Warming => "tadpole_warming_rust".to_string(),
        crate::types::SystemHealthState::Degraded => "tadpole_degraded_rust".to_string(),
    };

    Ok((
        StatusCode::OK,
        Json(HealthResponse {
            status,
            health_state,
            version: env!("CARGO_PKG_VERSION").to_string(),
            heartbeat: chrono::Utc::now().to_rfc3339(),
            active_agents: state.registry.agents.len(),
            features,
        }),
    ))
}

// Metadata: [health]
