"""OSV.dev API client for batch vulnerability queries (no API key required)."""

from __future__ import annotations

from typing import Any

import httpx

OSV_BATCH_URL = "https://api.osv.dev/v1/querybatch"


def query_osv(packages: list[dict[str, str]]) -> list[list[dict[str, Any]]]:
    """
    Query OSV.dev for vulnerabilities in a batch.
    packages: list of {"name": str, "version": str, "ecosystem": str}
    Returns: list of vulnerability lists, one per input package.
    """
    if not packages:
        return []

    queries = [
        {
            "version": pkg["version"],
            "package": {"name": pkg["name"], "ecosystem": pkg["ecosystem"]},
        }
        for pkg in packages
        if pkg.get("version") and pkg.get("name")
    ]

    if not queries:
        return [[] for _ in packages]

    try:
        with httpx.Client(timeout=30.0) as client:
            resp = client.post(OSV_BATCH_URL, json={"queries": queries})
            resp.raise_for_status()
            results = resp.json().get("results", [])
            return [r.get("vulns", []) for r in results]
    except Exception:  # noqa: BLE001
        return [[] for _ in packages]
