"""Email template renderer.

⚠️ AUTO-GENERATED BY PRISM — DO NOT EDIT
This file is regenerated on every `prisme generate`.
"""

from __future__ import annotations

import logging
from pathlib import Path
from string import Template
from typing import Any

logger = logging.getLogger(__name__)

# Template directory is adjacent to this file
TEMPLATES_DIR = Path(__file__).parent / "templates"


def render_template(template_name: str, context: dict[str, Any]) -> str:
    """Render an HTML email template with the given context.

    Loads ``templates/<template_name>.html``, wraps it in the base layout,
    and substitutes ``${variable}`` placeholders with values from *context*.

    Args:
        template_name: Name of the template file (without ``.html`` suffix).
        context: Dictionary of placeholder values.

    Returns:
        Rendered HTML string.

    Raises:
        FileNotFoundError: If the template file does not exist.
    """
    template_path = TEMPLATES_DIR / f"{template_name}.html"
    if not template_path.exists():
        msg = f"Email template not found: {template_path}"
        raise FileNotFoundError(msg)

    body_html = template_path.read_text(encoding="utf-8")

    # Substitute placeholders in the body
    try:
        body_html = Template(body_html).safe_substitute(context)
    except Exception:
        logger.exception("Error rendering email template %s", template_name)

    # Wrap in base layout if it exists
    base_path = TEMPLATES_DIR / "base.html"
    if base_path.exists():
        base_html = base_path.read_text(encoding="utf-8")
        try:
            html = Template(base_html).safe_substitute(body=body_html, **context)
        except Exception:
            logger.exception("Error rendering base email template")
            html = body_html
    else:
        html = body_html

    return html


def list_templates() -> list[str]:
    """List all available email template names."""
    if not TEMPLATES_DIR.exists():
        return []
    return sorted(
        p.stem for p in TEMPLATES_DIR.glob("*.html") if p.stem != "base"
    )
