"""PDF reporter — branded Cephalon Labs PDF via WeasyPrint."""

from __future__ import annotations

from pathlib import Path

from jinja2 import Environment, FileSystemLoader, select_autoescape

from sentinel.analyzers.compliance.mapper import (
    owasp_cicd_table,
    remediation_roadmap,
    soc2_gap_table,
)
from sentinel.models.config import BrandingConfig
from sentinel.models.findings import AggregatedReport
from sentinel.reporters.base import BaseReporter

_TEMPLATES_DIR = Path(__file__).parent / "templates"


class PdfReporter(BaseReporter):
    format_name = "pdf"
    file_extension = ".pdf"

    def __init__(self, branding: BrandingConfig | None = None) -> None:
        self.branding = branding

    def _write(self, report: AggregatedReport, path: Path) -> None:
        try:
            from weasyprint import HTML
        except ImportError as exc:
            raise RuntimeError(
                "WeasyPrint is required for PDF output. "
                "Install system dependencies first (see scripts/install-system-deps.sh), "
                "then: pip install weasyprint"
            ) from exc

        env = Environment(
            loader=FileSystemLoader(str(_TEMPLATES_DIR)),
            autoescape=select_autoescape(["html", "j2"]),
            trim_blocks=True,
            lstrip_blocks=True,
        )
        template = env.get_template("report.html.j2")
        html_content = template.render(
            report=report,
            branding=self.branding,
            soc2_table=soc2_gap_table(report),
            owasp_table=owasp_cicd_table(report),
            roadmap=remediation_roadmap(report),
            is_pdf=True,
        )
        HTML(string=html_content, base_url=str(_TEMPLATES_DIR)).write_pdf(str(path))
