"""PDF Reports service."""

from typing import Any, Dict, Optional
from sed_sh.services.base import BaseService


class ReportsService(BaseService):
    """Service for managing PDF report templates and generations.

    All methods may raise SedSHError or its subclasses on error.
    """

    def create_template(
        self,
        name: str,
        html: str,
        expiry_hours: int = 24,
    ) -> Dict[str, Any]:
        """Create a new report template.

        Templates are HTML files that use Handlebars syntax for variable substitution.
        The generated template endpoint can be called publicly (without authentication)
        to generate PDFs by providing JSON data.

        Args:
            name: Template name (for identification)
            html: HTML template content with Handlebars variables (max 1 MB)
            expiry_hours: Template expiry time in hours (max 24, default 24)

        Returns:
            Dict containing:
                - templateId (str): Unique template identifier
                - name (str): Template name
                - endpoint (str): Public endpoint for PDF generation
                - createdAt (int): Creation timestamp (milliseconds)
                - expiresAt (int): Expiration timestamp (seconds)

        Raises:
            InvalidRequestError: If HTML exceeds 1 MB or parameters invalid
            AuthenticationError: If API key is invalid
            SedSHError: On other errors

        Example:
            >>> html = '''
            ... <html>
            ... <body>
            ...     <h1>Hello {{name}}!</h1>
            ...     <p>Your order #{{orderNumber}} has been shipped.</p>
            ... </body>
            ... </html>
            ... '''
            >>> template = client.reports.create_template(
            ...     name="Order Confirmation",
            ...     html=html,
            ...     expiry_hours=24
            ... )
            >>> print(f"Template endpoint: {template['endpoint']}")
        """
        payload = {
            "name": name,
            "html": html,
            "expiryHours": expiry_hours,
        }
        return self._request("POST", "/reports/templates", json=payload)

    def list_templates(self) -> Dict[str, Any]:
        """List all report templates.

        Returns:
            Dict containing:
                - templates (list): List of template objects, each containing:
                    - templateId (str): Template identifier
                    - name (str): Template name
                    - endpoint (str): Public PDF generation endpoint
                    - sizeBytes (int): Template size in bytes
                    - createdAt (int): Creation timestamp
                    - expiresAt (int): Expiration timestamp
                    - status (str): Template status

        Raises:
            AuthenticationError: If API key is invalid
            SedSHError: On other errors

        Example:
            >>> templates = client.reports.list_templates()
            >>> for tpl in templates['templates']:
            ...     print(f"{tpl['name']}: {tpl['endpoint']}")
        """
        return self._request("GET", "/reports/templates")

    def get_template(self, template_id: str) -> Dict[str, Any]:
        """Get a template with its HTML content.

        Args:
            template_id: Template identifier

        Returns:
            Dict containing:
                - templateId (str): Template identifier
                - name (str): Template name
                - html (str): HTML template content
                - sizeBytes (int): Template size
                - createdAt (int): Creation timestamp
                - expiresAt (int): Expiration timestamp
                - status (str): Template status

        Raises:
            ResourceNotFoundError: If template doesn't exist
            AuthenticationError: If API key is invalid or not authorized
            SedSHError: On other errors

        Example:
            >>> template = client.reports.get_template("tpl_123")
            >>> print(f"HTML: {template['html']}")
        """
        return self._request("GET", f"/reports/templates/{template_id}")

    def delete_template(self, template_id: str) -> Dict[str, Any]:
        """Delete a template.

        Args:
            template_id: Template identifier

        Returns:
            Dict containing success confirmation

        Raises:
            ResourceNotFoundError: If template doesn't exist
            AuthenticationError: If API key is invalid or not authorized
            SedSHError: On other errors

        Example:
            >>> client.reports.delete_template("tpl_123")
        """
        return self._request("DELETE", f"/reports/templates/{template_id}")

    def generate_pdf(self, template_id: str, data: Dict[str, Any]) -> Dict[str, Any]:
        """Generate a PDF from a template and JSON data.

        This method calls the public generation endpoint. The template_id itself
        serves as authentication, so this works even without an API key.

        The PDF is generated using Puppeteer/Chromium and is available for
        download via a pre-signed URL that expires in 24 hours.

        Args:
            template_id: Template identifier
            data: JSON data to merge into the Handlebars template

        Returns:
            Dict containing:
                - generationId (str): Unique generation identifier
                - templateId (str): Template identifier
                - downloadUrl (str): Pre-signed S3 URL for PDF download (24h expiry)
                - expiresAt (int): When the download URL expires
                - sizeBytes (int): PDF size in bytes
                - computeTimeSeconds (float): Time taken to generate PDF

        Raises:
            ResourceNotFoundError: If template doesn't exist
            InvalidRequestError: If data is invalid or template compilation fails
            SedSHError: On other errors

        Example:
            >>> # Generate PDF from template
            >>> pdf = client.reports.generate_pdf(
            ...     template_id="tpl_123",
            ...     data={
            ...         "name": "John Doe",
            ...         "orderNumber": "12345",
            ...         "items": [
            ...             {"name": "Widget", "price": 9.99},
            ...             {"name": "Gadget", "price": 19.99}
            ...         ]
            ...     }
            ... )
            >>> print(f"Download: {pdf['downloadUrl']}")
            >>> print(f"Size: {pdf['sizeBytes']} bytes")
        """
        return self._request("POST", f"/reports/generate/{template_id}", json=data)

    def list_generations(self) -> Dict[str, Any]:
        """List recent PDF generations (last 100).

        Returns:
            Dict containing:
                - generations (list): List of generation objects, each containing:
                    - generationId (str): Generation identifier
                    - templateId (str): Template identifier
                    - downloadUrl (str or None): Pre-signed download URL (1h expiry)
                    - sizeBytes (int): PDF size in bytes
                    - computeTimeSeconds (float): Generation compute time
                    - createdAt (int): Creation timestamp
                    - status (str): Generation status

        Raises:
            AuthenticationError: If API key is invalid
            SedSHError: On other errors

        Example:
            >>> gens = client.reports.list_generations()
            >>> for gen in gens['generations']:
            ...     if gen['downloadUrl']:
            ...         print(f"Generation {gen['generationId']}: {gen['downloadUrl']}")
        """
        return self._request("GET", "/reports/generations")
