from datetime import date
from pathlib import Path
from typing import Any

from jinja2 import Environment, FileSystemLoader, select_autoescape

from app.core.config import settings

_TEMPLATES_DIR = Path(__file__).resolve().parent.parent / "templates" / "email"

# autoescape only for .html — the .txt counterpart must never HTML-escape
# its variables (an apostrophe in someone's name shouldn't turn into
# "&#39;" in a plain-text email).
_env = Environment(
    loader=FileSystemLoader(str(_TEMPLATES_DIR)),
    autoescape=select_autoescape(enabled_extensions=("html",), default=False),
    trim_blocks=True,
    lstrip_blocks=True,
)


def render_email(template_name: str, context: dict[str, Any]) -> tuple[str, str]:
    """Renders {template_name}.html and {template_name}.txt from
    app/templates/email/ against the same context, returning
    (html, text). logo_url/year are injected automatically — every
    template extends base.html, which always needs them, so no caller
    should have to remember to pass them."""
    full_context = {
        "logo_url": settings.email_logo_url,
        "year": date.today().year,
        **context,
    }
    html = _env.get_template(f"{template_name}.html").render(**full_context)
    text = _env.get_template(f"{template_name}.txt").render(**full_context)
    return html, text
