"""
Export - Render HTML slides to PNG/PDF using Playwright.
"""
import asyncio
from pathlib import Path
from typing import List, Literal

try:
    from playwright.async_api import async_playwright
    HAS_PLAYWRIGHT = True
except ImportError:
    HAS_PLAYWRIGHT = False


async def _export_async(
    slides: List[str],
    output_dir: str,
    width: int = 1920,
    height: int = 1080,
    format: Literal["png", "pdf"] = "png",
) -> List[str]:
    """
    Export slides to PNG or PDF files.

    Args:
        slides: List of HTML strings
        output_dir: Directory to save files
        width: Slide width in pixels
        height: Slide height in pixels
        format: Output format ("png" or "pdf")

    Returns:
        List of saved file paths
    """
    if not HAS_PLAYWRIGHT:
        raise ImportError(
            "Playwright required for export. Install with:\n"
            "  pip install playwright\n"
            "  playwright install chromium"
        )

    if format not in ("png", "pdf"):
        raise ValueError(f"format must be 'png' or 'pdf', got '{format}'")

    output_path = Path(output_dir)
    output_path.mkdir(parents=True, exist_ok=True)

    paths = []

    async with async_playwright() as p:
        browser = await p.chromium.launch()
        page = await browser.new_page(viewport={"width": width, "height": height})

        for i, html in enumerate(slides, 1):
            # Save HTML
            html_path = output_path / f"slide-{i:02d}.html"
            html_path.write_text(html, encoding="utf-8")

            # Render slide
            await page.set_content(html, wait_until="networkidle")

            if format == "png":
                out_path = output_path / f"slide-{i:02d}.png"
                await page.screenshot(path=str(out_path), type="png")
            else:  # pdf
                out_path = output_path / f"slide-{i:02d}.pdf"
                await page.pdf(
                    path=str(out_path),
                    width=f"{width}px",
                    height=f"{height}px",
                    print_background=True,
                )

            paths.append(str(out_path))

        await browser.close()

    return paths


def export(
    slides: List[str],
    output_dir: str,
    width: int = 1920,
    height: int = 1080,
    format: Literal["png", "pdf"] = "png",
) -> List[str]:
    """
    Export slides to PNG or PDF files (sync wrapper).

    Args:
        slides: List of HTML strings
        output_dir: Directory to save files
        width: Slide width in pixels (default: 1920)
        height: Slide height in pixels (default: 1080)
        format: Output format - "png" (default) or "pdf"

    Returns:
        List of saved file paths

    Example:
        slides = [slide_hero(), slide_problem(), ...]
        paths = export(slides, "/tmp/my-deck/")
        paths = export(slides, "/tmp/my-deck/", format="pdf")
    """
    return asyncio.run(_export_async(slides, output_dir, width, height, format))


async def export_async(
    slides: List[str],
    output_dir: str,
    width: int = 1920,
    height: int = 1080,
    format: Literal["png", "pdf"] = "png",
) -> List[str]:
    """
    Export slides to PNG or PDF files (async version).

    Use this if you're already in an async context.
    """
    return await _export_async(slides, output_dir, width, height, format)


def export_pdf(
    slides: List[str],
    output_dir: str,
    width: int = 1920,
    height: int = 1080,
) -> List[str]:
    """
    Export slides to PDF files (convenience wrapper).

    Args:
        slides: List of HTML strings
        output_dir: Directory to save files
        width: Slide width in pixels (default: 1920)
        height: Slide height in pixels (default: 1080)

    Returns:
        List of saved PDF file paths
    """
    return export(slides, output_dir, width, height, format="pdf")
