"""
PDF Service — Renders CV data to PDF bytes using Jinja2 + WeasyPrint.

Pipeline:
    cv_data (dict) → Jinja2 template render → HTML string → WeasyPrint → PDF bytes
"""

import logging
from pathlib import Path
from typing import Dict, Any

from jinja2 import Environment, FileSystemLoader, select_autoescape
from weasyprint import HTML

logger = logging.getLogger(__name__)

# Path to the templates directory (relative to project root)
_TEMPLATES_DIR = Path(__file__).resolve().parent.parent / "templates" / "cv"


class PDFService:
    """Service for generating CV PDFs from structured data."""

    def __init__(self, templates_dir: Path = _TEMPLATES_DIR) -> None:
        if not templates_dir.is_dir():
            raise FileNotFoundError(
                f"Templates directory not found: {templates_dir}"
            )
        self._jinja_env = Environment(
            loader=FileSystemLoader(str(templates_dir)),
            autoescape=select_autoescape(["html", "xml"]),
        )

    def generate_cv_pdf(self, cv_data: Dict[str, Any], template_name: str = "default.html") -> bytes:
        """
        Render `cv_data` into the named template and return the resulting PDF as bytes.

        Args:
            cv_data: Dict with keys: personal_info, profil, experiences, formations, skills, languages
            template_name: Filename of the template inside templates/cv/

        Returns:
            PDF binary content as bytes.

        Raises:
            jinja2.TemplateNotFound: If the template file does not exist.
            Exception: If WeasyPrint fails to render the HTML.
        """
        logger.info("Rendering CV PDF (template=%s)", template_name)

        # 1. Render Jinja2 template to HTML string
        template = self._jinja_env.get_template(template_name)
        html_string = template.render(**cv_data)

        # 2. Convert HTML to PDF bytes via WeasyPrint
        pdf_bytes = HTML(string=html_string).write_pdf()

        if not pdf_bytes:
            raise RuntimeError("WeasyPrint returned empty PDF bytes")

        logger.info("CV PDF generated (%d bytes)", len(pdf_bytes))
        return pdf_bytes


# Module-level singleton — convenient for direct import
pdf_service = PDFService()
