"""
Report PDF Generator — generates branded report PDFs via Jinja2 + WeasyPrint.
"""
import os
from datetime import datetime
from jinja2 import Environment, FileSystemLoader, select_autoescape
from weasyprint import HTML

TEMPLATES_DIR = os.path.normpath(
    os.path.join(os.path.dirname(__file__), "..", "templates")
)


class ReportPDFGenerator:
    """Generates branded report PDFs for payment methods, discounts, and activity logs."""

    def __init__(self) -> None:
        self.env = Environment(
            loader=FileSystemLoader(TEMPLATES_DIR),
            autoescape=select_autoescape(["html"]),
        )

    def generate_payment_methods_pdf(self, report_data: dict, merchant=None) -> bytes:
        template = self.env.get_template("payment_methods_report.html")
        brand_color = self._get_brand_color(merchant)
        context = {
            "report": report_data,
            "merchant_name": getattr(merchant, "name", "") if merchant else "",
            "merchant_logo_url": getattr(merchant, "logo_url", None) if merchant else None,
            "brand_color": brand_color,
            "generated_at": datetime.utcnow().strftime("%B %d, %Y"),
        }
        html_content = template.render(**context)
        return HTML(string=html_content, base_url=TEMPLATES_DIR).write_pdf()

    def generate_discounts_pdf(self, report_data: dict, merchant=None) -> bytes:
        template = self.env.get_template("discounts_report.html")
        brand_color = self._get_brand_color(merchant)
        context = {
            "report": report_data,
            "merchant_name": getattr(merchant, "name", "") if merchant else "",
            "merchant_logo_url": getattr(merchant, "logo_url", None) if merchant else None,
            "brand_color": brand_color,
            "generated_at": datetime.utcnow().strftime("%B %d, %Y"),
        }
        html_content = template.render(**context)
        return HTML(string=html_content, base_url=TEMPLATES_DIR).write_pdf()

    def generate_activity_log_pdf(self, report_data: dict, merchant=None) -> bytes:
        template = self.env.get_template("activity_log_report.html")
        brand_color = self._get_brand_color(merchant)
        context = {
            "report": report_data,
            "merchant_name": getattr(merchant, "name", "") if merchant else "",
            "merchant_logo_url": getattr(merchant, "logo_url", None) if merchant else None,
            "brand_color": brand_color,
            "generated_at": datetime.utcnow().strftime("%B %d, %Y"),
        }
        html_content = template.render(**context)
        return HTML(string=html_content, base_url=TEMPLATES_DIR).write_pdf()

    def _get_brand_color(self, merchant) -> str:
        try:
            if merchant:
                from src.apps.settings.helper import get_setting_with_default
                color = get_setting_with_default("Colors", "primary_color", merchant.id)
                if color:
                    return color
        except Exception:
            pass
        return "#28B4ED"


report_pdf_generator = ReportPDFGenerator()
