"""
Tenant context management.
[AC-AISVC-10, AC-AISVC-12] Multi-tenant isolation via X-Tenant-Id header.
"""

from contextvars import ContextVar
from dataclasses import dataclass

tenant_context: ContextVar["TenantContext | None"] = ContextVar("tenant_context", default=None)


@dataclass
class TenantContext:
    tenant_id: str


def set_tenant_context(tenant_id: str) -> None:
    tenant_context.set(TenantContext(tenant_id=tenant_id))


def get_tenant_context() -> TenantContext | None:
    return tenant_context.get()


def get_tenant_id() -> str | None:
    ctx = get_tenant_context()
    return ctx.tenant_id if ctx else None


def clear_tenant_context() -> None:
    tenant_context.set(None)
