//! Advanced analytics module for Claude Code usage analysis
//!
//! Provides time series trends, forecasting, usage pattern detection,
//! and actionable insights to optimize costs and productivity.

use chrono::{DateTime, Utc};
use std::sync::Arc;

use crate::models::config::AnomalyThresholds;
use crate::models::session::SessionMetadata;

pub mod anomalies;
pub mod discover;
pub mod discover_llm;
pub mod forecasting;
pub mod insights;
pub mod optimization;
pub mod patterns;
pub mod plugin_usage;
pub mod tool_chains;
pub mod trends;

#[cfg(test)]
mod tests;

pub use anomalies::{
    detect_anomalies, detect_daily_cost_spikes, Anomaly, AnomalyMetric, AnomalySeverity,
    DailyCostAnomaly,
};
pub use discover::{
    collect_sessions_data as discover_collect_sessions, discover_patterns, run_discover,
    DiscoverConfig, DiscoverSuggestion, SessionData as DiscoverSessionData, SuggestionCategory,
};
pub use discover_llm::{call_claude_cli as discover_call_llm, LlmSuggestion};
pub use forecasting::{forecast_usage, ForecastData, TrendDirection};
pub use insights::{generate_budget_alerts, generate_insights, Alert};
pub use optimization::{
    generate_cost_suggestions, generate_model_recommendations, CostSuggestion, OptimizationCategory,
};
pub use patterns::{detect_patterns, UsagePatterns};
pub use plugin_usage::{aggregate_plugin_usage, PluginAnalytics, PluginType, PluginUsage};
pub use tool_chains::{analyze_tool_chains, ToolChain, ToolChainAnalysis};
pub use trends::{compute_trends, SessionDurationStats, TrendsData};

/// Period selection for analytics computation
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Period {
    /// Last N days from now
    Days(usize),
    /// All loaded sessions (honest: not "all time", limited by DataStore)
    Available,
}

impl Period {
    /// Last 7 days
    pub fn last_7d() -> Self {
        Self::Days(7)
    }

    /// Last 30 days
    pub fn last_30d() -> Self {
        Self::Days(30)
    }

    /// Last 90 days
    pub fn last_90d() -> Self {
        Self::Days(90)
    }

    /// All available sessions
    pub fn available() -> Self {
        Self::Available
    }

    /// Convert to days (for filtering)
    pub fn days(&self) -> usize {
        match self {
            Period::Days(n) => *n,
            Period::Available => 36500, // 100 years (effectively all)
        }
    }

    /// Display label (shows loaded count for Available)
    pub fn display(&self, total_loaded: usize) -> String {
        match self {
            Period::Days(n) => format!("Last {} days", n),
            Period::Available => format!("All loaded ({} sessions)", total_loaded),
        }
    }
}

/// Per-tool token and cost attribution for a period
#[derive(Debug, Clone)]
pub struct ToolTokenStat {
    pub tool_name: String,
    pub call_count: usize,
    pub tokens: u64,
    /// Fraction of total tool tokens (0.0..1.0)
    pub pct_of_total: f64,
    /// Estimated cost proportional to period total cost
    pub est_cost_usd: f64,
    /// est_cost_usd / call_count (0 if call_count == 0)
    pub cost_per_call: f64,
}

/// Complete analytics data for a period
#[derive(Debug, Clone)]
pub struct AnalyticsData {
    /// Time series trends
    pub trends: TrendsData,
    /// Usage forecasting
    pub forecast: ForecastData,
    /// Behavioral patterns
    pub patterns: UsagePatterns,
    /// Actionable insights
    pub insights: Vec<String>,
    /// Tool chain bigram/trigram analysis
    pub tool_chains: Option<ToolChainAnalysis>,
    /// Cost optimization suggestions
    pub cost_suggestions: Vec<optimization::CostSuggestion>,
    /// Session-level anomalies (Z-score based)
    pub anomalies: Vec<anomalies::Anomaly>,
    /// Daily cost spikes
    pub daily_spikes: Vec<anomalies::DailyCostAnomaly>,
    /// Per-tool token and cost breakdown for the period
    pub tool_token_stats: Vec<ToolTokenStat>,
    /// Number of sessions in the analyzed period
    pub sessions_in_period: usize,
    /// Timestamp of computation
    pub computed_at: DateTime<Utc>,
    /// Period analyzed
    pub period: Period,
    /// Effective anomaly thresholds used for this computation
    pub anomaly_thresholds: AnomalyThresholds,
}

impl AnalyticsData {
    /// Compute analytics from sessions (sync function)
    ///
    /// This is a sync function for simplicity. If computation exceeds 16ms
    /// (render deadline), caller should offload to `tokio::task::spawn_blocking`.
    ///
    /// # Performance
    /// Target: <100ms for 1000 sessions over 30 days
    pub fn compute(sessions: &[Arc<SessionMetadata>], period: Period) -> Self {
        Self::compute_inner(sessions, period, &AnomalyThresholds::default())
    }

    /// Compute analytics using custom anomaly thresholds from settings.json.
    pub fn compute_with_thresholds(
        sessions: &[Arc<SessionMetadata>],
        period: Period,
        thresholds: &AnomalyThresholds,
    ) -> Self {
        Self::compute_inner(sessions, period, thresholds)
    }

    fn compute_inner(
        sessions: &[Arc<SessionMetadata>],
        period: Period,
        thresholds: &AnomalyThresholds,
    ) -> Self {
        use chrono::Local;

        let trends = compute_trends(sessions, period.days());
        let forecast = forecast_usage(&trends);
        let patterns = detect_patterns(sessions, period.days());
        let insights = generate_insights(&trends, &patterns, &forecast);

        let cutoff = Local::now() - chrono::Duration::days(period.days() as i64);
        let period_sessions: Vec<Arc<SessionMetadata>> = sessions
            .iter()
            .filter(|s| {
                s.first_timestamp
                    .map(|ts| ts.with_timezone(&Local) >= cutoff)
                    .unwrap_or(false)
            })
            .cloned()
            .collect();

        let sessions_in_period = period_sessions.len();
        let anomalies_detected =
            anomalies::detect_anomalies_with_thresholds(&period_sessions, thresholds);
        let daily_spikes_detected = anomalies::detect_daily_cost_spikes_with_thresholds(
            &period_sessions,
            period.days(),
            thresholds,
        );

        // Aggregate per-tool token usage across all sessions
        let mut aggregated_tool_tokens: std::collections::HashMap<String, u64> =
            std::collections::HashMap::new();
        for session in sessions {
            for (tool, &tokens) in &session.tool_token_usage {
                *aggregated_tool_tokens.entry(tool.clone()).or_default() += tokens;
            }
        }

        // Aggregate per-tool call counts and token usage for the period only
        let mut period_tool_calls: std::collections::HashMap<String, usize> =
            std::collections::HashMap::new();
        let mut period_tool_tokens: std::collections::HashMap<String, u64> =
            std::collections::HashMap::new();
        for session in &period_sessions {
            for (tool, &calls) in &session.tool_usage {
                *period_tool_calls.entry(tool.clone()).or_default() += calls;
            }
            for (tool, &tokens) in &session.tool_token_usage {
                *period_tool_tokens.entry(tool.clone()).or_default() += tokens;
            }
        }

        // Estimate period cost from trend data
        let total_cost_estimate: f64 = trends.daily_cost.iter().sum();

        // Build per-tool stats sorted by token usage descending
        let total_tool_tokens: u64 = period_tool_tokens.values().sum();
        let mut tool_token_stats: Vec<ToolTokenStat> = period_tool_tokens
            .iter()
            .map(|(name, &tokens)| {
                let pct = if total_tool_tokens > 0 {
                    tokens as f64 / total_tool_tokens as f64
                } else {
                    0.0
                };
                let est_cost = total_cost_estimate * pct;
                let calls = *period_tool_calls.get(name).unwrap_or(&0);
                let cost_per_call = if calls > 0 {
                    est_cost / calls as f64
                } else {
                    0.0
                };
                ToolTokenStat {
                    tool_name: name.clone(),
                    call_count: calls,
                    tokens,
                    pct_of_total: pct,
                    est_cost_usd: est_cost,
                    cost_per_call,
                }
            })
            .collect();
        tool_token_stats.sort_by(|a, b| b.tokens.cmp(&a.tokens));

        // Generate cost suggestions (plugin_analytics populated with empty data here;
        // full plugin analytics with dead-code detection requires skill/command lists
        // which are provided by DataStore when calling the analytics tab)
        let mut cost_suggestions = optimization::generate_cost_suggestions(
            &plugin_usage::PluginAnalytics::empty(),
            &aggregated_tool_tokens,
            total_cost_estimate,
        );

        // Append model downgrade recommendations
        let model_recs =
            optimization::generate_model_recommendations(sessions, total_cost_estimate);
        cost_suggestions.extend(model_recs);
        // Re-sort by potential savings descending after merge
        cost_suggestions.sort_by(|a, b| {
            b.potential_savings
                .partial_cmp(&a.potential_savings)
                .unwrap_or(std::cmp::Ordering::Equal)
        });

        Self {
            trends,
            forecast,
            patterns,
            insights,
            tool_chains: Some(analyze_tool_chains(sessions)),
            cost_suggestions,
            anomalies: anomalies_detected,
            daily_spikes: daily_spikes_detected,
            tool_token_stats,
            sessions_in_period,
            computed_at: Utc::now(),
            period,
            anomaly_thresholds: thresholds.clone(),
        }
    }

    /// Graceful fallback if stats-cache.json missing
    ///
    /// Cost forecasting requires pricing data from StatsCache.
    /// If unavailable, returns limited analytics with warning.
    pub fn from_sessions_only(sessions: &[Arc<SessionMetadata>], period: Period) -> Self {
        tracing::warn!("Stats cache missing, computing analytics from sessions only");

        Self {
            trends: compute_trends(sessions, period.days()),
            forecast: ForecastData::unavailable("Stats cache required for cost forecasting"),
            patterns: detect_patterns(sessions, period.days()),
            insights: vec!["Limited insights: stats cache unavailable".to_string()],
            tool_chains: Some(analyze_tool_chains(sessions)),
            cost_suggestions: Vec::new(),
            anomalies: Vec::new(),
            daily_spikes: Vec::new(),
            tool_token_stats: Vec::new(),
            sessions_in_period: sessions.len(),
            computed_at: Utc::now(),
            period,
            anomaly_thresholds: AnomalyThresholds::default(),
        }
    }
}
