"""Template engine implementation using Jinja2."""

from __future__ import annotations

import asyncio
from pathlib import Path  # noqa: TCH003
from typing import Any

from jinja2 import Environment, FileSystemLoader, TemplateError

from portal.shared.protocols.infrastructure_protocols import TemplateEngineProtocol


class TemplateEngine(TemplateEngineProtocol):
    """Process templates using Jinja2."""

    def __init__(self) -> None:
        """Initialize template engine."""
        self._environments: dict[str, Environment] = {}

    def _get_environment(self, template_dir: Path) -> Environment:
        """Get or create Jinja2 environment for a directory."""
        dir_str = str(template_dir)
        if dir_str not in self._environments:
            self._environments[dir_str] = Environment(
                loader=FileSystemLoader(dir_str),
                autoescape=False,
                keep_trailing_newline=True,
                trim_blocks=False,
                lstrip_blocks=False,
            )
        return self._environments[dir_str]

    async def render_to_file(
        self, template_path: Path, output_path: Path, context: dict[str, Any]
    ) -> bool:
        """Render template to file."""
        try:
            if not template_path.exists() or not template_path.is_file():
                return False

            template_dir = template_path.parent
            template_name = template_path.name
            env = self._get_environment(template_dir)

            template = await asyncio.to_thread(env.get_template, template_name)
            rendered = await asyncio.to_thread(template.render, **context)

            output_path.parent.mkdir(parents=True, exist_ok=True)
            await asyncio.to_thread(output_path.write_text, rendered)
            return True
        except (TemplateError, OSError):
            return False
