"""MIT License

Copyright (c) 2024-2025 gunyu1019

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

from __future__ import annotations

from typing import Generic, Optional, TypeVar, TYPE_CHECKING
from pydantic import BaseModel, ConfigDict, Extra, PrivateAttr
from pydantic.alias_generators import to_camel

if TYPE_CHECKING:
    from typing import Any, Callable, Coroutine, Optional

T = TypeVar("T")


class ChzzkModel(BaseModel):
    model_config = ConfigDict(
        alias_generator=to_camel, frozen=True, extra=Extra.allow  # prevent exception.
    )

    @staticmethod
    def special_date_parsing_validator(value: T) -> T:
        if not isinstance(value, str):
            return value
        return value.replace("+09", "")


class Content(ChzzkModel, Generic[T]):
    code: int
    message: Optional[str]
    content: Optional[T]


class SearchResult(ChzzkModel, Generic[T]):
    data: list[T]

    _page: Optional[dict[str] | int] = PrivateAttr(default=None)
    _next_method: Optional[Callable[..., Coroutine[Any, Any, Content[T]]]] = (
        PrivateAttr(default=None)
    )
    _next_method_arguments: Optional[tuple[Any]] = PrivateAttr(default=None)
    _next_method_key_argument: Optional[dict[str, Any]] = PrivateAttr(default=None)

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if "page" in kwargs.keys():
            self._page = kwargs.pop("page")

    async def _next(self, *args, **kwargs) -> Optional[SearchResult]:
        if self._next_method is None:
            return None

        next_method_arguments = self._next_method_arguments or tuple()
        next_method_key_argument = self._next_method_key_argument or dict()
        next_method_arguments += args
        next_method_key_argument.update(kwargs)

        result = await self._next_method(
            *next_method_arguments, **next_method_key_argument
        )
        data = result.content
        data._next_method = self._next_method
        data._next_method_arguments = self._next_method_arguments
        data._next_method_key_argument = self._next_method_key_argument
        return data

    async def next(self) -> Optional[SearchResult]:
        if self._page is None or self._next_method is None:
            raise RuntimeError(f"This search result has only one result.")
        next_id = self._page["next"]
        result = await self._next(next=next_id)
        return result

    def __getitem__(self, index):
        if isinstance(index, (slice, int)):
            return self.data[index]
        raise TypeError("'SearchResult' object is not subscriptable.")

    def __len__(self) -> int:
        return len(self.data)


class ChannelSearchResult(SearchResult, Generic[T]):
    total_count: int
    total_pages: int

    def __init__(self, *args, **kwargs):
        print(kwargs)
        super().__init__(*args, **kwargs)

    async def next(self) -> Optional[ChannelSearchResult]:
        if self._page + 1 >= self.total_pages:
            raise TypeError("This is the last page of search result.")
        page_id = self._page + 1
        result = await self._next(page=page_id)
        return result

    async def previous(self) -> Optional[ChannelSearchResult]:
        if self._page - 1 < 0:
            raise TypeError("This is the first page of search result.")
        page_id = self._page - 1
        result = await self._next(page=page_id)
        return result
