from functools import cache

CHUNK_SIZE = 4050
CHUNK_PREFIX = "chunks"
CHUNK_SUFFIX = ".chunk"


@cache
def get_authentication_cookie_name(name: str | None, scheme: str) -> str:
    return name or scheme


def split_value_to_chunks(key: str, value: str, chunk_size: int = CHUNK_SIZE) -> dict[str, str]:
    if len(value) <= chunk_size:
        return {key: value}
    chunks = [value[i : i + chunk_size] for i in range(0, len(value), chunk_size)]
    cookies = {key: f"{CHUNK_PREFIX}-{len(chunks)}"}
    chunk_key = f"{key}{CHUNK_SUFFIX}"
    cookies.update({f"{chunk_key}.{i}": chunk for i, chunk in enumerate(chunks, 1)})
    return cookies


def join_value_from_chunks(key: str, cookies: dict[str, str]) -> str | None:
    token_value = cookies.get(key)
    if token_value is None or not token_value.startswith(f"{CHUNK_PREFIX}-"):
        return token_value
    chunks_count = int(token_value.removeprefix(f"{CHUNK_PREFIX}-"))
    chunk_key = f"{key}{CHUNK_SUFFIX}"
    return "".join(cookies[f"{chunk_key}.{i}"] for i in range(1, chunks_count + 1, 1))


def get_authorization_scheme_param(
    authorization_header_value: str | None,
) -> tuple[str, str]:
    if not authorization_header_value:
        return "", ""
    scheme, _, token = authorization_header_value.partition(" ")
    return scheme, token
