using System;
using System.Collections.Generic;
using System.Linq;

namespace EonaCat.LogStack.PerformanceInsights
{
    /// <summary>
    /// Analyzes performance metrics and provides optimization insights.
    /// </summary>
    public sealed class PerformanceAnalyzer
    {
        private readonly PerformanceInsightsCollector _collector;

        public PerformanceAnalyzer(PerformanceInsightsCollector collector = null)
        {
            _collector = collector ?? new PerformanceInsightsCollector();
        }

        /// <summary>
        /// Analyzes current performance state and returns insights
        /// </summary>
        public PerformanceAnalysis Analyze()
        {
            var snapshot = _collector.GetSnapshot();
            var recommendations = _collector.GetRecommendations();

            var analysis = new PerformanceAnalysis
            {
                AnalyzedAt = DateTime.UtcNow,
                Uptime = snapshot.Uptime,
                TotalOperations = snapshot.TotalOperations,
                AverageErrorRate = snapshot.ErrorRatePercent,
                Recommendations = recommendations,
                Summary = GenerateSummary(snapshot, recommendations)
            };

            return analysis;
        }

        /// <summary>
        /// Generates a summary string of the analysis
        /// </summary>
        private string GenerateSummary(PerformanceInsightsSnapshot snapshot, List<PerformanceRecommendation> recommendations)
        {
            var lines = new List<string>
            {
                $"Performance Analysis - {snapshot.CapturedAt:O}",
                $"Uptime: {snapshot.Uptime.TotalSeconds:F2}s",
                $"Total Operations: {snapshot.TotalOperations}",
                $"Total Errors: {snapshot.TotalErrors}",
                $"Error Rate: {snapshot.ErrorRatePercent:F2}%",
                "",
                "Top Slowest Operations:"
            };

            foreach (var op in snapshot.SlowestOperations.Take(3))
            {
                lines.Add($"  - {op.Name}: {op.AverageDurationMs:F2}ms (min: {op.MinDurationMs:F2}ms, max: {op.MaxDurationMs:F2}ms)");
            }

            if (snapshot.MostErrorsOperations.Any())
            {
                lines.Add("");
                lines.Add("Operations with Most Errors:");
                foreach (var op in snapshot.MostErrorsOperations.Take(3))
                {
                    lines.Add($"  - {op.Name}: {op.ErrorCount} errors ({op.ErrorRatePercent:F2}% error rate)");
                }
            }

            if (recommendations.Any())
            {
                lines.Add("");
                lines.Add("Recommendations:");
                foreach (var rec in recommendations)
                {
                    lines.Add($"  [{rec.Severity}] {rec.Category}: {rec.Message}");
                    foreach (var op in rec.AffectedOperations.Take(3))
                    {
                        lines.Add($"    - {op}");
                    }
                }
            }

            return string.Join(Environment.NewLine, lines);
        }
    }

    /// <summary>
    /// Performance analysis result
    /// </summary>
    public sealed class PerformanceAnalysis
    {
        public DateTime AnalyzedAt { get; set; }
        public TimeSpan Uptime { get; set; }
        public long TotalOperations { get; set; }
        public double AverageErrorRate { get; set; }
        public List<PerformanceRecommendation> Recommendations { get; set; } = new();
        public string Summary { get; set; }
    }
}
