"""Sessão do Reading por token: o React guarda o token no localStorage (as abas compartilham) e o manda em Authorization: Bearer. Nenhum cookie.

O token é o mesmo formato assinado do SessionMiddleware do Starlette (dict em JSON + base64, assinado com timestamp), então tudo que lê
`request.session` segue igual. Quando a sessão muda, a resposta traz o token novo em `X-Session-Token` (vazio = sessão apagada) e o React
o guarda; a validade (5 h) desliza a cada resposta, como o cookie fazia.
"""
from __future__ import annotations

import base64
import json
from typing import Any

from itsdangerous import BadSignature, TimestampSigner
from starlette.datastructures import MutableHeaders
from starlette.types import ASGIApp, Message, Receive, Scope, Send

TOKEN_HEADER = "X-Session-Token"


def encode_session(session: dict[str, Any], secret_key: str) -> str:
    data = base64.b64encode(json.dumps(session).encode("utf-8"))
    return TimestampSigner(str(secret_key)).sign(data).decode("utf-8")


def decode_session(token: str, secret_key: str, max_age: int) -> dict[str, Any] | None:
    try:
        data = TimestampSigner(str(secret_key)).unsign(token.encode("utf-8"), max_age=max_age)
        value = json.loads(base64.b64decode(data))
    except (BadSignature, ValueError):
        return None
    return value if isinstance(value, dict) else None


def bearer_token(scope: Scope) -> str | None:
    for name, value in scope.get("headers", []):
        if name == b"authorization" and value[:7].lower() == b"bearer ":
            return value[7:].decode("latin-1").strip() or None
    return None


class BearerSessionMiddleware:
    """Preenche `scope["session"]` a partir do Bearer e devolve o token novo no cabeçalho quando a sessão mudou."""

    def __init__(self, app: ASGIApp, secret_key: str, max_age: int) -> None:
        self.app = app
        self.secret_key = secret_key
        self.max_age = max_age

    async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
        if scope["type"] not in ("http", "websocket"):
            await self.app(scope, receive, send)
            return

        token = bearer_token(scope)
        initial = (decode_session(token, self.secret_key, self.max_age) if token else None) or {}
        scope["session"] = dict(initial)

        async def send_with_token(message: Message) -> None:
            if message["type"] == "http.response.start" and scope["session"] != initial:
                session = scope["session"]
                headers = MutableHeaders(scope=message)
                headers[TOKEN_HEADER] = encode_session(session, self.secret_key) if session else ""
            await send(message)

        await self.app(scope, receive, send_with_token)
