from __future__ import annotations

from dataclasses import dataclass, field
from typing import Any, Optional

from aiohttp import web


@dataclass
class RequestContext:
    org_id: str = "org_anon"
    api_key_id: Optional[str] = None
    api_key_kid: Optional[str] = None
    api_key_role: Optional[str] = None
    api_key_tier: Optional[str] = None
    plan: Optional[str] = None
    quotas: dict[str, Any] = field(default_factory=dict)


def get_request_context(request: web.Request) -> RequestContext:
    ctx = request.get("ctx")
    if isinstance(ctx, RequestContext):
        return ctx
    ctx = RequestContext()
    request["ctx"] = ctx
    return ctx
