using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.Json; using System.Threading.Tasks; namespace MarketAlly.AIPlugin.Learning { public class ReportsManager { private readonly string _reportsDirectory; public ReportsManager(string reportsDirectory) { _reportsDirectory = reportsDirectory; } public async Task GenerateSessionReportAsync(ComprehensiveLearningResult result, bool verbose) { var projectDir = Path.Combine(_reportsDirectory, result.ProjectName); Directory.CreateDirectory(projectDir); var sessionDate = result.StartTime.ToString("yyyy-MM-dd"); var timeStamp = result.StartTime.ToString("HHmmss"); var reportPath = Path.Combine(projectDir, $"{sessionDate}-{timeStamp}-session-report.md"); var report = GenerateSessionReportContent(result, verbose); await File.WriteAllTextAsync(reportPath, report); Console.WriteLine($"📄 Session report generated: {reportPath}"); } private string GenerateSessionReportContent(ComprehensiveLearningResult result, bool verbose) { var report = new System.Text.StringBuilder(); // Header report.AppendLine($"# AI Learning Session Report"); report.AppendLine($"**Project:** {result.ProjectName}"); report.AppendLine($"**Session ID:** {result.SessionId}"); report.AppendLine($"**Date:** {result.StartTime:yyyy-MM-dd HH:mm:ss}"); report.AppendLine($"**Duration:** {result.TotalDuration.TotalMinutes:F1} minutes"); report.AppendLine($"**Status:** {(result.Success ? "✅ Success" : "❌ Failed")}"); report.AppendLine(); // Summary Statistics report.AppendLine("## 📊 Summary Statistics"); report.AppendLine($"- **Files Processed:** {result.TotalFilesProcessed}"); report.AppendLine($"- **Successful Iterations:** {result.SuccessfulIterations}"); report.AppendLine($"- **Total Fixes Applied:** {result.TotalFixesApplied}"); report.AppendLine($"- **Success Rate:** {result.SuccessRate:P1}"); report.AppendLine($"- **Failed Attempts:** {result.FailedAttempts.Count}"); report.AppendLine(); // Compilation Results if (result.BaselineCompilation != null && result.FinalCompilation != null) { report.AppendLine("## 🔨 Compilation Results"); report.AppendLine($"- **Baseline:** {result.BaselineCompilation.Status} ({result.BaselineCompilation.ErrorCount} errors, {result.BaselineCompilation.WarningCount} warnings)"); report.AppendLine($"- **Final:** {result.FinalCompilation.Status} ({result.FinalCompilation.ErrorCount} errors, {result.FinalCompilation.WarningCount} warnings)"); var errorImprovement = result.BaselineCompilation.ErrorCount - result.FinalCompilation.ErrorCount; var warningImprovement = result.BaselineCompilation.WarningCount - result.FinalCompilation.WarningCount; if (errorImprovement != 0) report.AppendLine($"- **Error Change:** {(errorImprovement > 0 ? "✅" : "❌")} {errorImprovement:+#;-#;0}"); if (warningImprovement != 0) report.AppendLine($"- **Warning Change:** {(warningImprovement > 0 ? "✅" : "❌")} {warningImprovement:+#;-#;0}"); report.AppendLine(); } // Git Information if (result.GitInfo != null) { report.AppendLine("## 🌿 Git Information"); report.AppendLine($"- **Original Branch:** {result.GitInfo.OriginalBranch}"); report.AppendLine($"- **AI Branch:** {result.GitInfo.AIBranch}"); report.AppendLine($"- **Session Branch:** {result.GitInfo.SessionBranch}"); report.AppendLine($"- **Failed Attempts Branch:** {result.GitInfo.FailedAttemptsBranch}"); report.AppendLine($"- **Final Merge Status:** {(result.GitInfo.FinalMergeSuccess ? "✅ Success" : "❌ Failed")}"); if (!string.IsNullOrEmpty(result.GitInfo.FinalMergeMessage)) report.AppendLine($"- **Merge Message:** {result.GitInfo.FinalMergeMessage}"); report.AppendLine(); } // Successful Iterations if (result.Iterations.Any(i => i.Success)) { report.AppendLine("## ✅ Successful Improvements"); foreach (var iteration in result.Iterations.Where(i => i.Success)) { report.AppendLine($"- **{Path.GetFileName(iteration.TargetFile)}:** {iteration.Summary} ({iteration.FixesApplied} fixes)"); } report.AppendLine(); } // Failed Attempts Summary if (result.FailedAttempts.Any()) { report.AppendLine("## ❌ Files Requiring Human Review"); var groupedFailures = result.FailedAttempts.GroupBy(f => f.FilePath); foreach (var group in groupedFailures) { var fileName = Path.GetFileName(group.Key); var attempts = group.Count(); var lastError = group.OrderBy(f => f.Timestamp).Last().Error; report.AppendLine($"- **{fileName}:** {attempts} attempts failed - {lastError}"); } report.AppendLine(); } // Verbose Details if (verbose && result.Iterations.Any()) { report.AppendLine("## 🔍 Detailed Iteration Log"); foreach (var iteration in result.Iterations) { report.AppendLine($"### Iteration {iteration.IterationNumber} - {Path.GetFileName(iteration.TargetFile)}"); report.AppendLine($"- **Duration:** {iteration.Duration.TotalSeconds:F1}s"); report.AppendLine($"- **Issues Found:** {iteration.IssuesFound}"); report.AppendLine($"- **Status:** {(iteration.Success ? "✅ Success" : "❌ Failed")}"); report.AppendLine($"- **Summary:** {iteration.Summary}"); if (iteration.CompilationResult != null) { report.AppendLine($"- **Compilation:** {iteration.CompilationResult.Status} ({iteration.CompilationResult.ErrorCount} errors)"); } if (iteration.FailedAttempts.Any()) { report.AppendLine("- **Failed Attempts:**"); foreach (var failed in iteration.FailedAttempts) { report.AppendLine($" - Attempt {failed.AttemptNumber}: {failed.FixApproach} - {failed.Error}"); } } report.AppendLine(); } } // Recommendations report.AppendLine("## 💡 Recommendations"); if (result.FailedAttempts.Any()) { report.AppendLine("### Files Requiring Manual Review:"); var uniqueFiles = result.FailedAttempts.Select(f => f.FilePath).Distinct(); foreach (var file in uniqueFiles) { report.AppendLine($"- Review `{Path.GetFileName(file)}` - Multiple AI attempts failed"); } report.AppendLine(); } if (result.SuccessfulIterations > 0) { report.AppendLine("### Next Steps:"); report.AppendLine($"- Review changes in AI branch: `{result.GitInfo?.AIBranch}`"); report.AppendLine("- Test the improved code thoroughly"); report.AppendLine("- Consider merging successful changes to main branch"); report.AppendLine(); } // Footer report.AppendLine("---"); report.AppendLine($"*Report generated by AI Learning System at {DateTime.UtcNow:yyyy-MM-dd HH:mm:ss} UTC*"); return report.ToString(); } public async Task GenerateFailuresReportAsync(List failures, string projectName, string sessionDate) { var projectDir = Path.Combine(_reportsDirectory, projectName); Directory.CreateDirectory(projectDir); var reportPath = Path.Combine(projectDir, $"{sessionDate}-failures.json"); var failuresData = new { GeneratedAt = DateTime.UtcNow, ProjectName = projectName, SessionDate = sessionDate, TotalFailures = failures.Count, UniqueFiles = failures.Select(f => f.FilePath).Distinct().Count(), Failures = failures.Select(f => new { f.FilePath, FileName = Path.GetFileName(f.FilePath), f.AttemptNumber, f.FixApproach, f.Error, f.Timestamp, f.HumanReviewNotes }).ToList() }; var json = JsonSerializer.Serialize(failuresData, new JsonSerializerOptions { WriteIndented = true }); await File.WriteAllTextAsync(reportPath, json); Console.WriteLine($"📄 Failures report generated: {reportPath}"); } public async Task GenerateWarningsReportAsync(ComprehensiveLearningResult result, string projectName, string sessionDate) { var projectDir = Path.Combine(_reportsDirectory, projectName); Directory.CreateDirectory(projectDir); var reportPath = Path.Combine(projectDir, $"{sessionDate}-warnings-analysis.md"); var report = new System.Text.StringBuilder(); report.AppendLine("# Warnings Analysis Report"); report.AppendLine($"**Project:** {projectName}"); report.AppendLine($"**Date:** {sessionDate}"); report.AppendLine(); if (result.InitialWarningsAnalysis != null) { report.AppendLine("## Initial Warnings Analysis"); report.AppendLine("```json"); report.AppendLine(JsonSerializer.Serialize(result.InitialWarningsAnalysis, new JsonSerializerOptions { WriteIndented = true })); report.AppendLine("```"); report.AppendLine(); } if (result.FinalWarningsAnalysis != null) { report.AppendLine("## Final Warnings Analysis"); report.AppendLine("```json"); report.AppendLine(JsonSerializer.Serialize(result.FinalWarningsAnalysis, new JsonSerializerOptions { WriteIndented = true })); report.AppendLine("```"); report.AppendLine(); } await File.WriteAllTextAsync(reportPath, report.ToString()); Console.WriteLine($"📄 Warnings report generated: {reportPath}"); } public async Task UpdateCumulativeProgressAsync(ComprehensiveLearningResult result) { var projectDir = Path.Combine(_reportsDirectory, result.ProjectName); Directory.CreateDirectory(projectDir); var cumulativePath = Path.Combine(projectDir, "cumulative-progress.md"); var newEntry = $"## {result.StartTime:yyyy-MM-dd HH:mm}\n" + $"- **Status:** {(result.Success ? "✅ Success" : "❌ Failed")}\n" + $"- **Files Processed:** {result.TotalFilesProcessed}\n" + $"- **Success Rate:** {result.SuccessRate:P1}\n" + $"- **Fixes Applied:** {result.TotalFixesApplied}\n" + $"- **Duration:** {result.TotalDuration.TotalMinutes:F1} minutes\n\n"; if (File.Exists(cumulativePath)) { var existingContent = await File.ReadAllTextAsync(cumulativePath); var header = "# Cumulative Learning Progress\n\n"; if (!existingContent.StartsWith("# Cumulative Learning Progress")) { existingContent = header + existingContent; } // Insert new entry after header var headerEndIndex = existingContent.IndexOf('\n', existingContent.IndexOf('\n') + 1); existingContent = existingContent.Insert(headerEndIndex + 1, newEntry); await File.WriteAllTextAsync(cumulativePath, existingContent); } else { var content = "# Cumulative Learning Progress\n\n" + newEntry; await File.WriteAllTextAsync(cumulativePath, content); } Console.WriteLine($"📄 Updated cumulative progress: {cumulativePath}"); } public async Task GenerateErrorReportAsync(ComprehensiveLearningResult result, Exception ex) { var projectDir = Path.Combine(_reportsDirectory, result.ProjectName); Directory.CreateDirectory(projectDir); var sessionDate = result.StartTime.ToString("yyyy-MM-dd"); var timeStamp = result.StartTime.ToString("HHmmss"); var errorReportPath = Path.Combine(projectDir, $"{sessionDate}-{timeStamp}-error-report.md"); var report = new System.Text.StringBuilder(); report.AppendLine("# AI Learning Session Error Report"); report.AppendLine($"**Project:** {result.ProjectName}"); report.AppendLine($"**Session ID:** {result.SessionId}"); report.AppendLine($"**Date:** {result.StartTime:yyyy-MM-dd HH:mm:ss}"); report.AppendLine($"**Error:** {result.ErrorMessage}"); report.AppendLine(); report.AppendLine("## Exception Details"); report.AppendLine("```"); report.AppendLine(ex.ToString()); report.AppendLine("```"); report.AppendLine(); if (result.Iterations.Any()) { report.AppendLine("## Completed Iterations Before Failure"); foreach (var iteration in result.Iterations) { report.AppendLine($"- **Iteration {iteration.IterationNumber}:** {iteration.Summary} ({(iteration.Success ? "Success" : "Failed")})"); } report.AppendLine(); } await File.WriteAllTextAsync(errorReportPath, report.ToString()); Console.WriteLine($"📄 Error report generated: {errorReportPath}"); } } }