from pip_audit_extra.vulnerability.dataclass import Vulnerability
from pip_audit_extra.vulnerability.sort import sort_vulnerabilities
from pip_audit_extra.severity import SEVERITY_COLOR

from typing import Iterable

from rich.console import Console
from rich.table import Table


def print_vulnerabilities(console: Console, vulns: Iterable[Vulnerability]) -> None:
	"""
	Prints table of vulnerabilities.

	Args:
		console: The `rich.console.Console` object to use for drawing the table.
		vulns: Vulnerabilities to print.
	"""
	table = Table()
	table.add_column("Id", no_wrap=True)
	table.add_column("Package name")
	table.add_column("Package version")
	table.add_column("Fix versions")
	table.add_column("Severity")

	for vuln in sort_vulnerabilities(vulns):
		if vuln.severity:
			severity = vuln.severity.value
			severity_color = SEVERITY_COLOR.get(vuln.severity, "")
		else:
			severity = ""
			severity_color = ""

		if severity_color:
			severity = f"[{severity_color}]{severity}[/{severity_color}]"

		table.add_row(
			vuln.id,
			vuln.package_name,
			vuln.package_version,
			", ".join(vuln.fix_versions),
			severity,
		)

	console.print(table)
