# TrustEval — Enterprise LLM Evaluation Framework
# Author: Antrixsh Gupta | https://www.linkedin.com/in/antrixshgupta
# License: MIT

"""PDF report generator for TrustEval evaluation results.

Converts the HTML report to PDF using WeasyPrint.  Adds print-specific
CSS for headers, footers, and page numbers.
"""

from __future__ import annotations

from pathlib import Path
from typing import Any, Dict

from trusteval.reporters.base_reporter import BaseReporter
from trusteval.reporters.html_reporter import HTMLReporter

# ---------------------------------------------------------------------------
# Print-specific CSS injected before conversion
# ---------------------------------------------------------------------------

_PRINT_CSS = """
<style>
@page {
    size: A4;
    margin: 20mm 15mm 25mm 15mm;

    @top-center {
        content: "TrustEval — Confidential Evaluation Report";
        font-size: 9px;
        color: #64748B;
        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
    }

    @bottom-left {
        content: "Generated by TrustEval";
        font-size: 9px;
        color: #64748B;
        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
    }

    @bottom-right {
        content: "Page " counter(page) " of " counter(pages);
        font-size: 9px;
        color: #64748B;
        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
    }
}

body {
    background: #FFFFFF !important;
    -webkit-print-color-adjust: exact;
    print-color-adjust: exact;
}

.header {
    -webkit-print-color-adjust: exact;
    print-color-adjust: exact;
}

table { page-break-inside: auto; }
tr { page-break-inside: avoid; page-break-after: auto; }
thead { display: table-header-group; }

.section-title { page-break-after: avoid; }
.flag { page-break-inside: avoid; }
</style>
"""


class PDFReporter(BaseReporter):
    """Generate a PDF evaluation report via WeasyPrint.

    Reuses the HTML template from :class:`HTMLReporter` and injects
    print-specific CSS for proper pagination, headers, and footers
    with page numbers.

    Args:
        evaluation_result: The evaluation result dict.

    Raises:
        ImportError: If WeasyPrint is not installed.

    Example::

        reporter = PDFReporter(result)
        path = reporter.generate("reports/eval_001.pdf")
    """

    def generate(self, output_path: str | Path) -> str:
        """Render the evaluation result to a PDF file.

        Args:
            output_path: Destination file path (with ``.pdf`` extension).

        Returns:
            Absolute path to the generated PDF file.

        Raises:
            ImportError: If WeasyPrint is not available.
            OSError: If the file cannot be written.
        """
        try:
            from weasyprint import HTML as WeasyprintHTML
        except ImportError as exc:
            raise ImportError(
                "PDFReporter requires WeasyPrint. "
                "Install it with: pip install weasyprint"
            ) from exc

        output_path = Path(output_path)
        self._ensure_parent_dir(output_path)

        # Generate the HTML content from HTMLReporter
        html_reporter = HTMLReporter(self.result)
        html_content = html_reporter.render_html()

        # Inject print-specific CSS just before </head>
        html_content = html_content.replace("</head>", f"{_PRINT_CSS}\n</head>")

        # Convert to PDF
        pdf_doc = WeasyprintHTML(string=html_content)
        pdf_doc.write_pdf(str(output_path))

        return str(output_path.resolve())
