"""Lightweight Posit Package Manager API client for VIP tests."""

from __future__ import annotations

from typing import Any

from vip.clients.base import BaseClient


class PackageManagerClient(BaseClient):
    """Minimal Package Manager HTTP wrapper."""

    def __init__(self, base_url: str, token: str = "", *, timeout: float = 30.0) -> None:
        super().__init__(
            base_url,
            auth_header_value=f"Bearer {token}" if token else "",
            timeout=timeout,
        )

    # -- Health / status ----------------------------------------------------

    def health(self) -> int:
        """Return the HTTP status code for the status endpoint."""
        resp = self._client.get("/__api__/status")
        return resp.status_code

    # -- Repos --------------------------------------------------------------

    def list_repos(self) -> list[dict[str, Any]]:
        """List configured repositories."""
        resp = self._client.get("/__api__/repos")
        resp.raise_for_status()
        return resp.json()

    def status(self) -> dict[str, Any]:
        """Return the parsed JSON body from the status endpoint."""
        resp = self._client.get("/__api__/status")
        resp.raise_for_status()
        return resp.json()

    # -- CRAN ---------------------------------------------------------------

    def cran_package_available(self, repo_name: str, package: str) -> bool:
        """Check whether a CRAN package is available in a repo."""
        resp = self._client.get(f"/{repo_name}/latest/src/contrib/PACKAGES")
        if resp.status_code != 200:
            return False
        return package in resp.text

    # -- Bioconductor -------------------------------------------------------

    def bioconductor_package_available(self, repo_name: str, package: str) -> bool:
        """Check whether a Bioconductor package is available in a repo.

        Bioconductor repos expose the same ``PACKAGES`` index as CRAN repos,
        served under the ``/bioc/`` sub-path for software packages.
        """
        resp = self._client.get(f"/{repo_name}/latest/bioc/src/contrib/PACKAGES")
        if resp.status_code != 200:
            # Fall back to the root PACKAGES path (pre-2022 layout or non-bioc mirror).
            resp = self._client.get(f"/{repo_name}/latest/src/contrib/PACKAGES")
        if resp.status_code != 200:
            return False
        return package in resp.text

    # -- PyPI ---------------------------------------------------------------

    def pypi_package_available(self, repo_name: str, package: str) -> bool:
        """Check whether a PyPI package is available in a repo."""
        resp = self._client.get(f"/{repo_name}/latest/simple/{package}/")
        return resp.status_code == 200
