from pip_audit_extra.vulnerability.dataclass import Vulnerability
from pip_audit_extra.severity import SEVERITY_PRIORITY

from typing import Iterable, List, Tuple


def sort_vulnerabilities(vulns: Iterable[Vulnerability]) -> List[Vulnerability]:
	"""
	Sorts vulnerabilities by priority and package name.

	Args:
		vulns: Vulnerabilities to sort.

	Returns:
		Sorted list of vulnerabilities.
	"""
	if SEVERITY_PRIORITY:
		lowest_priority = max(SEVERITY_PRIORITY.values()) + 1		# Maximum value - minimum priority
	else:
		lowest_priority = 0

	def sort_key(x: Vulnerability) -> Tuple[int, str]:
		if x.severity:
			return SEVERITY_PRIORITY.get(x.severity, lowest_priority), x.package_name

		return lowest_priority, x.package_name

	return sorted(vulns, key=sort_key)
