"""HTML → PDF helpers wrapping WeasyPrint.

Higher layers (MEL reports, exports) call :func:`render_pdf` to convert a
Django template into PDF bytes. WeasyPrint is imported lazily so that
environments without its native dependencies can still import this module.
"""
from __future__ import annotations

from typing import Any, Mapping

from django.http import HttpResponse
from django.template.loader import render_to_string


def render_pdf(
    template_name: str,
    context: Mapping[str, Any] | None = None,
    *,
    base_url: str | None = None,
) -> bytes:
    """Render ``template_name`` with ``context`` and return PDF bytes."""
    html = render_to_string(template_name, context or {})
    return render_pdf_from_html(html, base_url=base_url)


def render_pdf_from_html(html: str, *, base_url: str | None = None) -> bytes:
    """Convert an HTML string to PDF bytes via WeasyPrint.

    Import is deferred so a missing native dependency fails at call site
    rather than at module load (which would break unrelated test collection).
    """
    from weasyprint import HTML  # lazy

    return HTML(string=html, base_url=base_url).write_pdf()


def pdf_response(
    template_name: str,
    context: Mapping[str, Any] | None = None,
    *,
    filename: str,
    base_url: str | None = None,
) -> HttpResponse:
    pdf_bytes = render_pdf(template_name, context, base_url=base_url)
    response = HttpResponse(pdf_bytes, content_type="application/pdf")
    safe = filename.replace('"', "")
    response["Content-Disposition"] = f'attachment; filename="{safe}"'
    return response
