from datetime import datetime

from abs_utils.logger import setup_logger
from jinja2 import Environment, FileSystemLoader, select_autoescape

logger = setup_logger(__name__)


class TemplateService:
    """Service for rendering email templates using Jinja2."""

    def __init__(self, template_dir: str):
        """
        Initialize the template service.

        Args:
            template_dir: Directory containing template files.
        """
        self.template_dir = template_dir
        self.env = Environment(
            loader=FileSystemLoader(template_dir),
            autoescape=select_autoescape(["html", "xml"]),
        )

    def render_template(self, template_name: str, **kwargs) -> str:
        """
        Render a template with the provided variables.

        Args:
            template_name: Name of the template file
            **kwargs: Variables to pass to the template

        Returns:
            Rendered template as string
        """
        try:
            template = self.env.get_template(template_name)

            # Add default timestamp if not provided
            if "timestamp" not in kwargs:
                kwargs["timestamp"] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

            return template.render(**kwargs)

        except Exception as e:
            logger.error(f"Error rendering template {template_name}: {str(e)}")
            raise

    def render_email_template(self, title: str, content: str, **kwargs) -> str:
        """
        Render the email template with common variables.

        Args:
            title: Email title
            content: Email content (can be HTML)
            **kwargs: Additional template variables

        Returns:
            Rendered email HTML
        """
        return self.render_template(
            "email_template.html", title=title, content=content, **kwargs
        )
