"""aioimmich people api."""

from ..api import ImmichSubApi
from .models import ImmichPerson


class ImmichPeople(ImmichSubApi):
    """Immich tags api."""

    async def async_get_all_people(
        self, with_unnamed: bool = False, page_size: int = 200, max_pages: int = 10
    ) -> list[ImmichPerson]:
        """Get all people.

        Args:
            page_size (int):  assets per page
            max_pages (int):  maximum number of pages to return

        Returns:
            all people as list of `ImmichPerson`
        """
        results: list[ImmichPerson] = []
        for page in range(max_pages):
            result = await self.api.async_do_request(
                "people", params={"size": page_size, "page": page + 1}
            )
            assert isinstance(result, dict)
            people = result["people"]
            results.extend(
                ImmichPerson.from_dict(person)
                for person in people
                if person["name"] or with_unnamed
            )
            if not result.get("hasNextPage"):
                break

        return results

    async def async_get_person_by_id(self, person_id: str) -> ImmichPerson:
        """Get a specific person by its uuid.

        Args:
            person_id (str):  Person ID

        Returns:
            `ImmichPerson`
        """
        result = await self.api.async_do_request(f"people/{person_id}")
        assert isinstance(result, dict)
        return ImmichPerson.from_dict(result)

    async def async_filter_people_by_name(self, name: str) -> list[ImmichPerson]:
        """Filter people by name.

        Args:
            name (str): People name to filter by (case-insensitive)

        Returns:
            a list of `ImmichPerson`
        """
        return [
            person
            for person in await self.async_get_all_people(max_pages=50)
            if name.lower() in person.name.lower()
        ]

    async def async_get_people_count(self) -> int:
        """Get the total count of all people.

        Returns:
            total count of all people as `int`
        """
        result = await self.api.async_do_request(
            "people",
            params={
                "size": 1,
            },
        )
        assert isinstance(result, dict)
        return int(result["total"])

    async def async_get_person_thumbnail(self, person_id: str) -> bytes:
        """Download thumbnail for a person.

        Args:
            person_id (str): id of the person to fetch the thumbnail for

        Returns:
            persons thumbnail as `bytes`
        """
        result = await self.api.async_do_request(
            f"people/{person_id}/thumbnail", application="octet-stream"
        )
        assert isinstance(result, bytes)
        return result
