import logging
from pathlib import Path
from typing import Any

from jinja2 import Environment, FileSystemLoader, TemplateError, TemplateNotFound

logger = logging.getLogger(__name__)


def render_and_write_template(
    template_name: str,
    output_file: Path,
    context: dict[str, Any],
) -> bool:
    """Render a Jinja2 template and write the result to an output file."""
    template_dir = Path(__file__).parent.absolute()

    logger.debug("Initializing Jinja2 environment in directory: %s", template_dir)

    env = Environment(
        loader=FileSystemLoader(template_dir),
        autoescape=False,
        trim_blocks=True,
        lstrip_blocks=True,
    )

    try:
        template = env.get_template(template_name)
        logger.debug("Loaded template: %s", template_name)
    except TemplateNotFound:
        logger.exception("Template '%s' not found in '%s'.", template_name, template_dir)
        return False
    except TemplateError:
        logger.exception("Template error")
        return False

    try:
        rendered_content = template.render(context)
        logger.debug("Rendered template with context: %s", context)
    except Exception:
        logger.exception("Error rendering template '%s'", template_name)
        return False

    try:
        output_file.parent.mkdir(parents=True, exist_ok=True)
        output_file.write_text(rendered_content, encoding="utf-8")
        logger.info("File successfully written: %s", output_file)
    except OSError:
        logger.exception("Failed to write output file '%s'", output_file)
        return False

    return True
