from pathlib import Path
from typing import Any, Dict

from jinja2 import Environment, FileSystemLoader
from weasyprint import HTML

from ..translations.base import Language, translation_manager

BASE_DIR = Path(__file__).resolve().parent.parent
templates_dir = BASE_DIR / "templates"


def generate_pdf(template_name: str, data: Dict[str, Any], output_path: str = "output.pdf", language: Language = Language.ENGLISH):
    """
    Generate a PDF report from a template and data.

    Args:
        template_name: The name of the template to use.
        data: The data to use in the template.
        output_path: The path to save the PDF file.
        language: The language for the report (default: English).
    """
    # Get language-specific template path
    localized_template = translation_manager.get_template_path(template_name, language)

    # Add translation context to data
    data_with_translations = _add_translation_context(data, language)

    env = Environment(loader=FileSystemLoader(templates_dir))
    template = env.get_template(localized_template)
    html_output = template.render(data_with_translations)
    HTML(string=html_output).write_pdf(output_path)
    return output_path


def _add_translation_context(data: Dict[str, Any], language: Language) -> Dict[str, Any]:
    """
    Add translation context to template data.

    Args:
        data: Original template data
        language: Target language

    Returns:
        Enhanced data with translation context
    """
    # Create translation context
    translation_context = {
        "t": lambda key, default=None: translation_manager.get_translation(language, key, default),
        "language": language.value,
        "is_spanish": language == Language.SPANISH,
        "is_english": language == Language.ENGLISH,
    }

    # Add translation context to data
    enhanced_data = data.copy()
    enhanced_data.update(translation_context)
    return enhanced_data
