from __future__ import annotations

from typing import Optional

from ._core._http_client import (
    AsyncHttpClient,
    HttpClientConfig,
    SyncHttpClient,
)
from ._core._retry import RetryConfig
from ._resources import (
    Ammunition,
    AsyncAmmunition,
    AsyncCalibers,
    AsyncCategories,
    AsyncConflicts,
    AsyncCountries,
    AsyncDataQuality,
    AsyncFavorites,
    AsyncFirearms,
    AsyncGame,
    AsyncGameStats_,
    AsyncManufacturers,
    AsyncReports,
    AsyncStats,
    AsyncSupport,
    AsyncUsage,
    AsyncWebhooks,
    Calibers,
    Categories,
    Conflicts,
    Countries,
    DataQuality,
    Favorites,
    Firearms,
    Game,
    GameStats_,
    Manufacturers,
    Reports,
    Stats,
    Support,
    Usage,
    Webhooks,
)
from ._version import __version__


class GunSpec:
    """Synchronous GunSpec.io API client.

    Example::

        from gunspec import GunSpec

        client = GunSpec(api_key="gs_...")

        # List firearms
        result = client.firearms.list({"category": "pistol"})
        for firearm in result.data:
            print(firearm)

        # Context manager for clean shutdown
        with GunSpec() as client:
            data = client.firearms.get("glock-g17")
    """

    firearms: Firearms
    manufacturers: Manufacturers
    calibers: Calibers
    categories: Categories
    stats: Stats
    game: Game
    game_stats: GameStats_
    ammunition: Ammunition
    countries: Countries
    conflicts: Conflicts
    data_quality: DataQuality
    favorites: Favorites
    reports: Reports
    support: Support
    webhooks: Webhooks
    usage: Usage

    def __init__(
        self,
        *,
        api_key: Optional[str] = None,
        base_url: Optional[str] = None,
        timeout: Optional[float] = None,
        retry: Optional[RetryConfig] = None,
        default_headers: Optional[dict[str, str]] = None,
    ) -> None:
        config = HttpClientConfig(
            base_url=base_url or "https://api.gunspec.io",
            timeout=timeout or 30.0,
            api_key=api_key,
            retry=retry or RetryConfig(),
            headers={
                **(default_headers or {}),
                "User-Agent": f"gunspec-sdk/python/{__version__}",
                "X-SDK-Version": __version__,
                "X-SDK-Language": "python",
            },
        )
        self._client = SyncHttpClient(config)

        self.firearms = Firearms(self._client)
        self.manufacturers = Manufacturers(self._client)
        self.calibers = Calibers(self._client)
        self.categories = Categories(self._client)
        self.stats = Stats(self._client)
        self.game = Game(self._client)
        self.game_stats = GameStats_(self._client)
        self.ammunition = Ammunition(self._client)
        self.countries = Countries(self._client)
        self.conflicts = Conflicts(self._client)
        self.data_quality = DataQuality(self._client)
        self.favorites = Favorites(self._client)
        self.reports = Reports(self._client)
        self.support = Support(self._client)
        self.webhooks = Webhooks(self._client)
        self.usage = Usage(self._client)

    def close(self) -> None:
        """Close the underlying HTTP connection pool."""
        self._client.close()

    def __enter__(self) -> GunSpec:
        return self

    def __exit__(self, *_: object) -> None:
        self.close()


class AsyncGunSpec:
    """Asynchronous GunSpec.io API client.

    Example::

        from gunspec import AsyncGunSpec

        async with AsyncGunSpec(api_key="gs_...") as client:
            result = await client.firearms.list({"category": "rifle"})
            for firearm in result.data:
                print(firearm)
    """

    firearms: AsyncFirearms
    manufacturers: AsyncManufacturers
    calibers: AsyncCalibers
    categories: AsyncCategories
    stats: AsyncStats
    game: AsyncGame
    game_stats: AsyncGameStats_
    ammunition: AsyncAmmunition
    countries: AsyncCountries
    conflicts: AsyncConflicts
    data_quality: AsyncDataQuality
    favorites: AsyncFavorites
    reports: AsyncReports
    support: AsyncSupport
    webhooks: AsyncWebhooks
    usage: AsyncUsage

    def __init__(
        self,
        *,
        api_key: Optional[str] = None,
        base_url: Optional[str] = None,
        timeout: Optional[float] = None,
        retry: Optional[RetryConfig] = None,
        default_headers: Optional[dict[str, str]] = None,
    ) -> None:
        config = HttpClientConfig(
            base_url=base_url or "https://api.gunspec.io",
            timeout=timeout or 30.0,
            api_key=api_key,
            retry=retry or RetryConfig(),
            headers={
                **(default_headers or {}),
                "User-Agent": f"gunspec-sdk/python/{__version__}",
                "X-SDK-Version": __version__,
                "X-SDK-Language": "python",
            },
        )
        self._client = AsyncHttpClient(config)

        self.firearms = AsyncFirearms(self._client)
        self.manufacturers = AsyncManufacturers(self._client)
        self.calibers = AsyncCalibers(self._client)
        self.categories = AsyncCategories(self._client)
        self.stats = AsyncStats(self._client)
        self.game = AsyncGame(self._client)
        self.game_stats = AsyncGameStats_(self._client)
        self.ammunition = AsyncAmmunition(self._client)
        self.countries = AsyncCountries(self._client)
        self.conflicts = AsyncConflicts(self._client)
        self.data_quality = AsyncDataQuality(self._client)
        self.favorites = AsyncFavorites(self._client)
        self.reports = AsyncReports(self._client)
        self.support = AsyncSupport(self._client)
        self.webhooks = AsyncWebhooks(self._client)
        self.usage = AsyncUsage(self._client)

    async def aclose(self) -> None:
        """Close the underlying HTTP connection pool."""
        await self._client.aclose()

    async def __aenter__(self) -> AsyncGunSpec:
        return self

    async def __aexit__(self, *_: object) -> None:
        await self.aclose()
