import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { CallToolRequestSchema, Tool } from '@modelcontextprotocol/sdk/types.js';
import { ConfigManager } from '../../config/config-manager.js';
import { CodeAnalyzer } from './analyzer.js';
import { StorageManager } from '../../storage/storage-manager.js';
import { promises as fs } from 'fs';
import path from 'path';
import { 
  AnalysisOptions, 
  ReviewOptions, 
  TrackingOptions,
  MetricsHistory,
  HistoryEntry,
  CodeReview,
  AnalysisResult,
  FileAnalysis,
  CodeMetrics,
  Trend,
  CodeIssue,
  Finding,
  Suggestion,
} from './types.js';
import crypto from 'crypto';

let configManager: ConfigManager;
let storageManager: StorageManager;
let codeAnalyzer: CodeAnalyzer;

export async function setupCodeAnalysisTools(server: Server, config?: ConfigManager): Promise<{ tools: Tool[]; resources: any[] }> {
  configManager = config || new ConfigManager();
  storageManager = new StorageManager();
  codeAnalyzer = new CodeAnalyzer();

  server.setRequestHandler(CallToolRequestSchema, async (request) => {
    const { name, arguments: args } = request.params;

    if (!args) {
      throw new Error('No arguments provided');
    }

    switch (name) {
      case 'analyze_code_quality': {
        const options = args as AnalysisOptions;
        const { 
          files, 
          directories, 
          includeHistory = false, 
          compareWithBaseline = false,
          maxIssues = 100,
          excludePatterns = [],
          customRules = []
        } = options;

        try {
          // Collect files to analyze
          let filesToAnalyze: string[] = [];
          
          if (files && files.length > 0) {
            filesToAnalyze = files;
          }
          
          if (directories && directories.length > 0) {
            for (const dir of directories) {
              const dirFiles = await codeAnalyzer.findCodeFiles(dir, excludePatterns);
              filesToAnalyze.push(...dirFiles);
            }
          }

          if (filesToAnalyze.length === 0) {
            throw new Error('No files specified for analysis');
          }

          // Analyze files
          const fileAnalyses: FileAnalysis[] = [];
          for (const file of filesToAnalyze) {
            try {
              const analysis = await codeAnalyzer.analyzeFile(file);
              
              // Apply custom rules if provided
              if (customRules.length > 0) {
                for (const rule of customRules) {
                  const fileContent = await fs.readFile(file, 'utf-8');
                  const regex = new RegExp(rule.pattern, 'gm');
                  let match;
                  let lineNumber = 1;
                  const lines = fileContent.split('\n');
                  
                  for (const line of lines) {
                    if (regex.test(line)) {
                      analysis.issues.push({
                        type: rule.severity === 'error' ? 'error' : rule.severity === 'warning' ? 'warning' : 'info',
                        severity: rule.severity === 'error' ? 'high' : rule.severity === 'warning' ? 'medium' : 'low',
                        rule: rule.name,
                        message: rule.message,
                        location: {
                          file,
                          line: lineNumber,
                          column: 1,
                        },
                        fixable: false,
                        category: rule.category,
                      });
                    }
                    lineNumber++;
                  }
                }
              }
              
              // Limit issues if needed
              if (analysis.issues.length > maxIssues) {
                analysis.issues = analysis.issues.slice(0, maxIssues);
              }
              
              fileAnalyses.push(analysis);
            } catch (error: any) {
              console.error(`Failed to analyze ${file}: ${error.message}`);
            }
          }

          // Generate summary and recommendations
          const summary = codeAnalyzer.generateSummary(fileAnalyses);
          const recommendations = codeAnalyzer.generateRecommendations(summary);

          // Create analysis result
          const result: AnalysisResult = {
            id: crypto.randomUUID(),
            timestamp: new Date().toISOString(),
            files: fileAnalyses,
            summary,
            recommendations,
          };

          // Get baseline comparison if requested
          let baselineComparison = null;
          if (compareWithBaseline && includeHistory) {
            baselineComparison = await getBaselineComparison(result);
          }

          // Save to history if requested
          if (includeHistory) {
            await saveAnalysisToHistory(result);
          }

          // Format output
          const output = formatAnalysisOutput(result, baselineComparison);

          return {
            content: [
              {
                type: 'text',
                text: output,
              },
            ],
            structured: {
              analysisResult: result,
              baselineComparison,
              timestamp: new Date().toISOString(),
            },
          };
        } catch (error: any) {
          return {
            content: [
              {
                type: 'text',
                text: `❌ Code analysis failed\n\n**Error**: ${error.message}`,
              },
            ],
            structured: {
              error: error.message,
              timestamp: new Date().toISOString(),
            },
          };
        }
      }

      case 'review_code': {
        const options = args as ReviewOptions;
        const { file, compareWith, includeHistory = false } = options;

        try {
          // Load code to review
          let codeToReview: string;
          
          if (file) {
            codeToReview = await fs.readFile(file, 'utf-8');
          } else {
            throw new Error('No file specified for review');
          }

          // Analyze the code
          const analysis = await codeAnalyzer.analyzeFile(file);

          // Generate findings and suggestions
          const findings: Finding[] = analysis.issues.map(issue => ({
            type: issue.type === 'error' ? 'bug' : issue.type === 'warning' ? 'improvement' : 'style',
            severity: issue.severity,
            title: issue.rule,
            description: issue.message,
            location: issue.location,
            suggestedFix: issue.suggestion,
          }));

          const suggestions: Suggestion[] = [
            ...codeAnalyzer.generateSuggestions(analysis),
            ...codeAnalyzer.generateRefactoringIdeas(analysis),
          ];

          // Create review
          const review: CodeReview = {
            id: crypto.randomUUID(),
            timestamp: new Date().toISOString(),
            file,
            findings,
            suggestions,
            score: calculateReviewScore(analysis),
            summary: generateReviewSummary(findings, suggestions),
          };

          // Add comparison if requested
          if (compareWith) {
            const compareContent = await fs.readFile(compareWith, 'utf-8');
            const compareAnalysis = await codeAnalyzer.analyzeFile(compareWith);
            review.comparison = generateComparison(analysis, compareAnalysis);
          }

          // Save to history if requested
          if (includeHistory) {
            await saveReviewToHistory(review);
          }

          // Format output
          const output = formatReviewOutput(review);

          return {
            content: [
              {
                type: 'text',
                text: output,
              },
            ],
            structured: {
              review,
              timestamp: new Date().toISOString(),
            },
          };
        } catch (error: any) {
          return {
            content: [
              {
                type: 'text',
                text: `❌ Code review failed\n\n**Error**: ${error.message}`,
              },
            ],
            structured: {
              error: error.message,
              timestamp: new Date().toISOString(),
            },
          };
        }
      }

      case 'track_code_metrics': {
        const options = args as TrackingOptions;
        const { projectId, branch, commit, tags = [] } = options;

        try {
          // Determine project ID
          const projectRoot = storageManager.getProjectRoot();
          const effectiveProjectId = projectId || path.basename(projectRoot);

          // Analyze entire project
          const projectFiles = await codeAnalyzer.findCodeFiles('.', [
            'node_modules/**',
            'dist/**',
            'build/**',
            '.git/**',
            '*.test.*',
            '*.spec.*',
          ]);

          const fileAnalyses: FileAnalysis[] = [];
          for (const file of projectFiles) {
            try {
              const analysis = await codeAnalyzer.analyzeFile(file);
              fileAnalyses.push(analysis);
            } catch (error) {
              // Skip files that can't be analyzed
            }
          }

          // Calculate project metrics
          const projectMetrics = calculateProjectMetrics(fileAnalyses);

          // Create history entry
          const historyEntry: HistoryEntry = {
            timestamp: new Date().toISOString(),
            branch: branch || 'unknown',
            commit: commit || 'unknown',
            metrics: projectMetrics,
            tags,
          };

          // Load or create history
          let history: MetricsHistory;
          
          try {
            history = await storageManager.loadData('code-analysis', 'metrics-history.json') || {
              projectId: effectiveProjectId,
              entries: [],
              trends: [],
            };
          } catch {
            history = {
              projectId: effectiveProjectId,
              entries: [],
              trends: [],
            };
          }

          // Add new entry
          history.entries.push(historyEntry);

          // Keep only last 100 entries
          if (history.entries.length > 100) {
            history.entries = history.entries.slice(-100);
          }

          // Calculate trends
          history.trends = calculateMetricsTrends(history.entries);

          // Update baseline if this is tagged as baseline
          if (tags.includes('baseline')) {
            history.baseline = historyEntry;
          }

          // Save updated history
          await storageManager.saveData('code-analysis', 'metrics-history.json', history);

          // Generate formatted output
          const output = formatTrackingOutput(historyEntry, history.trends, history.baseline);

          return {
            content: [
              {
                type: 'text',
                text: output,
              },
            ],
            structured: {
              historyEntry,
              trends: history.trends,
              baseline: history.baseline,
              timestamp: new Date().toISOString(),
            },
          };
        } catch (error: any) {
          return {
            content: [
              {
                type: 'text',
                text: `❌ Metrics tracking failed\n\n**Error**: ${error.message}`,
              },
            ],
            structured: {
              error: error.message,
              timestamp: new Date().toISOString(),
            },
          };
        }
      }

      default:
        return null as any;
    }
  });

  return {
    tools: [
      {
        name: 'analyze_code_quality',
        description: 'Perform comprehensive code quality analysis with complexity metrics and issue detection',
        inputSchema: {
          type: 'object',
          properties: {
            files: {
              type: 'array',
              items: { type: 'string' },
              description: 'Specific files to analyze',
            },
            directories: {
              type: 'array',
              items: { type: 'string' },
              description: 'Directories to recursively analyze',
            },
            includeHistory: {
              type: 'boolean',
              description: 'Save results to history for trend analysis',
              default: false,
            },
            compareWithBaseline: {
              type: 'boolean',
              description: 'Compare results with baseline metrics',
              default: false,
            },
            maxIssues: {
              type: 'number',
              description: 'Maximum number of issues to report',
              default: 100,
            },
            excludePatterns: {
              type: 'array',
              items: { type: 'string' },
              description: 'Glob patterns to exclude from analysis',
            },
            customRules: {
              type: 'array',
              items: {
                type: 'object',
                properties: {
                  name: { type: 'string' },
                  pattern: { type: 'string' },
                  severity: { type: 'string', enum: ['error', 'warning', 'info'] },
                  category: { type: 'string' },
                  message: { type: 'string' },
                },
                required: ['name', 'pattern', 'severity', 'category', 'message'],
              },
              description: 'Custom rules to apply during analysis',
            },
          },
          required: [],
        },
      },
      {
        name: 'review_code',
        description: 'AI-powered code review with detailed findings and improvement suggestions',
        inputSchema: {
          type: 'object',
          properties: {
            file: {
              type: 'string',
              description: 'File to review',
            },
            compareWith: {
              type: 'string',
              description: 'Compare with another file (e.g., previous version)',
            },
            includeHistory: {
              type: 'boolean',
              description: 'Save review to history',
              default: false,
            },
            focusAreas: {
              type: 'array',
              items: {
                type: 'string',
                enum: ['security', 'performance', 'maintainability', 'style', 'testing'],
              },
              description: 'Specific areas to focus on',
            },
          },
          required: ['file'],
        },
      },
      {
        name: 'track_code_metrics',
        description: 'Track code quality metrics over time with trend analysis',
        inputSchema: {
          type: 'object',
          properties: {
            projectId: {
              type: 'string',
              description: 'Project identifier (defaults to directory name)',
            },
            branch: {
              type: 'string',
              description: 'Git branch name',
            },
            commit: {
              type: 'string',
              description: 'Git commit hash',
            },
            tags: {
              type: 'array',
              items: { type: 'string' },
              description: 'Tags for this metrics snapshot (e.g., "release", "baseline")',
            },
          },
          required: [],
        },
      },
    ],
    resources: [],
  };
}

// Helper functions

async function saveAnalysisToHistory(result: AnalysisResult): Promise<void> {
  let history: AnalysisResult[] = [];
  
  try {
    history = await storageManager.loadData('code-analysis', 'analysis-history.json') || [];
  } catch {
    // File doesn't exist yet
  }

  history.push(result);

  // Keep only last 50 analyses
  if (history.length > 50) {
    history = history.slice(-50);
  }

  await storageManager.saveData('code-analysis', 'analysis-history.json', history);
}

async function getBaselineComparison(current: AnalysisResult): Promise<any> {
  try {
    const history = await storageManager.loadData('code-analysis', 'metrics-history.json') as MetricsHistory;
    
    if (history && history.baseline) {
      const baseline = history.baseline;
      const currentMetrics = calculateProjectMetrics(current.files);
      
      return {
        complexityChange: currentMetrics.complexity.average - baseline.metrics.complexity.average,
        maintainabilityChange: currentMetrics.maintainability.average - baseline.metrics.maintainability.average,
        issuesChange: currentMetrics.quality.issues.total - baseline.metrics.quality.issues.total,
        duplicationChange: currentMetrics.duplication.percentage - baseline.metrics.duplication.percentage,
      };
    }
  } catch {
    // No baseline available
  }

  return null;
}

function calculateProjectMetrics(files: FileAnalysis[]): CodeMetrics {
  const totalFiles = files.length;
  
  if (totalFiles === 0) {
    return {
      complexity: { 
        cyclomatic: 0,
        cognitive: 0,
        halstead: { difficulty: 0, volume: 0, effort: 0 },
        functions: [],
        average: 0, 
        max: 0, 
        total: 0 
      },
      maintainability: { 
        index: 0,
        rating: 'F' as const,
        factors: { complexity: 0, lineCount: 0, commentRatio: 0 },
        average: 0, 
        min: 100, 
        distribution: {} 
      },
      duplication: { 
        percentage: 0, 
        duplicateBlocks: [],
        totalLines: 0,
        duplicatedLines: 0,
        blocks: 0 
      },
      quality: {
        issues: { total: 0, high: 0, medium: 0, low: 0 },
        codeSmells: 0,
        technicalDebt: 0,
        score: 0,
        grade: 'F' as const,
      },
    };
  }

  // Aggregate metrics
  let totalComplexity = 0;
  let maxComplexity = 0;
  let totalMaintainability = 0;
  let minMaintainability = 100;
  let totalIssues = 0;
  let highIssues = 0;
  let mediumIssues = 0;
  let lowIssues = 0;
  let totalDuplication = 0;

  for (const file of files) {
    totalComplexity += file.metrics.complexity.average;
    maxComplexity = Math.max(maxComplexity, file.metrics.complexity.max);
    totalMaintainability += file.metrics.maintainability.average;
    minMaintainability = Math.min(minMaintainability, file.metrics.maintainability.average);
    totalDuplication += file.metrics.duplication.percentage;

    totalIssues += file.issues.length;
    highIssues += file.issues.filter(i => i.severity === 'high').length;
    mediumIssues += file.issues.filter(i => i.severity === 'medium').length;
    lowIssues += file.issues.filter(i => i.severity === 'low').length;
  }

  return {
    complexity: {
      cyclomatic: totalComplexity,
      cognitive: totalComplexity, // Simplified - same as cyclomatic
      halstead: { difficulty: 0, volume: 0, effort: 0 },
      functions: [],
      average: totalComplexity / totalFiles,
      max: maxComplexity,
      total: totalComplexity,
    },
    maintainability: {
      index: totalMaintainability / totalFiles,
      rating: 'B' as const, // Simplified
      factors: { complexity: totalComplexity / totalFiles, lineCount: 0, commentRatio: 0 },
      average: totalMaintainability / totalFiles,
      min: minMaintainability,
      distribution: {},
    },
    duplication: {
      percentage: totalDuplication / totalFiles,
      duplicateBlocks: [],
      totalLines: 0,
      duplicatedLines: 0,
      blocks: 0,
    },
    quality: {
      issues: {
        total: totalIssues,
        high: highIssues,
        medium: mediumIssues,
        low: lowIssues,
      },
      codeSmells: 0,
      technicalDebt: Math.round(totalIssues * 0.5), // Simplified estimation
      score: 80, // Simplified
      grade: 'B' as const,
    },
  };
}

function calculateMetricsTrends(entries: HistoryEntry[]): Trend[] {
  if (entries.length < 2) {
    return [];
  }

  const trends: Trend[] = [];
  const recentEntries = entries.slice(-10); // Last 10 entries

  // Calculate complexity trend
  const complexityValues = recentEntries.map(e => e.metrics.complexity.average);
  trends.push({
    metric: 'complexity',
    direction: getTrendDirection(complexityValues),
    change: complexityValues[complexityValues.length - 1] - complexityValues[0],
    percentage: ((complexityValues[complexityValues.length - 1] - complexityValues[0]) / complexityValues[0]) * 100,
  });

  // Calculate maintainability trend
  const maintainabilityValues = recentEntries.map(e => e.metrics.maintainability.average);
  trends.push({
    metric: 'maintainability',
    direction: getTrendDirection(maintainabilityValues),
    change: maintainabilityValues[maintainabilityValues.length - 1] - maintainabilityValues[0],
    percentage: ((maintainabilityValues[maintainabilityValues.length - 1] - maintainabilityValues[0]) / maintainabilityValues[0]) * 100,
  });

  return trends;
}

function getTrendDirection(values: number[]): 'improving' | 'degrading' | 'stable' {
  if (values.length < 2) return 'stable';
  
  const first = values[0];
  const last = values[values.length - 1];
  const threshold = 0.05; // 5% threshold

  if (Math.abs(last - first) / first < threshold) {
    return 'stable';
  }

  return last > first ? 'degrading' : 'improving';
}

async function saveReviewToHistory(review: CodeReview): Promise<void> {
  let reviews: CodeReview[] = [];
  
  try {
    reviews = await storageManager.loadData('code-analysis', 'code-reviews.json') || [];
  } catch {
    // File doesn't exist yet
  }

  reviews.push(review);

  // Keep only last 100 reviews
  if (reviews.length > 100) {
    reviews = reviews.slice(-100);
  }

  await storageManager.saveData('code-analysis', 'code-reviews.json', reviews);
}

function calculateReviewScore(analysis: FileAnalysis): number {
  const { metrics, issues } = analysis;
  
  // Start with perfect score
  let score = 100;
  
  // Deduct for complexity
  if (metrics.complexity.average > 10) {
    score -= Math.min(20, (metrics.complexity.average - 10) * 2);
  }
  
  // Deduct for low maintainability
  if (metrics.maintainability.average < 70) {
    score -= Math.min(20, (70 - metrics.maintainability.average) * 0.5);
  }
  
  // Deduct for issues
  score -= issues.filter(i => i.severity === 'high').length * 5;
  score -= issues.filter(i => i.severity === 'medium').length * 2;
  score -= issues.filter(i => i.severity === 'low').length * 0.5;
  
  return Math.max(0, Math.round(score));
}

function generateReviewSummary(findings: Finding[], suggestions: Suggestion[]): string {
  const highPriorityFindings = findings.filter(f => f.severity === 'high').length;
  const mediumPriorityFindings = findings.filter(f => f.severity === 'medium').length;
  
  let summary = '';
  
  if (highPriorityFindings > 0) {
    summary += `Found ${highPriorityFindings} high-priority issues that should be addressed immediately. `;
  }
  
  if (mediumPriorityFindings > 0) {
    summary += `Found ${mediumPriorityFindings} medium-priority issues that should be addressed soon. `;
  }
  
  if (suggestions.length > 0) {
    summary += `Generated ${suggestions.length} improvement suggestions. `;
  }
  
  if (findings.length === 0 && suggestions.length === 0) {
    summary = 'Code looks good! No significant issues found.';
  }
  
  return summary;
}

function generateComparison(current: FileAnalysis, previous: FileAnalysis): any {
  return {
    complexityChange: current.metrics.complexity.average - previous.metrics.complexity.average,
    maintainabilityChange: current.metrics.maintainability.average - previous.metrics.maintainability.average,
    issuesAdded: current.issues.length - previous.issues.length,
    linesChanged: Math.abs(current.metrics.complexity.total - previous.metrics.complexity.total),
  };
}

function formatAnalysisOutput(result: AnalysisResult, baselineComparison: any): string {
  let output = `📊 Code Quality Analysis Report\n\n`;
  
  output += `**Files Analyzed**: ${result.files.length}\n`;
  output += `**Analysis Time**: ${new Date(result.timestamp).toLocaleString()}\n\n`;
  
  output += `**Summary**\n${result.summary}\n\n`;
  
  output += `**Key Metrics**\n`;
  output += `• Average Complexity: ${(result.files.reduce((sum, f) => sum + f.metrics.complexity.average, 0) / result.files.length).toFixed(1)}\n`;
  output += `• Average Maintainability: ${(result.files.reduce((sum, f) => sum + f.metrics.maintainability.average, 0) / result.files.length).toFixed(1)}\n`;
  output += `• Total Issues: ${result.files.reduce((sum, f) => sum + f.issues.length, 0)}\n\n`;
  
  if (baselineComparison) {
    output += `**Changes from Baseline**\n`;
    output += `• Complexity: ${baselineComparison.complexityChange > 0 ? '+' : ''}${baselineComparison.complexityChange.toFixed(1)}\n`;
    output += `• Maintainability: ${baselineComparison.maintainabilityChange > 0 ? '+' : ''}${baselineComparison.maintainabilityChange.toFixed(1)}\n`;
    output += `• Issues: ${baselineComparison.issuesChange > 0 ? '+' : ''}${baselineComparison.issuesChange}\n\n`;
  }
  
  output += `**Recommendations**\n`;
  result.recommendations.forEach((rec, i) => {
    output += `${i + 1}. ${rec}\n`;
  });
  
  return output;
}

function formatReviewOutput(review: CodeReview): string {
  let output = `🔍 Code Review Report\n\n`;
  
  output += `**File**: ${review.file}\n`;
  output += `**Score**: ${review.score}/100\n`;
  output += `**Summary**: ${review.summary}\n\n`;
  
  if (review.findings.length > 0) {
    output += `**Findings** (${review.findings.length})\n`;
    review.findings.forEach((finding, i) => {
      const icon = finding.severity === 'high' ? '🔴' : finding.severity === 'medium' ? '🟡' : '🟢';
      output += `${icon} ${finding.title}\n`;
      output += `   ${finding.description}\n`;
      if (finding.location) {
        output += `   Location: ${finding.location.file}:${finding.location.line}\n`;
      }
      if (finding.suggestedFix) {
        output += `   Fix: ${finding.suggestedFix}\n`;
      }
      output += '\n';
    });
  }
  
  if (review.suggestions.length > 0) {
    output += `**Improvement Suggestions**\n`;
    review.suggestions.forEach((suggestion, i) => {
      output += `${i + 1}. ${suggestion.title}\n`;
      output += `   ${suggestion.description}\n`;
      if (suggestion.priority) {
        output += `   Priority: ${suggestion.priority}\n`;
      }
      output += '\n';
    });
  }
  
  if (review.comparison) {
    output += `**Comparison with Previous Version**\n`;
    output += `• Complexity Change: ${review.comparison.complexityChange > 0 ? '+' : ''}${review.comparison.complexityChange}\n`;
    output += `• Maintainability Change: ${review.comparison.maintainabilityChange > 0 ? '+' : ''}${review.comparison.maintainabilityChange}\n`;
    output += `• Issues Change: ${review.comparison.issuesAdded > 0 ? '+' : ''}${review.comparison.issuesAdded}\n`;
  }
  
  return output;
}

function formatTrackingOutput(entry: HistoryEntry, trends: Trend[], baseline?: HistoryEntry): string {
  let output = `📈 Code Metrics Tracked\n\n`;
  
  output += `**Branch**: ${entry.branch}\n`;
  output += `**Commit**: ${entry.commit}\n`;
  output += `**Time**: ${new Date(entry.timestamp).toLocaleString()}\n\n`;
  
  output += `**Current Metrics**\n`;
  output += `• Complexity: ${entry.metrics.complexity.average.toFixed(1)} (avg), ${entry.metrics.complexity.max} (max)\n`;
  output += `• Maintainability: ${entry.metrics.maintainability.average.toFixed(1)} (avg), ${entry.metrics.maintainability.min.toFixed(1)} (min)\n`;
  output += `• Duplication: ${entry.metrics.duplication.percentage.toFixed(1)}%\n`;
  output += `• Issues: ${entry.metrics.quality.issues.total} total (${entry.metrics.quality.issues.high} high)\n\n`;
  
  if (trends.length > 0) {
    output += `**Trends**\n`;
    trends.forEach(trend => {
      const icon = trend.direction === 'improving' ? '📈' : trend.direction === 'degrading' ? '📉' : '➡️';
      output += `${icon} ${trend.metric}: ${trend.direction} (${trend.change > 0 ? '+' : ''}${trend.change.toFixed(1)}, ${trend.percentage.toFixed(1)}%)\n`;
    });
    output += '\n';
  }
  
  if (baseline) {
    output += `**Comparison with Baseline**\n`;
    output += `• Complexity: ${entry.metrics.complexity.average - baseline.metrics.complexity.average > 0 ? '+' : ''}${(entry.metrics.complexity.average - baseline.metrics.complexity.average).toFixed(1)}\n`;
    output += `• Maintainability: ${entry.metrics.maintainability.average - baseline.metrics.maintainability.average > 0 ? '+' : ''}${(entry.metrics.maintainability.average - baseline.metrics.maintainability.average).toFixed(1)}\n`;
    output += `• Issues: ${entry.metrics.quality.issues.total - baseline.metrics.quality.issues.total > 0 ? '+' : ''}${entry.metrics.quality.issues.total - baseline.metrics.quality.issues.total}\n`;
  }
  
  if (entry.tags && entry.tags.length > 0) {
    output += `\n**Tags**: ${entry.tags.join(', ')}`;
  }
  
  return output;
}