from __future__ import annotations

from typing import TYPE_CHECKING, Any

from ..._internal._schemas import APIEnvelope
from ..._internal._schemas.auth import AuthSession

if TYPE_CHECKING:
    from ._types import ClientProto


def build_tourist_headers(client: ClientProto, device_id: str | None) -> dict[str, str]:
    """Build the request headers required for unauthenticated (tourist) API calls.

    Args:
        client: Client instance used to generate the device identifier.
        device_id: Explicit device ID to use, or ``None`` to auto-generate one.

    Returns:
        A dict containing the ``x-device-id`` header.
    """
    return {"x-device-id": client.generate_x_device_id(device_id)}


def parse_login_and_apply_token(
    client: ClientProto, env: APIEnvelope[Any]
) -> APIEnvelope[AuthSession]:
    """Validate a raw login envelope and apply the session credentials to the client.

    Parses the raw API response into an ``AuthSession`` envelope. If the
    response contains a valid session, the token and account ID are written
    back to ``client`` so subsequent requests are authenticated automatically.

    Args:
        client: Client instance whose token and account ID will be updated.
        env: Raw API envelope returned by the login endpoint.

    Returns:
        A typed ``APIEnvelope[AuthSession]`` with the parsed session data.
    """
    login = APIEnvelope[AuthSession].model_validate(env)
    if login.data:
        client.set_token(login.data.token)
        client.set_account_id(login.data.account.id)
    return login
