// Metrics computation trait for breaking persistence ↔ analytics circular
// dependency Phase 5.5: Abstraction layer for analytics computations

use async_trait::async_trait;
use chrono::Duration;
use serde::{Deserialize, Serialize};

/// Time period for analytics grouping
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub enum TimePeriod {
    LastHour,
    LastDay,
    LastWeek,
    LastMonth,
    AllTime,
}

impl TimePeriod {
    pub fn duration(&self) -> Duration {
        match self {
            TimePeriod::LastHour => Duration::hours(1),
            TimePeriod::LastDay => Duration::days(1),
            TimePeriod::LastWeek => Duration::days(7),
            TimePeriod::LastMonth => Duration::days(30),
            TimePeriod::AllTime => Duration::days(36500), // 100 years
        }
    }

    pub fn description(&self) -> &'static str {
        match self {
            TimePeriod::LastHour => "Last Hour",
            TimePeriod::LastDay => "Last 24 Hours",
            TimePeriod::LastWeek => "Last 7 Days",
            TimePeriod::LastMonth => "Last 30 Days",
            TimePeriod::AllTime => "All Time",
        }
    }
}

/// Abstraction for computing analytics metrics from execution data.
/// Breaks the persistence ↔ analytics circular dependency by inverting control
/// flow.
#[async_trait]
pub trait AnalyticsComputation: Send + Sync {
    /// Compute agent performance metrics for a time period.
    async fn compute_agent_performance(
        &self,
        executions: Vec<crate::persistence::PersistedExecution>,
        period: TimePeriod,
        agent_id: &str,
    ) -> anyhow::Result<crate::analytics::AgentPerformance>;

    /// Analyze metrics by task type.
    async fn compute_task_type_analytics(
        &self,
        executions: Vec<crate::persistence::PersistedExecution>,
        task_type: &str,
    ) -> anyhow::Result<crate::analytics::TaskTypeAnalytics>;

    /// Generate dashboard metrics snapshot.
    async fn compute_dashboard_metrics(
        &self,
        executions: Vec<crate::persistence::PersistedExecution>,
        period: TimePeriod,
    ) -> anyhow::Result<crate::analytics::DashboardMetrics>;

    /// Generate cost report for auditing.
    async fn compute_cost_report(
        &self,
        executions: Vec<crate::persistence::PersistedExecution>,
        period: TimePeriod,
    ) -> anyhow::Result<crate::analytics::CostEfficiencyReport>;

    /// Calculate learning progress for agent + task type
    async fn compute_learning_progress(
        &self,
        recent_executions: Vec<crate::persistence::PersistedExecution>,
        historical_executions: Vec<crate::persistence::PersistedExecution>,
        agent_id: &str,
        task_type: &str,
    ) -> anyhow::Result<crate::analytics::LearningProgress>;
}
