import datetime
from typing import (
    Any,
    Dict,
    Iterable,
    Iterator,
    List,
    MutableMapping,
    Optional,
    Sequence,
    Sized,
    Tuple,
    Type,
    TypeVar,
    Union,
    overload,
    Generic,
    NamedTuple,
    Collection,
)

from django.db.models.base import Model
from django.db.models.expressions import Combinable as Combinable, F as F
from django.db.models.sql.query import Query, RawQuery

from django.db import models
from django.db.models import Manager
from django.db.models.query_utils import Q as Q

_Row = TypeVar("_Row", covariant=True)

class BaseIterable(Sequence[_Row]):
    def __init__(self, queryset: QuerySet, chunked_fetch: bool = ..., chunk_size: int = ...): ...
    def __iter__(self) -> Iterator[_Row]: ...
    def __contains__(self, x: object) -> bool: ...
    def __len__(self) -> int: ...
    @overload
    def __getitem__(self, i: int) -> _Row: ...
    @overload
    def __getitem__(self, s: slice) -> Sequence[_Row]: ...

class ModelIterable(BaseIterable[Model]): ...
class ValuesIterable(BaseIterable[Dict[str, Any]]): ...
class ValuesListIterable(BaseIterable[Tuple]): ...
class NamedValuesListIterable(ValuesListIterable): ...

class FlatValuesListIterable(BaseIterable):
    def __iter__(self) -> Iterator[Any]: ...

_T = TypeVar("_T", bound=models.Model, covariant=True)

class QuerySet(Generic[_T, _Row], Collection[_Row], Sized):
    query: Query
    def __init__(
        self,
        model: Optional[Type[models.Model]] = ...,
        query: Optional[Query] = ...,
        using: Optional[str] = ...,
        hints: Optional[Dict[str, models.Model]] = ...,
    ) -> None: ...
    @classmethod
    def as_manager(cls) -> Manager[Any]: ...
    def __len__(self) -> int: ...
    def __iter__(self) -> Iterator[_Row]: ...
    def __contains__(self, x: object) -> bool: ...
    @overload
    def __getitem__(self, i: int) -> _Row: ...
    @overload
    def __getitem__(self, s: slice) -> QuerySet[_T, _Row]: ...
    def __bool__(self) -> bool: ...
    def __class_getitem__(cls, item: Type[_T]):
        pass
    def __getstate__(self) -> Dict[str, Any]: ...
    # __and__ and __or__ ignore the other QuerySet's _Row type parameter because they use the same row type as the self QuerySet.
    # Technically, the other QuerySet must be of the same type _T, but _T is covariant
    def __and__(self, other: QuerySet[_T, Any]) -> QuerySet[_T, _Row]: ...
    def __or__(self, other: QuerySet[_T, Any]) -> QuerySet[_T, _Row]: ...
    def iterator(self, chunk_size: int = ...) -> Iterator[_Row]: ...
    def aggregate(self, *args: Any, **kwargs: Any) -> Dict[str, Any]: ...
    def get(self, *args: Any, **kwargs: Any) -> _Row: ...
    def create(self, *args: Any, **kwargs: Any) -> _T: ...
    def bulk_create(
        self, objs: Iterable[Model], batch_size: Optional[int] = ..., ignore_conflicts: bool = ...
    ) -> List[_T]: ...
    def get_or_create(self, defaults: Optional[MutableMapping[str, Any]] = ..., **kwargs: Any) -> Tuple[_T, bool]: ...
    def update_or_create(
        self, defaults: Optional[MutableMapping[str, Any]] = ..., **kwargs: Any
    ) -> Tuple[_T, bool]: ...
    def earliest(self, *fields: Any, field_name: Optional[Any] = ...) -> _Row: ...
    def latest(self, *fields: Any, field_name: Optional[Any] = ...) -> _Row: ...
    # technically it's Optional[_Row], but it creates a lot of false-positives (same for last())
    def first(self) -> _Row: ...
    def last(self) -> _Row: ...
    def in_bulk(self, id_list: Iterable[Any] = ..., *, field_name: str = ...) -> Dict[Any, _T]: ...
    def delete(self) -> Tuple[int, Dict[str, int]]: ...
    def update(self, **kwargs: Any) -> int: ...
    def exists(self) -> bool: ...
    def explain(self, *, format: Optional[Any] = ..., **options: Any) -> str: ...
    def raw(
        self,
        raw_query: str,
        params: Any = ...,
        translations: Optional[Dict[str, str]] = ...,
        using: Optional[str] = ...,
    ) -> RawQuerySet: ...
    # The type of values may be overridden to be more specific in the mypy plugin, depending on the fields param
    def values(self, *fields: Union[str, Combinable], **expressions: Any) -> QuerySet[_T, Dict[str, Any]]: ...
    # The type of values_list may be overridden to be more specific in the mypy plugin, depending on the fields param
    def values_list(
        self, *fields: Union[str, Combinable], flat: bool = ..., named: bool = ...
    ) -> QuerySet[_T, Any]: ...
    def dates(self, field_name: str, kind: str, order: str = ...) -> QuerySet[_T, datetime.date]: ...
    def datetimes(
        self, field_name: str, kind: str, order: str = ..., tzinfo: None = ...
    ) -> QuerySet[_T, datetime.datetime]: ...
    def none(self) -> QuerySet[_T, _Row]: ...
    def all(self) -> QuerySet[_T, _Row]: ...
    def filter(self, *args: Any, **kwargs: Any) -> QuerySet[_T, _Row]: ...
    def exclude(self, *args: Any, **kwargs: Any) -> QuerySet[_T, _Row]: ...
    def complex_filter(self, filter_obj: Any) -> QuerySet[_T, _Row]: ...
    def count(self) -> int: ...
    def union(self, *other_qs: Any, all: bool = ...) -> QuerySet[_T, _Row]: ...
    def intersection(self, *other_qs: Any) -> QuerySet[_T, _Row]: ...
    def difference(self, *other_qs: Any) -> QuerySet[_T, _Row]: ...
    def select_for_update(self, nowait: bool = ..., skip_locked: bool = ..., of: Tuple = ...) -> QuerySet[_T, _Row]: ...
    def select_related(self, *fields: Any) -> QuerySet[_T, _Row]: ...
    def prefetch_related(self, *lookups: Any) -> QuerySet[_T, _Row]: ...
    # TODO: return type
    def annotate(self, *args: Any, **kwargs: Any) -> QuerySet[Any, Any]: ...
    def order_by(self, *field_names: Any) -> QuerySet[_T, _Row]: ...
    def distinct(self, *field_names: Any) -> QuerySet[_T, _Row]: ...
    # extra() return type won't be supported any time soon
    def extra(
        self,
        select: Optional[Dict[str, Any]] = ...,
        where: Optional[List[str]] = ...,
        params: Optional[List[Any]] = ...,
        tables: Optional[List[str]] = ...,
        order_by: Optional[Sequence[str]] = ...,
        select_params: Optional[Sequence[Any]] = ...,
    ) -> QuerySet[Any, Any]: ...
    def reverse(self) -> QuerySet[_T, _Row]: ...
    def defer(self, *fields: Any) -> QuerySet[_T, _Row]: ...
    def only(self, *fields: Any) -> QuerySet[_T, _Row]: ...
    def using(self, alias: Optional[str]) -> QuerySet[_T, _Row]: ...
    @property
    def ordered(self) -> bool: ...
    @property
    def db(self) -> str: ...
    def resolve_expression(self, *args: Any, **kwargs: Any) -> Any: ...
    # TODO: remove when django adds __class_getitem__ methods
    def __getattr__(self, item: str) -> Any: ...

class RawQuerySet(Iterable[_T], Sized):
    query: RawQuery
    def __init__(
        self,
        raw_query: Union[RawQuery, str],
        model: Optional[Type[models.Model]] = ...,
        query: Optional[Query] = ...,
        params: Tuple[Any] = ...,
        translations: Optional[Dict[str, str]] = ...,
        using: str = ...,
        hints: Optional[Dict[str, models.Model]] = ...,
    ) -> None: ...
    def __len__(self) -> int: ...
    def __iter__(self) -> Iterator[_T]: ...
    def __bool__(self) -> bool: ...
    @overload
    def __getitem__(self, k: int) -> _T: ...
    @overload
    def __getitem__(self, k: str) -> Any: ...
    @overload
    def __getitem__(self, k: slice) -> RawQuerySet[_T]: ...
    @property
    def columns(self) -> List[str]: ...
    @property
    def db(self) -> str: ...
    def iterator(self) -> Iterator[_T]: ...
    @property
    def model_fields(self) -> Dict[str, str]: ...
    def prefetch_related(self, *lookups: Any) -> RawQuerySet[_T]: ...
    def resolve_model_init_order(self) -> Tuple[List[str], List[int], List[Tuple[str, int]]]: ...
    def using(self, alias: Optional[str]) -> RawQuerySet[_T]: ...

class Prefetch(object):
    def __init__(self, lookup: str, queryset: Optional[QuerySet] = None, to_attr: Optional[str] = None) -> None: ...
    def __getstate__(self) -> Dict[str, Any]: ...
    def add_prefix(self, prefix: str) -> None: ...
    def get_current_prefetch_to(self, level: int) -> str: ...
    def get_current_to_attr(self, level: int) -> Tuple[str, str]: ...
    def get_current_queryset(self, level) -> Optional[QuerySet]: ...

def prefetch_related_objects(model_instances: Iterable[_T], *related_lookups: Union[str, Prefetch]) -> None: ...
def get_prefetcher(instance: Model, through_attr: str, to_attr: str) -> Tuple[Any, Any, bool, bool]: ...

class InstanceCheckMeta(type): ...
class EmptyQuerySet(metaclass=InstanceCheckMeta): ...
