// Analytics API endpoints - KG analytics and insights
// Phase 6: REST endpoints for performance, cost, and learning analytics

use axum::{
    extract::{Path, Query, State},
    http::StatusCode,
    response::{IntoResponse, Response},
    Json,
};
use serde::{Deserialize, Serialize};
use vapora_knowledge_graph::{
    AgentPerformance, CostEfficiencyReport, DashboardMetrics, TaskTypeAnalytics,
};

use crate::api::state::AppState;

/// Query parameters for analytics endpoints
#[derive(Debug, Deserialize)]
pub struct AnalyticsQuery {
    /// Time period for analysis: hour, day, week, month, all
    #[serde(default = "default_period")]
    pub period: String,
}

fn default_period() -> String {
    "week".to_string()
}

/// Analytics response wrapper
#[derive(Debug, Serialize)]
pub struct AnalyticsResponse<T> {
    pub success: bool,
    pub data: Option<T>,
    pub error: Option<String>,
}

impl<T> AnalyticsResponse<T> {
    fn error(msg: String) -> Self {
        Self {
            success: false,
            data: None,
            error: Some(msg),
        }
    }
}

impl<T: Serialize> IntoResponse for AnalyticsResponse<T> {
    fn into_response(self) -> Response {
        (StatusCode::OK, Json(self)).into_response()
    }
}

/// Analytics error type
#[derive(Debug)]
pub enum AnalyticsError {
    QueryFailed(String),
    NotFound(String),
}

impl IntoResponse for AnalyticsError {
    fn into_response(self) -> Response {
        let (status, msg) = match self {
            AnalyticsError::QueryFailed(e) => (StatusCode::INTERNAL_SERVER_ERROR, e),
            AnalyticsError::NotFound(e) => (StatusCode::NOT_FOUND, e),
        };
        (status, Json(AnalyticsResponse::<()>::error(msg))).into_response()
    }
}

/// Get agent performance metrics
pub async fn get_agent_performance(
    State(_state): State<AppState>,
    Path(agent_id): Path<String>,
    Query(_params): Query<AnalyticsQuery>,
) -> Result<AnalyticsResponse<AgentPerformance>, AnalyticsError> {
    // For now, return a placeholder since AppState doesn't have KGAnalyticsService
    // yet In real implementation, we'd fetch from service
    Err(AnalyticsError::NotFound(format!(
        "Agent analytics service not yet initialized for {}",
        agent_id
    )))
}

/// Get task type analytics
pub async fn get_task_type_analytics(
    State(_state): State<AppState>,
    Path(task_type): Path<String>,
    Query(_params): Query<AnalyticsQuery>,
) -> Result<AnalyticsResponse<TaskTypeAnalytics>, AnalyticsError> {
    Err(AnalyticsError::NotFound(format!(
        "Task type analytics service not yet initialized for {}",
        task_type
    )))
}

/// Get system dashboard metrics
pub async fn get_dashboard_metrics(
    State(_state): State<AppState>,
    Query(_params): Query<AnalyticsQuery>,
) -> Result<AnalyticsResponse<DashboardMetrics>, AnalyticsError> {
    Err(AnalyticsError::NotFound(
        "Dashboard metrics service not yet initialized".to_string(),
    ))
}

/// Get cost efficiency report
pub async fn get_cost_report(
    State(_state): State<AppState>,
    Query(_params): Query<AnalyticsQuery>,
) -> Result<AnalyticsResponse<CostEfficiencyReport>, AnalyticsError> {
    Err(AnalyticsError::NotFound(
        "Cost report service not yet initialized".to_string(),
    ))
}

/// Summary report combining all analytics
#[derive(Debug, Serialize)]
pub struct AnalyticsSummary {
    pub period: String,
    pub dashboard_metrics: Option<DashboardMetrics>,
    pub cost_report: Option<CostEfficiencyReport>,
}

/// Get comprehensive analytics summary
pub async fn get_analytics_summary(
    State(_state): State<AppState>,
    Query(_params): Query<AnalyticsQuery>,
) -> Result<AnalyticsResponse<AnalyticsSummary>, AnalyticsError> {
    Err(AnalyticsError::NotFound(
        "Analytics summary service not yet initialized".to_string(),
    ))
}
