from __future__ import annotations

from typing import TYPE_CHECKING, AsyncIterator, Dict, Iterator
from urllib.parse import quote

if TYPE_CHECKING:
    from .._core._http_client import APIResponse, AsyncHttpClient, PaginatedResponse, SyncHttpClient


class Ammunition:
    """Sync ammunition resource."""

    def __init__(self, client: SyncHttpClient) -> None:
        self._client = client

    def list(self, params: Dict | None = None) -> PaginatedResponse:
        return self._client.get_paginated("/v1/ammunition", query=params)

    def list_auto_paging(self, params: Dict | None = None) -> Iterator:
        page = (params or {}).get("page", 1)
        while True:
            result = self.list({**(params or {}), "page": page})
            yield from result.data
            if not result.pagination.total_pages or page >= result.pagination.total_pages:
                break
            page += 1

    def get(self, id: str) -> APIResponse:
        return self._client.get(f"/v1/ammunition/{quote(id, safe='')}")

    def get_bullet_svg(self, id: str) -> str:
        response = self._client.get(f"/v1/ammunition/{quote(id, safe='')}/bullet.svg")
        return response.data

    def ballistics(self, id: str, params: Dict | None = None) -> APIResponse:
        return self._client.get(
            f"/v1/ammunition/{quote(id, safe='')}/ballistics", query=params
        )


class AsyncAmmunition:
    """Async ammunition resource."""

    def __init__(self, client: AsyncHttpClient) -> None:
        self._client = client

    async def list(self, params: Dict | None = None) -> PaginatedResponse:
        return await self._client.get_paginated("/v1/ammunition", query=params)

    async def list_auto_paging(self, params: Dict | None = None) -> AsyncIterator:
        page = (params or {}).get("page", 1)
        while True:
            result = await self.list({**(params or {}), "page": page})
            for item in result.data:
                yield item
            if not result.pagination.total_pages or page >= result.pagination.total_pages:
                break
            page += 1

    async def get(self, id: str) -> APIResponse:
        return await self._client.get(f"/v1/ammunition/{quote(id, safe='')}")

    async def get_bullet_svg(self, id: str) -> str:
        response = await self._client.get(f"/v1/ammunition/{quote(id, safe='')}/bullet.svg")
        return response.data

    async def ballistics(self, id: str, params: Dict | None = None) -> APIResponse:
        return await self._client.get(
            f"/v1/ammunition/{quote(id, safe='')}/ballistics", query=params
        )
