/**
 * Report Summary — Sorting and counting utilities for scan results.
 *
 * Pure functions extracted from the orchestrator. No cross-stage dependencies.
 */

import type {
  Vulnerability,
  SeverityCounts,
  CategoryCounts,
  VulnerabilityCategory,
} from '../shared/types'
import { severityRank, confidenceRank } from '../shared/parsed-file'

/**
 * Sort vulnerabilities by severity (critical first)
 */
export function sortBySeverity(vulnerabilities: Vulnerability[]): Vulnerability[] {
  return [...vulnerabilities].sort((a, b) => {
    const severityDiff = severityRank(b.severity) - severityRank(a.severity)
    if (severityDiff !== 0) return severityDiff

    // Secondary sort by confidence
    return confidenceRank(b.confidence) - confidenceRank(a.confidence)
  })
}

/**
 * Compute severity counts from vulnerabilities
 */
export function computeSeverityCounts(vulnerabilities: Vulnerability[]): SeverityCounts {
  const counts: SeverityCounts = { critical: 0, high: 0, medium: 0, low: 0, info: 0 }

  for (const vuln of vulnerabilities) {
    if (vuln.severity in counts) {
      counts[vuln.severity]++
    }
  }

  return counts
}

/**
 * Compute category counts from vulnerabilities
 */
export function computeCategoryCounts(vulnerabilities: Vulnerability[]): CategoryCounts {
  const counts: CategoryCounts = {}

  for (const vuln of vulnerabilities) {
    const category = vuln.category as VulnerabilityCategory
    counts[category] = (counts[category] || 0) + 1
  }

  return counts
}

/**
 * Helper to compute counts from vulnerabilities (for backfilling legacy scans)
 */
export function computeIssueMixFromVulnerabilities(vulnerabilities: Vulnerability[]): {
  severityCounts: SeverityCounts
  categoryCounts: CategoryCounts
  hasBlockingIssues: boolean
} {
  const severityCounts = computeSeverityCounts(vulnerabilities)
  const categoryCounts = computeCategoryCounts(vulnerabilities)
  const hasBlockingIssues = severityCounts.critical > 0 || severityCounts.high > 0

  return { severityCounts, categoryCounts, hasBlockingIssues }
}
