"""NVD REST API v2 client (optional — provide API key for higher rate limits)."""

from __future__ import annotations

from typing import Any

import httpx

NVD_BASE = "https://services.nvd.nist.gov/rest/json/cves/2.0"


def query_nvd_by_package(package_name: str, api_key: str | None = None) -> list[dict[str, Any]]:
    """Query NVD for CVEs mentioning a package name."""
    headers: dict[str, str] = {}
    if api_key:
        headers["apiKey"] = api_key

    params: dict[str, str] = {"keywordSearch": package_name, "resultsPerPage": "20"}
    try:
        with httpx.Client(timeout=30.0) as client:
            resp = client.get(NVD_BASE, params=params, headers=headers)
            if resp.status_code == 200:
                result: list[dict[str, Any]] = resp.json().get("vulnerabilities", [])
                return result
    except Exception:  # noqa: BLE001
        pass
    return []


def cvss_to_severity(cvss_score: float) -> str:
    if cvss_score >= 9.0:
        return "critical"
    if cvss_score >= 7.0:
        return "high"
    if cvss_score >= 4.0:
        return "medium"
    if cvss_score > 0:
        return "low"
    return "info"
