/**
 * Noisy Finding Aggregation — Groups repeated findings in the same file.
 *
 * When 3+ findings share the same file + category + base title, they are
 * collapsed into a single aggregated finding to reduce clutter.
 */

import type { Vulnerability } from '../shared/types'
import { severityRank } from '../shared/parsed-file'

/**
 * Aggregate noisy findings in the same file to reduce clutter
 * Groups repeated findings with same filePath + category + title
 * Especially useful for AI pattern spam
 */
export function aggregateNoisyFindings(vulnerabilities: Vulnerability[]): Vulnerability[] {
  // Group findings by file + category + title
  const groups = new Map<string, Vulnerability[]>()

  for (const vuln of vulnerabilities) {
    // Create grouping key: same file, category, and base title (without line-specific info)
    const baseTitle = vuln.title.replace(/\s*\(\d+ instances?\)/, '').trim()
    const key = `${vuln.filePath}|${vuln.category}|${baseTitle}`

    const existing = groups.get(key) || []
    existing.push(vuln)
    groups.set(key, existing)
  }

  const result: Vulnerability[] = []

  for (const [, group] of groups) {
    // If only 1-2 findings, keep them as-is
    if (group.length <= 2) {
      result.push(...group)
      continue
    }

    // For 3+ similar findings in same file, aggregate into one
    const first = group[0]
    const lineNumbers = group.map(v => v.lineNumber).sort((a, b) => a - b)
    const uniqueLines = [...new Set(lineNumbers)]

    // Format line numbers nicely (show first few, then "...")
    const lineDisplay = uniqueLines.length > 5
      ? `${uniqueLines.slice(0, 5).join(', ')}... (${uniqueLines.length} total)`
      : uniqueLines.join(', ')

    // Keep highest severity from the group
    const highestSeverity = group.reduce((max, v) =>
      severityRank(v.severity) > severityRank(max.severity) ? v : max
    , group[0]).severity

    // Create aggregated finding
    const aggregated: Vulnerability = {
      id: `${first.id}-aggregated`,
      filePath: first.filePath,
      lineNumber: uniqueLines[0], // First occurrence
      lineContent: `${group.length} instances across this file`,
      severity: highestSeverity,
      category: first.category,
      title: `${first.title.replace(/\s*\(\d+ instances?\)/, '')} (${group.length} instances)`,
      description: `${first.description}\n\nFound ${group.length} occurrences at lines: ${lineDisplay}`,
      suggestedFix: first.suggestedFix,
      confidence: first.confidence,
      layer: first.layer,
      requiresAIValidation: first.requiresAIValidation,
    }

    result.push(aggregated)
  }

  return result
}
