import datetime
from collections.abc import Awaitable, Callable, Iterable, Iterator, Mapping, Sequence
from re import Pattern
from typing import Any, BinaryIO, Protocol, TypeAlias, overload, type_check_only

import django.core.files.uploadedfile as uploadedfile
import django.core.files.uploadhandler as uploadhandler
from django.contrib.auth.models import _AnyUser
from django.contrib.sessions.backends.base import SessionBase
from django.contrib.sites.models import Site
from django.urls import ResolverMatch
from django.utils.datastructures import CaseInsensitiveMapping, ImmutableList, MultiValueDict
from django.utils.functional import cached_property
from typing_extensions import Self

RAISE_ERROR: object
host_validation_re: Pattern[str]

@type_check_only
class _PostDataProtocol(Protocol):
    def read(self, num_bytes: int | None = ..., /) -> bytes: ...
    def readline(self, limit: int | None = ..., /) -> bytes: ...
    def readlines(self) -> list[bytes]: ...
    def __iter__(self) -> Iterator[bytes]: ...

class UnreadablePostError(OSError): ...
class RawPostDataException(Exception): ...

_UploadHandlerList: TypeAlias = list[uploadhandler.FileUploadHandler] | ImmutableList[uploadhandler.FileUploadHandler]

class HttpHeaders(CaseInsensitiveMapping[str]):
    HTTP_PREFIX: str
    UNPREFIXED_HEADERS: set[str]
    def __init__(self, environ: Mapping[str, Any]) -> None: ...
    @classmethod
    def parse_header_name(cls, header: str) -> str | None: ...
    @classmethod
    def to_wsgi_name(cls, header: str) -> str: ...
    @classmethod
    def to_asgi_name(cls, header: str) -> str: ...
    @classmethod
    def to_wsgi_names(cls, headers: Mapping[str, Any]) -> dict[str, Any]: ...
    @classmethod
    def to_asgi_names(cls, headers: Mapping[str, Any]) -> dict[str, Any]: ...

class HttpRequest:
    GET: QueryDict
    POST: QueryDict
    COOKIES: dict[str, str]
    META: dict[str, Any]
    FILES: MultiValueDict[str, uploadedfile.UploadedFile]
    path: str
    path_info: str
    method: str | None
    resolver_match: ResolverMatch | None
    content_type: str | None
    content_params: dict[str, str] | None
    _body: bytes
    _stream: BinaryIO
    # Attributes added by optional parts of Django
    # django.contrib.admin views:
    current_app: str
    # django.contrib.auth.middleware.AuthenticationMiddleware:
    user: _AnyUser
    # django.contrib.auth.middleware.AuthenticationMiddleware:
    auser: Callable[[], Awaitable[_AnyUser]]
    # django.middleware.locale.LocaleMiddleware:
    LANGUAGE_CODE: str
    # django.contrib.sites.middleware.CurrentSiteMiddleware
    site: Site
    # django.contrib.sessions.middleware.SessionMiddleware
    session: SessionBase
    def __init__(self) -> None: ...
    def get_host(self) -> str: ...
    def get_port(self) -> str: ...
    def get_full_path(self, force_append_slash: bool = False) -> str: ...
    def get_full_path_info(self, force_append_slash: bool = False) -> str: ...
    def get_signed_cookie(
        self, key: str, default: Any = ..., salt: str = ..., max_age: int | datetime.timedelta | None = ...
    ) -> str | None: ...
    def build_absolute_uri(self, location: str | None = ...) -> str: ...
    @property
    def scheme(self) -> str | None: ...
    def is_secure(self) -> bool: ...
    @property
    def encoding(self) -> str | None: ...
    @encoding.setter
    def encoding(self, val: str) -> None: ...
    @property
    def upload_handlers(self) -> _UploadHandlerList: ...
    @upload_handlers.setter
    def upload_handlers(self, upload_handlers: _UploadHandlerList) -> None: ...
    @cached_property
    def accepted_types(self) -> list[MediaType]: ...
    @cached_property
    def accepted_types_by_precedence(self) -> list[MediaType]: ...
    def accepted_type(self, media_type: str) -> MediaType | None: ...
    def get_preferred_type(self, media_types: Sequence[str]) -> str | None: ...
    def parse_file_upload(
        self, META: Mapping[str, Any], post_data: _PostDataProtocol
    ) -> tuple[QueryDict, MultiValueDict[str, uploadedfile.UploadedFile]]: ...
    @cached_property
    def headers(self) -> HttpHeaders: ...
    @property
    def body(self) -> bytes: ...
    def _load_post_and_files(self) -> None: ...
    def accepts(self, media_type: str) -> bool: ...
    def close(self) -> None: ...
    # File-like and iterator interface, a minimal subset of BytesIO.
    def read(self, n: int | None = -1, /) -> bytes: ...
    def readline(self, limit: int | None = -1, /) -> bytes: ...
    def __iter__(self) -> Iterator[bytes]: ...
    def readlines(self) -> list[bytes]: ...

class QueryDict(MultiValueDict[str, str]):
    encoding: str = ...
    _mutable: bool = ...
    def __init__(
        self,
        query_string: str | bytes | None = ...,
        mutable: bool = ...,
        encoding: str | None = ...,
    ) -> None: ...
    def setlist(self, key: str, list_: list[str]) -> None: ...
    def setlistdefault(self, key: str, default_list: list[str] | None = ...) -> list[str]: ...
    def appendlist(self, key: str, value: str) -> None: ...
    def urlencode(self, safe: str | None = ...) -> str: ...
    @classmethod
    def fromkeys(  # type: ignore[override]
        cls,
        iterable: Iterable[bytes | str],
        value: str | bytes = ...,
        mutable: bool = ...,
        encoding: str | None = ...,
    ) -> Self: ...

class MediaType:
    main_type: str
    sub_type: str
    params: dict[str, bytes]
    def __init__(self, media_type_raw_line: str) -> None: ...
    def match(self, other: str) -> bool: ...
    @cached_property
    def quality(self) -> float: ...
    @property
    def specificity(self) -> int: ...
    @cached_property
    def range_params(self) -> dict[str, bytes]: ...

@overload
def bytes_to_text(s: None, encoding: str) -> None: ...
@overload
def bytes_to_text(s: bytes | str, encoding: str) -> str: ...
def split_domain_port(host: str) -> tuple[str, str]: ...
def validate_host(host: str, allowed_hosts: Iterable[str]) -> bool: ...
