"""i18n-aware notification template registry.

Templates are declared in code (alongside the feature that emits them);
the values are i18next-style keys, resolved against Django's translation
catalog at render time.
"""

from __future__ import annotations

from dataclasses import dataclass
from typing import Any

from django.utils import translation
from django.utils.translation import gettext


@dataclass(frozen=True)
class NotificationTemplate:
    kind: str
    title_key: str
    body_key: str
    default_channels: tuple[str, ...] = ("inbox",)


_REGISTRY: dict[str, NotificationTemplate] = {}


def register_template(template: NotificationTemplate) -> NotificationTemplate:
    existing = _REGISTRY.get(template.kind)
    if existing and existing != template:
        raise ValueError(f"template {template.kind!r} already registered with different spec")
    _REGISTRY[template.kind] = template
    return template


def get_template(kind: str) -> NotificationTemplate:
    try:
        return _REGISTRY[kind]
    except KeyError as exc:
        raise LookupError(f"no notification template for kind {kind!r}") from exc


def render(
    template: NotificationTemplate, context: dict[str, Any], *, lang: str | None = None
) -> tuple[str, str]:
    """Return ``(title, body)`` rendered in `lang` (defaults to active)."""
    with translation.override(lang or translation.get_language() or "en"):
        title = gettext(template.title_key).format(**context)
        body = gettext(template.body_key).format(**context)
    return title, body
