"""Jinja2 prompt template management for the Vastian Network."""

from __future__ import annotations

import logging
from pathlib import Path

from jinja2 import Environment, FileSystemLoader, select_autoescape

logger = logging.getLogger(__name__)


class PromptEngine:
    """Loads and renders Jinja2 prompt templates."""

    def __init__(self, prompts_dir: Path) -> None:
        self.prompts_dir = prompts_dir
        if prompts_dir.exists():
            self.env = Environment(
                loader=FileSystemLoader(str(prompts_dir)),
                autoescape=select_autoescape([]),
                trim_blocks=True,
                lstrip_blocks=True,
            )
        else:
            self.env = None
            logger.warning("Prompts directory not found: %s", prompts_dir)

    def render(self, template_name: str, **context: object) -> str:
        """Render a named template with the given context variables."""
        if self.env is None:
            logger.warning("No template engine — returning empty string for %s", template_name)
            return ""

        try:
            template = self.env.get_template(template_name)
            return template.render(**context)
        except Exception:
            logger.exception("Failed to render template: %s", template_name)
            return ""

    def has_template(self, template_name: str) -> bool:
        """Check if a template exists."""
        if self.env is None:
            return False
        try:
            self.env.get_template(template_name)
            return True
        except Exception:
            return False
