"""Small Python client for the mepdf Web API beta.

This is a source client, not a published package. The current endpoint is
unauthenticated and has no production SLA. See https://mepdf.com/developers.
"""

from contextlib import ExitStack
from pathlib import Path
import re

import requests


class MePDFError(RuntimeError):
    """Raised when mepdf returns a non-success status."""

    def __init__(self, status_code: int, message: str):
        super().__init__(message)
        self.status_code = status_code


class MePDFClient:
    """Call mepdf's synchronous file-processing endpoint from a server."""

    def __init__(self, base_url: str = "https://mepdf.com", timeout: int = 120):
        self.base_url = base_url.rstrip("/")
        self.timeout = timeout

    def process_pdf(
        self,
        operation: str,
        files: list[str | Path],
        fields: dict[str, str | int | float] | None = None,
    ) -> bytes:
        """Process input file paths and return the output bytes (PDF, ZIP, etc.)."""
        if not re.fullmatch(r"[a-z0-9-]+", operation):
            raise ValueError("operation must be a lowercase mepdf operation slug")
        if not files:
            raise ValueError("at least one input file is required")

        with ExitStack() as stack:
            uploads = []
            for item in files:
                path = Path(item)
                stream = stack.enter_context(path.open("rb"))
                uploads.append(("files", (path.name, stream, "application/octet-stream")))
            response = requests.post(
                f"{self.base_url}/api/pdf/{operation}",
                files=uploads,
                data={key: str(value) for key, value in (fields or {}).items()},
                timeout=self.timeout,
            )

        if not response.ok:
            try:
                message = response.json().get("detail", response.text)
            except ValueError:
                message = response.text
            raise MePDFError(response.status_code, str(message))
        return response.content
