//! Analytics CLI Tools
//!
//! Command-line interface for analytics operations:
//! - Query and search analytics data
//! - Generate reports and summaries
//! - Monitor real-time events
//! - Export data in various formats
//! - System health checks

use super::{
    AnalyticsEvent, EventLevel, LogSource,
    search::{AnalyticsSearch, SearchQuery, TimeRange},
    collector::{AnalyticsCollector, CollectorConfig},
};
use anyhow::{Context, Result};
use chrono::{Duration, Utc};
use clap::{Parser, Subcommand, ValueEnum};
use serde_json;
use std::path::PathBuf;
use std::io::{self, Write};

/// Analytics CLI Application
#[derive(Parser)]
#[command(name = "analytics", about = "Analytics CLI for navigation, server, and browser logs")]
pub struct AnalyticsCli {
    #[command(subcommand)]
    pub command: AnalyticsCommand,
}

/// Analytics commands
#[derive(Subcommand)]
pub enum AnalyticsCommand {
    /// Search analytics events
    Search {
        /// Text to search for
        #[arg(short, long)]
        text: Option<String>,

        /// Regex pattern
        #[arg(short, long)]
        regex: Option<String>,

        /// Filter by source
        #[arg(short, long)]
        source: Option<Vec<AnalyticsSource>>,

        /// Filter by event level
        #[arg(short, long)]
        level: Option<Vec<AnalyticsLevel>>,

        /// Hours back to search (default: 24)
        #[arg(long, default_value = "24")]
        hours: i64,

        /// Maximum results to return
        #[arg(short, long, default_value = "50")]
        limit: usize,

        /// Output format
        #[arg(short, long, default_value = "table")]
        format: OutputFormat,

        /// Include error events only
        #[arg(long)]
        errors_only: bool,

        /// Minimum duration in milliseconds
        #[arg(long)]
        min_duration: Option<u64>,

        /// Export to file
        #[arg(short, long)]
        export: Option<PathBuf>,
    },

    /// Show analytics dashboard
    Dashboard {
        /// Refresh interval in seconds
        #[arg(short, long, default_value = "30")]
        refresh: u64,

        /// Hours of data to show
        #[arg(long, default_value = "24")]
        hours: i64,
    },

    /// Generate analytics report
    Report {
        /// Report type
        #[arg(short, long, default_value = "summary")]
        report_type: ReportType,

        /// Time period in hours
        #[arg(short, long, default_value = "24")]
        hours: i64,

        /// Output file
        #[arg(short, long)]
        output: Option<PathBuf>,

        /// Include detailed breakdown
        #[arg(long)]
        detailed: bool,
    },

    /// Monitor real-time events
    Monitor {
        /// Filter by source
        #[arg(short, long)]
        source: Option<Vec<AnalyticsSource>>,

        /// Filter by level
        #[arg(short, long)]
        level: Option<Vec<AnalyticsLevel>>,

        /// Show only errors
        #[arg(long)]
        errors_only: bool,
    },

    /// Show system statistics
    Stats {
        /// Hours back to analyze
        #[arg(long, default_value = "24")]
        hours: i64,

        /// Show breakdown by source
        #[arg(long)]
        by_source: bool,

        /// Show hourly distribution
        #[arg(long)]
        hourly: bool,
    },

    /// Export analytics data
    Export {
        /// Export format
        #[arg(short, long, default_value = "json")]
        format: ExportFormat,

        /// Output file
        #[arg(short, long)]
        output: PathBuf,

        /// Hours back to export
        #[arg(long, default_value = "24")]
        hours: i64,

        /// Filter by source
        #[arg(short, long)]
        source: Option<Vec<AnalyticsSource>>,
    },

    /// Health check
    Health {
        /// Show detailed health information
        #[arg(long)]
        detailed: bool,
    },
}

/// Analytics source filter
#[derive(Clone, ValueEnum)]
pub enum AnalyticsSource {
    Navigation,
    RouteCache,
    Server,
    Browser,
    System,
}

impl From<AnalyticsSource> for LogSource {
    fn from(source: AnalyticsSource) -> Self {
        match source {
            AnalyticsSource::Navigation => LogSource::Navigation,
            AnalyticsSource::RouteCache => LogSource::RouteCache,
            AnalyticsSource::Server => LogSource::Server,
            AnalyticsSource::Browser => LogSource::Browser,
            AnalyticsSource::System => LogSource::System,
        }
    }
}

/// Analytics level filter
#[derive(Clone, ValueEnum)]
pub enum AnalyticsLevel {
    Trace,
    Debug,
    Info,
    Warn,
    Error,
    Critical,
}

impl From<AnalyticsLevel> for EventLevel {
    fn from(level: AnalyticsLevel) -> Self {
        match level {
            AnalyticsLevel::Trace => EventLevel::Trace,
            AnalyticsLevel::Debug => EventLevel::Debug,
            AnalyticsLevel::Info => EventLevel::Info,
            AnalyticsLevel::Warn => EventLevel::Warn,
            AnalyticsLevel::Error => EventLevel::Error,
            AnalyticsLevel::Critical => EventLevel::Critical,
        }
    }
}

/// Output formats
#[derive(Clone, ValueEnum)]
pub enum OutputFormat {
    Table,
    Json,
    Csv,
    Summary,
}

/// Report types
#[derive(Clone, ValueEnum)]
pub enum ReportType {
    Summary,
    Errors,
    Performance,
    Navigation,
    Browser,
    Server,
}

/// Export formats
#[derive(Clone, ValueEnum)]
pub enum ExportFormat {
    Json,
    Jsonl,
    Csv,
    Tsv,
}

/// Analytics CLI handler
pub struct AnalyticsCliHandler {
    search_engine: AnalyticsSearch,
}

impl AnalyticsCliHandler {
    /// Create new CLI handler
    pub fn new() -> Self {
        Self {
            search_engine: AnalyticsSearch::new(),
        }
    }

    /// Execute CLI command
    pub async fn execute(&mut self, command: AnalyticsCommand) -> Result<()> {
        match command {
            AnalyticsCommand::Search {
                text,
                regex,
                source,
                level,
                hours,
                limit,
                format,
                errors_only,
                min_duration,
                export,
            } => {
                self.handle_search(text, regex, source, level, hours, limit, format, errors_only, min_duration, export).await
            }

            AnalyticsCommand::Dashboard { refresh, hours } => {
                self.handle_dashboard(refresh, hours).await
            }

            AnalyticsCommand::Report { report_type, hours, output, detailed } => {
                self.handle_report(report_type, hours, output, detailed).await
            }

            AnalyticsCommand::Monitor { source, level, errors_only } => {
                self.handle_monitor(source, level, errors_only).await
            }

            AnalyticsCommand::Stats { hours, by_source, hourly } => {
                self.handle_stats(hours, by_source, hourly).await
            }

            AnalyticsCommand::Export { format, output, hours, source } => {
                self.handle_export(format, output, hours, source).await
            }

            AnalyticsCommand::Health { detailed } => {
                self.handle_health_check(detailed).await
            }
        }
    }

    /// Handle search command
    async fn handle_search(
        &mut self,
        text: Option<String>,
        regex: Option<String>,
        source: Option<Vec<AnalyticsSource>>,
        level: Option<Vec<AnalyticsLevel>>,
        hours: i64,
        limit: usize,
        format: OutputFormat,
        errors_only: bool,
        min_duration: Option<u64>,
        export: Option<PathBuf>,
    ) -> Result<()> {
        let query = SearchQuery {
            text,
            regex,
            sources: source.map(|s| s.into_iter().map(|src| src.into()).collect()),
            event_types: None,
            levels: level.map(|l| l.into_iter().map(|lvl| lvl.into()).collect()),
            time_range: Some(TimeRange::last_hours(hours)),
            paths: None,
            session_ids: None,
            has_errors: if errors_only { Some(true) } else { None },
            min_duration_ms: min_duration,
            max_duration_ms: None,
            limit: Some(limit),
            sort: None,
        };

        // Load sample data for demonstration
        self.load_sample_data().await;

        let results = self.search_engine.search(query).await?;

        match format {
            OutputFormat::Table => self.print_table_results(&results),
            OutputFormat::Json => self.print_json_results(&results)?,
            OutputFormat::Csv => self.print_csv_results(&results)?,
            OutputFormat::Summary => self.print_summary_results(&results),
        }

        if let Some(export_path) = export {
            self.export_results(&results, &export_path).await?;
            println!("Results exported to: {}", export_path.display());
        }

        Ok(())
    }

    /// Handle dashboard command
    async fn handle_dashboard(&mut self, refresh: u64, hours: i64) -> Result<()> {
        println!("🔄 Analytics Dashboard (refresh: {}s, showing last {}h)", refresh, hours);
        println!("Press Ctrl+C to exit\n");

        loop {
            self.load_sample_data().await;
            self.print_dashboard_info(hours).await?;

            tokio::time::sleep(tokio::time::Duration::from_secs(refresh)).await;

            // Clear screen (works on most terminals)
            print!("\\x1B[2J\\x1B[H");
            io::stdout().flush().unwrap();
        }
    }

    /// Handle report generation
    async fn handle_report(
        &mut self,
        report_type: ReportType,
        hours: i64,
        output: Option<PathBuf>,
        detailed: bool,
    ) -> Result<()> {
        self.load_sample_data().await;

        let report = match report_type {
            ReportType::Summary => self.generate_summary_report(hours, detailed).await?,
            ReportType::Errors => self.generate_error_report(hours).await?,
            ReportType::Performance => self.generate_performance_report(hours).await?,
            ReportType::Navigation => self.generate_navigation_report(hours).await?,
            ReportType::Browser => self.generate_browser_report(hours).await?,
            ReportType::Server => self.generate_server_report(hours).await?,
        };

        if let Some(output_path) = output {
            std::fs::write(&output_path, &report)
                .with_context(|| format!("Failed to write report to {}", output_path.display()))?;
            println!("Report saved to: {}", output_path.display());
        } else {
            println!("{}", report);
        }

        Ok(())
    }

    /// Handle real-time monitoring
    async fn handle_monitor(
        &mut self,
        source: Option<Vec<AnalyticsSource>>,
        level: Option<Vec<AnalyticsLevel>>,
        errors_only: bool,
    ) -> Result<()> {
        println!("🔍 Real-time Analytics Monitor");
        println!("Press Ctrl+C to exit\\n");

        // In a real implementation, this would connect to the live analytics stream
        // For now, simulate with periodic updates
        loop {
            let events = self.simulate_live_events(source.clone(), level.clone(), errors_only).await;

            for event in events {
                self.print_live_event(&event);
            }

            tokio::time::sleep(tokio::time::Duration::from_secs(5)).await;
        }
    }

    /// Handle statistics
    async fn handle_stats(&mut self, hours: i64, by_source: bool, hourly: bool) -> Result<()> {
        self.load_sample_data().await;

        let stats = self.search_engine.get_stats();

        println!("📊 Analytics Statistics (last {}h)", hours);
        println!("Total Events: {}", stats.total_events);

        if let (Some(oldest), Some(newest)) = (stats.oldest_event, stats.newest_event) {
            println!("Time Range: {} to {}", oldest.format("%Y-%m-%d %H:%M"), newest.format("%Y-%m-%d %H:%M"));
        }

        if by_source {
            println!("\\nBy Source:");
            for (source, count) in stats.sources.iter() {
                println!("  {}: {}", source.as_str(), count);
            }
        }

        if hourly {
            println!("\\nHourly Distribution:");
            // This would show hourly breakdown in a real implementation
            println!("  (Hourly data visualization would be shown here)");
        }

        Ok(())
    }

    /// Handle data export
    async fn handle_export(
        &mut self,
        format: ExportFormat,
        output: PathBuf,
        hours: i64,
        source: Option<Vec<AnalyticsSource>>,
    ) -> Result<()> {
        self.load_sample_data().await;

        let query = SearchQuery {
            text: None,
            regex: None,
            sources: source.map(|s| s.into_iter().map(|src| src.into()).collect()),
            event_types: None,
            levels: None,
            time_range: Some(TimeRange::last_hours(hours)),
            paths: None,
            session_ids: None,
            has_errors: None,
            min_duration_ms: None,
            max_duration_ms: None,
            limit: None,
            sort: None,
        };

        let results = self.search_engine.search(query).await?;

        let data = match format {
            ExportFormat::Json => serde_json::to_string_pretty(&results.events)?,
            ExportFormat::Jsonl => {
                results.events.iter()
                    .map(|event| serde_json::to_string(event))
                    .collect::<Result<Vec<_>, _>>()?
                    .join("\\n")
            }
            ExportFormat::Csv | ExportFormat::Tsv => {
                let separator = if matches!(format, ExportFormat::Csv) { "," } else { "\\t" };
                self.format_as_delimited(&results.events, separator)?
            }
        };

        std::fs::write(&output, data)
            .with_context(|| format!("Failed to write export to {}", output.display()))?;

        println!("Exported {} events to {}", results.events.len(), output.display());
        Ok(())
    }

    /// Handle health check
    async fn handle_health_check(&mut self, detailed: bool) -> Result<()> {
        println!("🏥 Analytics System Health Check");

        // Check search engine
        let stats = self.search_engine.get_stats();
        println!("✅ Search Engine: {} events indexed", stats.total_events);

        // Check collectors (simulated)
        println!("✅ Navigation Collector: Active");
        println!("✅ Server Collector: Active");
        println!("✅ Browser Collector: Active");

        if detailed {
            println!("\\n📋 Detailed Information:");
            println!("  Regex Cache Size: {}", stats.regex_cache_size);
            println!("  Memory Usage: ~{}MB", stats.total_events * 1024 / 1_000_000); // Rough estimate

            for (source, count) in stats.sources.iter() {
                println!("  {}: {} events", source.as_str(), count);
            }
        }

        Ok(())
    }

    /// Load sample data for demonstration
    async fn load_sample_data(&mut self) {
        let sample_events = vec![
            AnalyticsEvent {
                id: "nav_001".to_string(),
                timestamp: Utc::now() - Duration::minutes(30),
                source: LogSource::Navigation,
                event_type: "route_cache_hit".to_string(),
                session_id: Some("session_123".to_string()),
                path: Some("/recipes".to_string()),
                level: EventLevel::Info,
                message: "Route cache hit for /recipes".to_string(),
                metadata: std::collections::HashMap::new(),
                duration_ms: Some(12),
                errors: vec![],
            },
            AnalyticsEvent {
                id: "server_001".to_string(),
                timestamp: Utc::now() - Duration::minutes(15),
                source: LogSource::Server,
                event_type: "panic".to_string(),
                session_id: None,
                path: Some("/api/content".to_string()),
                level: EventLevel::Error,
                message: "Panic: index out of bounds".to_string(),
                metadata: std::collections::HashMap::new(),
                duration_ms: None,
                errors: vec!["index out of bounds: the len is 3 but the index is 5".to_string()],
            },
            AnalyticsEvent {
                id: "browser_001".to_string(),
                timestamp: Utc::now() - Duration::minutes(5),
                source: LogSource::Browser,
                event_type: "javascript_error".to_string(),
                session_id: Some("session_456".to_string()),
                path: Some("/blog".to_string()),
                level: EventLevel::Error,
                message: "ReferenceError: variable is not defined".to_string(),
                metadata: std::collections::HashMap::new(),
                duration_ms: None,
                errors: vec!["variable is not defined".to_string()],
            },
        ];

        self.search_engine.index_events(sample_events);
    }

    /// Print results in table format
    fn print_table_results(&self, results: &super::search::SearchResults) {
        use comfy_table::{Table, presets::UTF8_FULL};

        let mut table = Table::new();
        table.load_preset(UTF8_FULL);
        table.set_header(vec!["Time", "Source", "Level", "Type", "Message"]);

        for event in &results.events {
            let message = if event.message.len() > 80 {
                format!("{}...", &event.message[..77])
            } else {
                event.message.clone()
            };

            table.add_row(vec![
                event.timestamp.format("%H:%M:%S").to_string(),
                event.source.as_str().to_string(),
                format!("{:?}", event.level),
                event.event_type.clone(),
                message,
            ]);
        }

        println!("{}", table);
        println!("Found {} events (query took {}ms)", results.total_count, results.query_time_ms);
    }

    /// Print results in JSON format
    fn print_json_results(&self, results: &super::search::SearchResults) -> Result<()> {
        let json = serde_json::to_string_pretty(results)?;
        println!("{}", json);
        Ok(())
    }

    /// Print results in CSV format
    fn print_csv_results(&self, results: &super::search::SearchResults) -> Result<()> {
        let csv = self.format_as_delimited(&results.events, ",")?;
        println!("{}", csv);
        Ok(())
    }

    /// Print summary of results
    fn print_summary_results(&self, results: &super::search::SearchResults) {
        println!("📊 Search Results Summary");
        println!("Total Events: {}", results.total_count);
        println!("Query Time: {}ms", results.query_time_ms);

        println!("\\nBy Source:");
        for (source, count) in &results.aggregations.sources {
            println!("  {}: {}", source.as_str(), count);
        }

        println!("\\nBy Level:");
        for (level, count) in &results.aggregations.levels {
            println!("  {:?}: {}", level, count);
        }

        if results.aggregations.error_summary.total_errors > 0 {
            println!("\\n🚨 Error Summary:");
            println!("  Total Errors: {}", results.aggregations.error_summary.total_errors);
            println!("  Unique Messages: {}", results.aggregations.error_summary.unique_error_messages);
        }
    }

    /// Format events as delimited data
    fn format_as_delimited(&self, events: &[AnalyticsEvent], delimiter: &str) -> Result<String> {
        let mut result = format!(
            "timestamp{}source{}level{}event_type{}message{}path{}session_id{}duration_ms\\n",
            delimiter, delimiter, delimiter, delimiter, delimiter, delimiter, delimiter
        );

        for event in events {
            result.push_str(&format!(
                "{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}\\n",
                event.timestamp.to_rfc3339(),
                delimiter,
                event.source.as_str(),
                delimiter,
                format!("{:?}", event.level),
                delimiter,
                event.event_type,
                delimiter,
                event.message.replace(delimiter, " "), // Escape delimiter in message
                delimiter,
                event.path.as_deref().unwrap_or(""),
                delimiter,
                event.session_id.as_deref().unwrap_or(""),
                delimiter,
                event.duration_ms.map(|d| d.to_string()).as_deref().unwrap_or(""),
            ));
        }

        Ok(result)
    }

    /// Export results to file
    async fn export_results(&self, results: &super::search::SearchResults, path: &PathBuf) -> Result<()> {
        let json = serde_json::to_string_pretty(results)?;
        tokio::fs::write(path, json).await?;
        Ok(())
    }

    /// Print dashboard information
    async fn print_dashboard_info(&mut self, hours: i64) -> Result<()> {
        println!("📊 Analytics Dashboard - {}", Utc::now().format("%Y-%m-%d %H:%M:%S UTC"));
        println!("{}".repeat(80));

        let stats = self.search_engine.get_stats();
        println!("Total Events: {}", stats.total_events);

        // Show recent activity
        let recent_query = SearchQuery {
            text: None,
            regex: None,
            sources: None,
            event_types: None,
            levels: None,
            time_range: Some(TimeRange::last_hours(1)), // Last hour
            paths: None,
            session_ids: None,
            has_errors: None,
            min_duration_ms: None,
            max_duration_ms: None,
            limit: Some(10),
            sort: None,
        };

        let recent_results = self.search_engine.search(recent_query).await?;
        println!("Recent Activity (last hour): {} events", recent_results.total_count);

        // Show error summary
        let error_query = SearchQuery {
            text: None,
            regex: None,
            sources: None,
            event_types: None,
            levels: Some(vec![EventLevel::Error, EventLevel::Critical]),
            time_range: Some(TimeRange::last_hours(hours)),
            paths: None,
            session_ids: None,
            has_errors: Some(true),
            min_duration_ms: None,
            max_duration_ms: None,
            limit: Some(5),
            sort: None,
        };

        let error_results = self.search_engine.search(error_query).await?;
        println!("Recent Errors: {}", error_results.total_count);

        if !error_results.events.is_empty() {
            println!("\\n🚨 Latest Errors:");
            for event in error_results.events.iter().take(3) {
                println!("  {} - {}: {}",
                    event.timestamp.format("%H:%M:%S"),
                    event.source.as_str(),
                    event.message
                );
            }
        }

        println!("\\n");
        Ok(())
    }

    /// Simulate live events for monitoring
    async fn simulate_live_events(
        &self,
        _source: Option<Vec<AnalyticsSource>>,
        _level: Option<Vec<AnalyticsLevel>>,
        errors_only: bool,
    ) -> Vec<AnalyticsEvent> {
        // Simulate 1-3 events
        let num_events = 1 + rand::random::<usize>() % 3;
        let mut events = Vec::new();

        for i in 0..num_events {
            let level = if errors_only {
                if rand::random::<bool>() { EventLevel::Error } else { EventLevel::Critical }
            } else {
                match rand::random::<u8>() % 6 {
                    0 => EventLevel::Trace,
                    1 => EventLevel::Debug,
                    2 => EventLevel::Info,
                    3 => EventLevel::Warn,
                    4 => EventLevel::Error,
                    _ => EventLevel::Critical,
                }
            };

            events.push(AnalyticsEvent {
                id: format!("live_{}", i),
                timestamp: Utc::now(),
                source: LogSource::Server,
                event_type: "live_event".to_string(),
                session_id: None,
                path: Some("/live".to_string()),
                level,
                message: format!("Live event {} - {}", i, "simulated message"),
                metadata: std::collections::HashMap::new(),
                duration_ms: Some(rand::random::<u64>() % 100),
                errors: if matches!(level, EventLevel::Error | EventLevel::Critical) {
                    vec!["simulated error".to_string()]
                } else {
                    vec![]
                },
            });
        }

        events
    }

    /// Print live event
    fn print_live_event(&self, event: &AnalyticsEvent) {
        let level_emoji = match event.level {
            EventLevel::Trace => "🔍",
            EventLevel::Debug => "🐛",
            EventLevel::Info => "ℹ️",
            EventLevel::Warn => "⚠️",
            EventLevel::Error => "❌",
            EventLevel::Critical => "🚨",
        };

        println!("{} {} [{}] {}: {}",
            event.timestamp.format("%H:%M:%S"),
            level_emoji,
            event.source.as_str(),
            event.event_type,
            event.message
        );
    }

    /// Generate summary report
    async fn generate_summary_report(&mut self, hours: i64, detailed: bool) -> Result<String> {
        let query = SearchQuery {
            text: None,
            regex: None,
            sources: None,
            event_types: None,
            levels: None,
            time_range: Some(TimeRange::last_hours(hours)),
            paths: None,
            session_ids: None,
            has_errors: None,
            min_duration_ms: None,
            max_duration_ms: None,
            limit: None,
            sort: None,
        };

        let results = self.search_engine.search(query).await?;

        let mut report = format!("📊 Analytics Summary Report\\n");
        report.push_str(&format!("Period: Last {} hours\\n", hours));
        report.push_str(&format!("Generated: {}\\n\\n", Utc::now().format("%Y-%m-%d %H:%M:%S UTC")));

        report.push_str(&format!("Total Events: {}\\n", results.total_count));

        report.push_str("\\nBy Source:\\n");
        for (source, count) in &results.aggregations.sources {
            report.push_str(&format!("  {}: {}\\n", source.as_str(), count));
        }

        if detailed {
            report.push_str("\\nBy Event Type:\\n");
            for (event_type, count) in &results.aggregations.event_types {
                report.push_str(&format!("  {}: {}\\n", event_type, count));
            }
        }

        Ok(report)
    }

    /// Generate error-specific report
    async fn generate_error_report(&mut self, hours: i64) -> Result<String> {
        let query = SearchQuery {
            text: None,
            regex: None,
            sources: None,
            event_types: None,
            levels: Some(vec![EventLevel::Error, EventLevel::Critical]),
            time_range: Some(TimeRange::last_hours(hours)),
            paths: None,
            session_ids: None,
            has_errors: Some(true),
            min_duration_ms: None,
            max_duration_ms: None,
            limit: None,
            sort: None,
        };

        let results = self.search_engine.search(query).await?;

        Ok(format!("🚨 Error Analysis Report\\nTotal Errors: {}\\nError Rate: {:.2}%\\n",
            results.aggregations.error_summary.total_errors,
            if results.total_count > 0 {
                results.aggregations.error_summary.total_errors as f64 / results.total_count as f64 * 100.0
            } else { 0.0 }
        ))
    }

    /// Generate performance report
    async fn generate_performance_report(&mut self, hours: i64) -> Result<String> {
        let query = SearchQuery {
            text: None,
            regex: None,
            sources: None,
            event_types: None,
            levels: None,
            time_range: Some(TimeRange::last_hours(hours)),
            paths: None,
            session_ids: None,
            has_errors: None,
            min_duration_ms: Some(100), // Events taking more than 100ms
            max_duration_ms: None,
            limit: None,
            sort: None,
        };

        let results = self.search_engine.search(query).await?;
        Ok(format!("⚡ Performance Report\\nSlow Events (>100ms): {}\\n", results.total_count))
    }

    /// Generate navigation report
    async fn generate_navigation_report(&mut self, hours: i64) -> Result<String> {
        let query = SearchQuery {
            text: None,
            regex: None,
            sources: Some(vec![LogSource::Navigation, LogSource::RouteCache]),
            event_types: None,
            levels: None,
            time_range: Some(TimeRange::last_hours(hours)),
            paths: None,
            session_ids: None,
            has_errors: None,
            min_duration_ms: None,
            max_duration_ms: None,
            limit: None,
            sort: None,
        };

        let results = self.search_engine.search(query).await?;
        Ok(format!("🧭 Navigation Report\\nNavigation Events: {}\\n", results.total_count))
    }

    /// Generate browser report
    async fn generate_browser_report(&mut self, hours: i64) -> Result<String> {
        let query = SearchQuery {
            text: None,
            regex: None,
            sources: Some(vec![LogSource::Browser]),
            event_types: None,
            levels: None,
            time_range: Some(TimeRange::last_hours(hours)),
            paths: None,
            session_ids: None,
            has_errors: None,
            min_duration_ms: None,
            max_duration_ms: None,
            limit: None,
            sort: None,
        };

        let results = self.search_engine.search(query).await?;
        Ok(format!("🌐 Browser Report\\nBrowser Events: {}\\n", results.total_count))
    }

    /// Generate server report
    async fn generate_server_report(&mut self, hours: i64) -> Result<String> {
        let query = SearchQuery {
            text: None,
            regex: None,
            sources: Some(vec![LogSource::Server]),
            event_types: None,
            levels: None,
            time_range: Some(TimeRange::last_hours(hours)),
            paths: None,
            session_ids: None,
            has_errors: None,
            min_duration_ms: None,
            max_duration_ms: None,
            limit: None,
            sort: None,
        };

        let results = self.search_engine.search(query).await?;
        Ok(format!("🖥️ Server Report\\nServer Events: {}\\n", results.total_count))
    }
}
