"""refget v2 API client."""

from __future__ import annotations

from typing import Any

from ai4gh.core.client import GA4GHClient
from ai4gh.specs.refget.models import RefgetMetadata


class RefgetClient(GA4GHClient):
    """Client for the GA4GH refget v2 API.

    refget provides access to reference sequences by their checksum
    identifiers, supporting subsequence retrieval and metadata lookup.
    """

    spec_name = "refget"
    spec_version = "2.0.0"
    base_path = "/sequence"

    async def get_sequence(
        self,
        checksum: str,
        *,
        start: int | None = None,
        end: int | None = None,
    ) -> str:
        """Retrieve a reference sequence by checksum.

        Args:
            checksum: The sequence checksum (MD5, TRUNC512, or GA4GH).
            start: Start coordinate (0-based, inclusive).
            end: End coordinate (0-based, exclusive).

        Returns:
            The sequence string.
        """
        params: dict[str, Any] = {}
        if start is not None:
            params["start"] = start
        if end is not None:
            params["end"] = end

        headers = {"Accept": "text/plain"}
        url = f"{self.url}/{checksum}"
        auth_headers = await self._get_auth_headers()
        headers.update(auth_headers)

        response = await self._transport.get(url, headers=headers, params=params or None)
        return response.text

    async def get_metadata(self, checksum: str) -> RefgetMetadata:
        """Get metadata for a sequence.

        Args:
            checksum: The sequence checksum.

        Returns:
            Sequence metadata including length and aliases.
        """
        data = await self._request("GET", f"/{checksum}/metadata")
        metadata = data.get("metadata", data)
        return RefgetMetadata.model_validate(metadata)
