from __future__ import annotations

"""Utilities related to Appwrite session cookies."""

from typing import Optional


def normalize_appwrite_session_cookie(
    project_id: str | None, session_cookie: str | None
) -> Optional[str]:
    """Return a normalized cookie string for Appwrite session authentication.

    Appwrite stores session cookies using the pattern ``a_session_<projectId>`` as the
    cookie name. Operators configuring the BFF might provide either the raw cookie
    value (only the token itself) or the full ``Cookie`` header contents copied from a
    browser. This helper ensures the string always contains the expected cookie name
    so that requests authenticated via cookie succeed regardless of the provided
    format.

    Args:
        project_id: The Appwrite project identifier used to build the cookie name.
        session_cookie: Raw cookie string or value obtained from configuration.

    Returns:
        A normalized cookie string ready to be sent via the ``Cookie`` header, or
        ``None`` when no usable session cookie is available.
    """

    if not isinstance(session_cookie, str):
        return None

    trimmed = session_cookie.strip()
    if not trimmed:
        return None

    if not project_id:
        return trimmed

    prefix = f"a_session_{project_id}"

    # When the expected prefix already appears in the string we assume the cookie is
    # well formatted and reuse the value as-is. This covers cases where the operator
    # pasted the entire ``Cookie`` header captured from developer tools.
    if prefix in trimmed:
        return trimmed

    first_segment, separator, remainder = trimmed.partition(";")
    name, has_equals, value = first_segment.partition("=")

    if has_equals:
        normalized_first = f"{prefix}={value.strip()}"
    else:
        normalized_first = f"{prefix}={first_segment.strip()}"

    rest = f"{separator}{remainder}" if separator else ""

    return f"{normalized_first}{rest}" if rest else normalized_first


__all__ = ["normalize_appwrite_session_cookie"]

