"""Tool to save the current browser page as a PDF file."""

from __future__ import annotations

import json
import uuid
from pathlib import Path
from typing import Any

from .base import Tool


class PageToPdfTool(Tool):
    """Save the current browser page as a PDF."""

    def __init__(self, *, workspace: Path, browser_backend: Any = None) -> None:
        self._workspace = workspace
        self._backend = browser_backend

    @property
    def name(self) -> str:
        return "page_to_pdf"

    @property
    def description(self) -> str:
        return (
            "Save the current browser page as a PDF file in the workspace. "
            "Requires a native Playwright browser backend."
        )

    @property
    def parameters(self) -> dict[str, Any]:
        return {
            "type": "object",
            "properties": {
                "filename": {
                    "type": "string",
                    "description": "Output filename (without path). Defaults to page-<uuid>.pdf.",
                },
                "format": {
                    "type": "string",
                    "description": "Paper format: Letter, A4, A3, Legal, Tabloid.",
                    "enum": ["Letter", "A4", "A3", "Legal", "Tabloid"],
                },
                "landscape": {
                    "type": "boolean",
                    "description": "Use landscape orientation. Default false.",
                },
                "print_background": {
                    "type": "boolean",
                    "description": "Include background graphics. Default true.",
                },
            },
        }

    async def execute(self, **kwargs: Any) -> str:
        if self._backend is None:
            return json.dumps({"error": "No browser backend available"})

        from .browser import NativePlaywrightBrowserBackend

        if not isinstance(self._backend, NativePlaywrightBrowserBackend):
            return json.dumps({"error": "page_to_pdf requires native Playwright backend"})

        filename = kwargs.get("filename") or f"page-{uuid.uuid4().hex[:8]}.pdf"
        if not filename.endswith(".pdf"):
            filename += ".pdf"

        out_dir = self._workspace / "pdfs"
        out_dir.mkdir(parents=True, exist_ok=True)
        out_path = out_dir / filename

        fmt = kwargs.get("format", "A4")
        landscape = kwargs.get("landscape", False)
        print_bg = kwargs.get("print_background", True)

        try:
            page = await self._backend._current_page()
            await page.pdf(
                path=str(out_path),
                format=fmt,
                landscape=landscape,
                print_background=print_bg,
            )
            return json.dumps({
                "ok": True,
                "path": str(out_path),
                "format": fmt,
                "landscape": landscape,
                "url": page.url,
            })
        except Exception as exc:
            return json.dumps({"error": str(exc)})
