"""
inventory/services/pdf_service.py
──────────────────────────────────
WeasyPrint HTML→PDF rendering helper, shared by the DRF views, the admin
report pages, and the author-statement email sender.
"""

import base64
from functools import lru_cache
from pathlib import Path

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

_LOGO_PATH = Path(settings.BASE_DIR) / "inventory" / "static" / "inventory" / "img" / "logo.png"


@lru_cache(maxsize=1)
def _logo_data_uri() -> str:
    """
    Base64-embed the brand logo so it always renders regardless of
    collectstatic/STATIC_ROOT state or WeasyPrint's base_url resolution —
    this must work identically in dev, docker, and cPanel.
    """
    try:
        data = _LOGO_PATH.read_bytes()
    except OSError:
        return ""
    return f"data:image/png;base64,{base64.b64encode(data).decode('ascii')}"


def _with_logo(context: dict) -> dict:
    context.setdefault("logo_data_uri", _logo_data_uri())
    return context


def render_pdf(template_name: str, context: dict, filename: str) -> HttpResponse:
    try:
        from weasyprint import HTML
    except ImportError:
        return HttpResponse("WeasyPrint is not installed.", status=503)

    html_string = render_to_string(template_name, _with_logo(context))
    pdf_bytes = HTML(string=html_string, base_url="/").write_pdf()
    response = HttpResponse(pdf_bytes, content_type="application/pdf")
    response["Content-Disposition"] = f'attachment; filename="{filename}"'
    return response


def render_pdf_bytes(template_name: str, context: dict) -> bytes:
    """Same rendering path as render_pdf(), but returns raw bytes for emailing."""
    from weasyprint import HTML

    html_string = render_to_string(template_name, _with_logo(context))
    return HTML(string=html_string, base_url="/").write_pdf()
