"""Framework-neutral "generate_pdf" tool for LLM agents (Python 3.9+, standard library only).

- GENERATE_PDF_TOOL is the tool definition (name, description, JSON Schema) to register with your
  function-calling API or agent framework.
- execute_generate_pdf(args) is the executor your code runs when the model calls the tool. It validates
  the arguments, calls SublimePDF with the API key from the environment (the key never enters the model
  context), saves the PDF and returns a small document reference. Failures come back as structured tool
  results the model can act on.

    template mode: {template_id, data} -> POST {base}/templates/{id}/generate  body {data}
    html mode:     {html, data?}       -> POST {base}/html-to-pdf             body {html, data?}

Usage:
    SUBLIMEPDF_API_KEY=... python3 generate_pdf_tool.py '{"template_id":"report","data":{...}}'
    python3 generate_pdf_tool.py --schema

Environment:
    SUBLIMEPDF_API_KEY       required; read only by the executor
    SUBLIMEPDF_API_BASE_URL  default https://api.sublimepdf.com/v1
    PDF_OUTPUT_DIR           default ./generated-pdfs
"""
import hashlib
import json
import os
import re
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
import uuid
from pathlib import Path
from typing import Any, Dict, Optional

GENERATE_PDF_TOOL: Dict[str, Any] = {
    "name": "generate_pdf",
    "description": (
        "Create a PDF with SublimePDF and save it on the server. It accepts two kinds of input; provide exactly one of html or template_id. "
        "html: a complete HTML document with its CSS, written for this request; optional data fills {{placeholders}} in it. "
        "template_id with data: fill a template saved in the SublimePDF app; use it when you have been given a template ID, never guess one, and send data whose keys match that template's fields. "
        "Values are printed as given: calculate totals and format dates and currency before calling. "
        "Returns a document reference (id, file name, size, pages), never the PDF content itself."
    ),
    "parameters": {
        "type": "object",
        "properties": {
            "template_id": {
                "type": "string",
                "description": 'ID of a template saved in the SublimePDF app, as given by the user or system prompt, e.g. "invoice". Omit when sending html.',
                "pattern": "^[A-Za-z0-9_-]{1,64}$",
            },
            "data": {
                "type": "object",
                "description": "Values for the placeholders in the template or HTML. Keys must match the placeholder names. Required with template_id; optional with html.",
            },
            "html": {
                "type": "string",
                "description": "Complete HTML document to render, including its CSS. Omit when sending template_id.",
                "maxLength": 200000,
            },
            "filename": {
                "type": "string",
                "description": 'Optional output file name without directories, e.g. "invoice-1042.pdf".',
                "pattern": "^[A-Za-z0-9][A-Za-z0-9._-]{0,95}$",
            },
        },
        "additionalProperties": False,
    },
}

ID_PATTERN = re.compile(r"^[A-Za-z0-9_-]{1,64}$")
FILENAME_PATTERN = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,95}$")
MAX_DATA_BYTES = 512 * 1024
MAX_HTML_CHARS = 200_000
MAX_RETRY_AFTER_SECONDS = 10
SERVER_ERROR_RETRIES = 2


def validate_args(raw: Any) -> list:
    """Return a list of problems with untrusted model arguments (empty list means valid)."""
    if not isinstance(raw, dict):
        return ["arguments must be a JSON object"]
    problems = [f'unknown argument "{k}"' for k in raw if k not in ("template_id", "data", "html", "filename")]
    has_template = "template_id" in raw
    has_html = "html" in raw
    if has_template == has_html:
        problems.append("provide exactly one of template_id or html")
    if has_template and (not isinstance(raw["template_id"], str) or not ID_PATTERN.match(raw["template_id"])):
        problems.append("template_id must be 1-64 characters: letters, digits, '_' or '-'")
    if has_html:
        if not isinstance(raw["html"], str) or not raw["html"].strip():
            problems.append("html must be a non-empty string")
        elif len(raw["html"]) > MAX_HTML_CHARS:
            problems.append(f"html must be at most {MAX_HTML_CHARS} characters (limit set by this executor)")
    if "data" not in raw:
        if has_template:
            problems.append("data is required with template_id")
    elif not isinstance(raw["data"], dict):
        problems.append("data must be a JSON object")
    elif len(json.dumps(raw["data"]).encode("utf-8")) > MAX_DATA_BYTES:
        problems.append(f"data must be smaller than {MAX_DATA_BYTES} bytes when serialised")
    filename = raw.get("filename")
    if filename is not None and (not isinstance(filename, str) or not FILENAME_PATTERN.match(filename)):
        problems.append("filename must be a plain file name (letters, digits, '.', '_' or '-'; no directories)")
    return problems


def _instruction_for(status: Optional[int], field: Optional[str] = None) -> Dict[str, Any]:
    if status in (400, 422):
        if field:
            text = (f'The data is invalid at "{field}". Correct that value (or ask the user for it) '
                    "and call the tool again once. Do not resend the same arguments.")
        else:
            text = ("The request was rejected. Correct the arguments described in the message and call the "
                    "tool again once. Do not resend the same arguments.")
        return {"retryable": False, "instruction": text}
    if status in (401, 403):
        return {"retryable": False, "instruction": "The PDF service is not authorised on this server. Do not retry; tell the user PDF generation is not configured."}
    if status == 402:
        return {"retryable": False, "instruction": "The account's monthly document allowance is used up. Do not retry; tell the user to upgrade the plan or wait for the monthly reset."}
    if status == 404:
        return {"retryable": False, "instruction": "That template ID does not exist. Do not guess IDs; ask the user which template to use."}
    if status == 409:
        return {"retryable": True, "instruction": "The same document is still being generated. Do not call this tool again in this turn; tell the user it is still in progress."}
    if status == 413:
        return {"retryable": False, "instruction": "The request is too large. Send fewer rows or shorter text, or ask the user to split the document."}
    if status == 429:
        return {"retryable": True, "instruction": "Rate limited even after waiting. Do not call this tool again in this turn; tell the user to try again shortly."}
    return {"retryable": True, "instruction": "The PDF service failed after retries. Do not call this tool again in this turn; tell the user the document could not be generated."}


def _error(status: Optional[int], type_: str, message: str, field: Optional[str] = None) -> Dict[str, Any]:
    err: Dict[str, Any] = {"status": status, "type": type_, "message": message}
    if field:
        err["field"] = field
    err.update(_instruction_for(status, field))
    return {"ok": False, "error": err}


def _count_pages(pdf: bytes) -> Optional[int]:
    """Best-effort page count for PDFs with uncompressed page objects (true for Chromium output)."""
    matches = re.findall(rb"/Type\s*/Page(?![s\w])", pdf)
    return len(matches) or None


def execute_generate_pdf(raw_args: Any) -> Dict[str, Any]:
    problems = validate_args(raw_args)
    if problems:
        return {"ok": False, "error": {
            "status": None, "type": "invalid_arguments", "message": "; ".join(problems), "retryable": False,
            "instruction": "Fix the arguments to match the tool schema and call the tool again once.",
        }}
    api_key = os.environ.get("SUBLIMEPDF_API_KEY")
    if not api_key:
        result = _error(401, "configuration_error", "SUBLIMEPDF_API_KEY is not set on the server.")
        result["error"]["status"] = None  # local configuration problem, no HTTP request was made
        return result

    base_url = os.environ.get("SUBLIMEPDF_API_BASE_URL", "https://api.sublimepdf.com/v1").rstrip("/")
    template_id = raw_args.get("template_id")
    source = "template" if template_id is not None else "html"
    if source == "template":
        url = f"{base_url}/templates/{urllib.parse.quote(template_id, safe='')}/generate"
        payload_body: Dict[str, Any] = {"data": raw_args["data"]}
    else:
        url = f"{base_url}/html-to-pdf"
        payload_body = {"html": raw_args["html"]}
        if raw_args.get("data"):
            payload_body["data"] = raw_args["data"]
    body = json.dumps(payload_body).encode("utf-8")
    idempotency_key = str(uuid.uuid4())  # one key per tool call, reused for every retry of that call
    server_errors_left = SERVER_ERROR_RETRIES
    waited_for_rate_limit = False
    in_flight_waits_left = 5  # 409 idempotency_in_flight: an earlier attempt with this key is still rendering
    attempt = 0

    while True:
        attempt += 1
        request = urllib.request.Request(url, data=body, method="POST", headers={
            "Authorization": f"Bearer {api_key}",
            "Content-Type": "application/json",
            "Accept": "application/pdf",
            "Idempotency-Key": idempotency_key,
        })
        try:
            with urllib.request.urlopen(request, timeout=60) as response:
                content_type = response.headers.get("Content-Type", "")
                payload = response.read()
            if "application/pdf" not in content_type:
                return _error(None, "unexpected_response", f"Expected application/pdf, got {content_type}")
            filename = raw_args.get("filename") or f"{template_id or 'document'}-{idempotency_key[:8]}.pdf"
            if not filename.endswith(".pdf"):
                filename += ".pdf"
            out_dir = Path(os.environ.get("PDF_OUTPUT_DIR", "generated-pdfs"))
            out_dir.mkdir(parents=True, exist_ok=True)
            path = (out_dir / filename).resolve()
            path.write_bytes(payload)
            return {"ok": True, "document": {
                "document_id": idempotency_key,
                "source": source,
                "template_id": template_id,
                "file_name": filename,
                "path": str(path),
                "uri": path.as_uri(),
                "bytes": len(payload),
                "pages": _count_pages(payload),
                "sha256": hashlib.sha256(payload).hexdigest(),
                "content_type": "application/pdf",
            }}
        except urllib.error.HTTPError as exc:
            status = exc.code
            if status == 429 and not waited_for_rate_limit:
                try:
                    retry_after = float(exc.headers.get("Retry-After", "1"))
                except ValueError:
                    retry_after = MAX_RETRY_AFTER_SECONDS + 1
                if retry_after <= MAX_RETRY_AFTER_SECONDS:
                    waited_for_rate_limit = True
                    time.sleep(max(retry_after, 0))
                    continue
            if status == 409 and in_flight_waits_left > 0:
                # A timed-out earlier attempt with the same Idempotency-Key is still running; wait,
                # then retry with the same key to receive its result instead of rendering twice.
                in_flight_waits_left -= 1
                try:
                    wait = float(exc.headers.get("Retry-After", "2"))
                except ValueError:
                    wait = 2
                time.sleep(min(max(wait, 1), MAX_RETRY_AFTER_SECONDS))
                continue
            if status in (500, 502, 503) and server_errors_left > 0:
                server_errors_left -= 1
                time.sleep(0.5 * 2 ** (attempt - 1))
                continue
            # Error body: {"error": {"type", "message", "field"?, "code"?, "request_id"}}. Falls back to the status line.
            type_, message, field = "http_error", f"HTTP {status}", None
            try:
                detail = json.loads(exc.read().decode("utf-8")).get("error", {})
                type_ = detail.get("type", type_)
                message = detail.get("message", message)
                field = detail.get("field")
            except (ValueError, AttributeError):
                pass
            return _error(status, type_, message, field)
        except (urllib.error.URLError, TimeoutError) as exc:
            if server_errors_left > 0:
                server_errors_left -= 1
                time.sleep(0.5 * 2 ** (attempt - 1))
                continue
            return _error(None, "network_error", str(exc))


if __name__ == "__main__":
    if len(sys.argv) > 1 and sys.argv[1] == "--schema":
        print(json.dumps(GENERATE_PDF_TOOL, indent=2))
        sys.exit(0)
    try:
        parsed = json.loads(sys.argv[1]) if len(sys.argv) > 1 else None
    except ValueError:
        parsed = sys.argv[1]
    result = execute_generate_pdf(parsed)
    print(json.dumps(result, indent=2))
    sys.exit(0 if result["ok"] else 1)
