"""Factory for release providers — single entry point for callers."""

from __future__ import annotations

from typing import TYPE_CHECKING

from .base import ReleaseProvider, ReleaseProviderKind, is_valid_repo
from .gitea import GiteaReleaseProvider
from .github import GitHubReleaseProvider

if TYPE_CHECKING:
    import aiohttp


def build_release_provider(
    kind: str | ReleaseProviderKind,
    *,
    session: aiohttp.ClientSession,
    url: str = "",
    repo: str = "",
) -> ReleaseProvider | None:
    """Build a release provider for the given kind.

    Returns ``None`` when disabled or when required configuration is missing
    or unsafe (invalid repo format, empty URL) — callers treat the absence as
    "no checks performed" without branching on the kind string everywhere.
    """

    try:
        normalised = (
            ReleaseProviderKind(kind)
            if not isinstance(kind, ReleaseProviderKind)
            else kind
        )
    except ValueError:
        return None

    if normalised is ReleaseProviderKind.DISABLED:
        return None
    if normalised is ReleaseProviderKind.GITEA:
        if not url or not is_valid_repo(repo):
            return None
        try:
            return GiteaReleaseProvider(session=session, url=url, repo=repo)
        except ValueError:
            return None
    if normalised is ReleaseProviderKind.GITHUB:
        if not is_valid_repo(repo):
            return None
        return GitHubReleaseProvider(session=session, repo=repo)
    return None
