"""DocAPI tool spec for LlamaIndex."""

from llama_index.core.tools.tool_spec.base import BaseToolSpec


class DocAPIToolSpec(BaseToolSpec):
    """DocAPI tool spec for generating PDFs, screenshots, and invoices."""

    spec_functions = ["generate_pdf", "capture_screenshot", "generate_invoice"]

    def __init__(self, api_key: str) -> None:
        self.api_key = api_key

    def generate_pdf(
        self,
        html: str,
        output_path: str = "output.pdf",
        format: str = "A4",
        landscape: bool = False,
    ) -> str:
        """
        Generate a PDF from HTML content using DocAPI's headless Chromium renderer.
        Full CSS support including Flexbox, Grid, and Google Fonts.

        Args:
            html (str): HTML content to render as PDF
            output_path (str): File path to save the PDF (default: output.pdf)
            format (str): Paper size — A4, Letter, Legal, or Tabloid (default: A4)
            landscape (bool): Landscape orientation (default: False)

        Returns:
            str: Success message with file path and byte count
        """
        from docapi import DocAPI

        try:
            client = DocAPI(self.api_key)
            pdf_bytes = client.pdf(html, format=format, landscape=landscape)
            with open(output_path, "wb") as f:
                f.write(pdf_bytes)
            return f"PDF saved to {output_path} ({len(pdf_bytes):,} bytes)"
        except Exception as e:
            return f"Error generating PDF: {str(e)}"

    def capture_screenshot(
        self,
        output_path: str = "screenshot.png",
        url: str = None,
        html: str = None,
        width: int = 1280,
        height: int = 800,
    ) -> str:
        """
        Capture a screenshot of a URL or HTML content as PNG.

        Args:
            output_path (str): File path to save the screenshot (default: screenshot.png)
            url (str): URL to screenshot (provide url or html, not both)
            html (str): HTML content to render and screenshot
            width (int): Viewport width in pixels (default: 1280)
            height (int): Viewport height in pixels (default: 800)

        Returns:
            str: Success message with file path and byte count
        """
        from docapi import DocAPI

        try:
            client = DocAPI(self.api_key)
            img_bytes = client.screenshot(
                url=url, html=html, width=width, height=height
            )
            with open(output_path, "wb") as f:
                f.write(img_bytes)
            return f"Screenshot saved to {output_path} ({len(img_bytes):,} bytes)"
        except Exception as e:
            return f"Error capturing screenshot: {str(e)}"

    def generate_invoice(
        self,
        from_name: str,
        to_name: str,
        line_items: list,
        output_path: str = "invoice.pdf",
        from_email: str = None,
        to_email: str = None,
        invoice_number: str = None,
        date: str = None,
        due_date: str = None,
        currency_symbol: str = "$",
        tax_percent: float = None,
        notes: str = None,
    ) -> str:
        """
        Generate a professional invoice PDF from structured data.

        Args:
            from_name (str): Sender's business name
            to_name (str): Recipient's business name
            line_items (list): List of dicts, each with 'description' (str), 'quantity' (number), 'unit_price' (number)
            output_path (str): File path to save the invoice PDF (default: invoice.pdf)
            from_email (str): Sender's email (optional)
            to_email (str): Recipient's email (optional)
            invoice_number (str): Invoice number, e.g. INV-001 (optional)
            date (str): Invoice date (optional, defaults to today)
            due_date (str): Payment due date (optional)
            currency_symbol (str): Currency symbol (default: $)
            tax_percent (float): Tax rate as percentage, 0-100 (optional)
            notes (str): Footer notes (optional)

        Returns:
            str: Success message with file path and byte count
        """
        from docapi import DocAPI

        try:
            client = DocAPI(self.api_key)
            from_data = {"name": from_name}
            if from_email:
                from_data["email"] = from_email
            to_data = {"name": to_name}
            if to_email:
                to_data["email"] = to_email

            kwargs = {
                "from_": from_data,
                "to": to_data,
                "line_items": line_items,
                "currency_symbol": currency_symbol,
            }
            if invoice_number:
                kwargs["invoice_number"] = invoice_number
            if date:
                kwargs["date"] = date
            if due_date:
                kwargs["due_date"] = due_date
            if tax_percent is not None:
                kwargs["tax_percent"] = tax_percent
            if notes:
                kwargs["notes"] = notes

            pdf_bytes = client.invoice(**kwargs)
            with open(output_path, "wb") as f:
                f.write(pdf_bytes)
            return f"Invoice saved to {output_path} ({len(pdf_bytes):,} bytes)"
        except Exception as e:
            return f"Error generating invoice: {str(e)}"
