from pathlib import Path

from jinja2 import Environment, FileSystemLoader, TemplateNotFound, select_autoescape

from ..exceptions import TemplateError
from .logger import get_mail_logger

logger = get_mail_logger()


class TemplateEngine:
    """
    Motor de templates basado en Jinja2.
    La ruta de templates la define el proyecto consumidor.
    """

    def __init__(self, templates_path: str | Path):
        path = Path(templates_path)

        if not path.exists() or not path.is_dir():
            raise TemplateError(f"La carpeta de templates no existe: {path}")

        self.templates_path = path

        self.env = Environment(
            loader=FileSystemLoader(str(path)),
            autoescape=select_autoescape(["html", "xml"]),
        )

    def render(self, template_name: str, context: dict | None = None) -> str:
        context = context or {}

        try:
            template = self.env.get_template(template_name)
        except TemplateNotFound as e:
            raise TemplateError(f"Template no encontrado: {template_name}") from e
        except Exception as e:
            raise TemplateError(f"Error cargando template '{template_name}': {e}") from e

        try:
            return template.render(**context)
        except Exception as e:
            raise TemplateError(f"Error renderizando template '{template_name}': {e}") from e