"""Gitea release provider — fetches releases from a Gitea instance."""

import httpx

from wled_controller.core.update.release_provider import AssetInfo, ReleaseInfo, ReleaseProvider
from wled_controller.utils import get_logger

logger = get_logger(__name__)


class GiteaReleaseProvider(ReleaseProvider):
    """Fetch releases from a Gitea repository via its REST API."""

    def __init__(self, base_url: str, repo: str, token: str = "") -> None:
        self._base_url = base_url.rstrip("/")
        self._repo = repo
        self._token = token

    async def get_releases(self, limit: int = 10) -> list[ReleaseInfo]:
        url = f"{self._base_url}/api/v1/repos/{self._repo}/releases"
        headers: dict[str, str] = {}
        if self._token:
            headers["Authorization"] = f"token {self._token}"

        async with httpx.AsyncClient(timeout=15) as client:
            resp = await client.get(url, params={"limit": limit}, headers=headers)
            resp.raise_for_status()
            data = resp.json()

        releases: list[ReleaseInfo] = []
        for item in data:
            tag = item.get("tag_name", "")
            version = tag.lstrip("v")
            assets = tuple(
                AssetInfo(
                    name=a["name"],
                    size=a.get("size", 0),
                    download_url=a["browser_download_url"],
                )
                for a in item.get("assets", [])
            )
            releases.append(ReleaseInfo(
                tag=tag,
                version=version,
                name=item.get("name", tag),
                body=item.get("body", ""),
                prerelease=item.get("prerelease", False),
                published_at=item.get("published_at", ""),
                assets=assets,
            ))
        return releases

    def get_releases_page_url(self) -> str:
        return f"{self._base_url}/{self._repo}/releases"
