import logging
import os
import platform
from datetime import datetime
from logging import ERROR
from textwrap import dedent

from strif import atomic_output_file

from kash.config.logger import get_logger
from kash.config.settings import APP_NAME
from kash.kits.media.libs import media_templates_dir
from kash.web_gen import base_templates_dir as common_templates_dir
from kash.web_gen.template_render import render_web_template

log = get_logger(__name__)


def weasyprint_setup() -> None:
    is_macos = platform.system() == "Darwin"
    if is_macos:
        dylib = os.getenv("DYLD_LIBRARY_PATH")
        homebrew_lib = "/opt/homebrew/lib"

        new_dylib = f"{dylib}:{homebrew_lib}" if dylib else homebrew_lib
        print("Setting DYLD_LIBRARY_PATH to: %s", new_dylib)
        # os.environ["DYLD_LIBRARY_PATH"] = new_dylib

    try:
        import weasyprint  # noqa: F401
    except ImportError:
        if is_macos:
            log.exception(
                dedent(
                    """Failed to import weasyprint. Installing with `brew` may help. See:
                    https://github.com/Kozea/WeasyPrint/issues/1448
                    https://github.com/astral-sh/uv/issues/6971
                    """
                )
            )

    # Reduce weasyprint noisiness.
    log_levels = {
        "weasyprint": ERROR,
        "weasyprint.progress": ERROR,
    }
    for logger_name, level in log_levels.items():
        logger = logging.getLogger(logger_name)
        logger.setLevel(level)
        logger.propagate = True


def html_to_pdf(
    html_content: str,
    output_file_path: str,
    title: str | None = None,
) -> None:
    """
    Converts an HTML doc to a nicely formatted PDF file.
    """

    today = datetime.now().strftime("%Y-%m-%d")
    footer = f"Generated by {APP_NAME} on {today}"

    title = title or ""

    # Scale the content down a bit.
    scaled_html = f"""
        <style>
            body {{
                transform: scale(0.9);
                transform-origin: top left;
            }}
        </style>
        {html_content}
        """

    extra_css = render_web_template(
        media_templates_dir,
        "pdf_styles.css.jinja",
        {
            "title": title,
            "footer": footer,
        },
    )

    full_html = render_web_template(
        common_templates_dir,
        "base_webpage.html.jinja",
        {
            "title": title,
            "content": scaled_html,  # Use the scaled content
            "extra_css": extra_css,
        },
    )

    # Create PDF.
    weasyprint_setup()
    import weasyprint

    weasy_html = weasyprint.HTML(string=full_html)
    with atomic_output_file(output_file_path, make_parents=True) as temp_file_path:
        weasy_html.write_pdf(temp_file_path)
