#!/usr/bin/env python3
"""Clic'n Done PDF for AI assistants: an MCP server (stdio) that converts files on your
computer with https://pdf.clicndone.com (PDF to Word that keeps the layout, merge, split,
compress, OCR, redaction, PDF/A and more).

One file, standard library only (Python 3.9+). Add it to your assistant:

    Claude Code:     claude mcp add clicndone-pdf -- python /path/to/clicndone_pdf_mcp.py
    Claude Desktop,
    Cursor and more: {"mcpServers": {"clicndone-pdf": {"command": "python",
                      "args": ["/path/to/clicndone_pdf_mcp.py"]}}}

Each tool takes paths to files on your computer, uploads them, waits for the result and
saves it next to the first file (or in ``output_dir``). The files are deleted from the
server as soon as the result has been downloaded.

Environment (optional): CLICNDONE_PDF_KEY, a prepaid or Premium key for bigger limits;
CLICNDONE_PDF_URL, another server (default https://pdf.clicndone.com);
CLICNDONE_PDF_TIMEOUT, seconds to wait for a job (default 600).
"""

from __future__ import annotations

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

VERSION = "1.0.0"
AGENT = f"clicndone-pdf-mcp/{VERSION}"
BASE = os.environ.get("CLICNDONE_PDF_URL", "https://pdf.clicndone.com").rstrip("/")
KEY = os.environ.get("CLICNDONE_PDF_KEY", "").strip()
TIMEOUT = float(os.environ.get("CLICNDONE_PDF_TIMEOUT", "600"))
PROTOCOLS = ("2025-06-18", "2025-03-26", "2024-11-05")
INSTRUCTIONS = (
    "Tools to convert and edit documents on the user's computer with Clic'n Done PDF. "
    "Pass absolute paths to existing files; the result is saved next to the first file "
    "(or in output_dir) and its path is returned. Files are uploaded to "
    f"{BASE} and deleted from it right after the result is downloaded. Free plan limits "
    "apply unless CLICNDONE_PDF_KEY is set.")


class ApiError(Exception):
    pass


def _request(method: str, path: str, body: bytes | None = None,
             headers: dict | None = None, timeout: float = 60):
    h = {"User-Agent": AGENT, "Accept": "application/json", **(headers or {})}
    if KEY:
        h["Authorization"] = f"Bearer {KEY}"
    req = urllib.request.Request(BASE + path, data=body, method=method, headers=h)
    try:
        return urllib.request.urlopen(req, timeout=timeout)
    except urllib.error.HTTPError as e:
        try:
            detail = json.loads(e.read().decode("utf-8")).get("detail")
        except Exception:
            detail = None
        if isinstance(detail, list):  # errores de validación de FastAPI
            detail = "; ".join(str(d.get("msg", d)) for d in detail)
        raise ApiError(f"HTTP {e.code}: {detail or e.reason}") from None
    except urllib.error.URLError as e:
        raise ApiError(f"cannot reach {BASE}: {e.reason}") from None


def _json(method: str, path: str, **kw) -> dict:
    with _request(method, path, **kw) as r:
        return json.loads(r.read().decode("utf-8"))


_catalog: list | None = None


def catalog() -> list:
    global _catalog
    if _catalog is None:
        _catalog = _json("GET", "/tools")["tools"]
    return _catalog


def tool_name(t: dict) -> str:
    """The English page name: /en/pdf-to-word -> pdf_to_word."""
    return t["page"].rstrip("/").rsplit("/", 1)[-1].replace("-", "_")


def _schema(o: dict) -> dict:
    text = o.get("label") or o["name"]
    if o.get("description"):
        text = f"{text}. {o['description']}" if o.get("label") else o["description"]
    choices = o.get("choices") or []
    if choices:
        text += " Values: " + "; ".join(f"'{c['value']}' = {c['label']}" for c in choices)
    s: dict = {"description": text}
    if o["type"] == "array":
        s.update(type="array", items={"type": "string", "enum": [c["value"] for c in choices]})
    elif o["type"] == "integer":
        s["type"] = "integer"
        if "min" in o:
            s["minimum"] = o["min"]
        if "max" in o:
            s["maximum"] = o["max"]
    else:
        s["type"] = "string"
        if choices:
            s["enum"] = [c["value"] for c in choices]
        if "max_length" in o:
            s["maxLength"] = o["max_length"]
    if "default" in o:
        s["default"] = o["default"]
    return s


def describe(t: dict) -> dict:
    n_min, n_max = t["min_files"], t["max_files"]
    files = {"type": "array", "items": {"type": "string"}, "minItems": n_min,
             "description": (f"Absolute paths of the input files ({', '.join(t['accepts'])})"
                             + (f", {n_min} to {n_max}" if n_max and n_max != n_min
                                else f", exactly {n_min}" if n_max == n_min
                                else f", at least {n_min}" if n_min > 1 else "")
                             + ". Several files in one call are processed together; the "
                             "result is a ZIP if there are several outputs.")}
    if n_max:
        files["maxItems"] = n_max
    props = {"files": files,
             "output_dir": {"type": "string", "description": (
                 "Folder for the result (default: the folder of the first file).")}}
    for o in t["options"]:
        props[o["name"]] = _schema(o)
    price = t.get("price") or (f"{t['credits']} credits " + (
        "per page" if t["credits_per"] == "page" else "per file"))
    return {"name": tool_name(t), "title": t["title"],
            "description": (f"{t['description']} Saves the result on this computer and "
                            f"returns its path. Credits on paid plans: {price}."),
            "inputSchema": {"type": "object", "properties": props, "required": ["files"],
                            "additionalProperties": False},
            "annotations": {"title": t["title"], "readOnlyHint": False,
                            "destructiveHint": False, "idempotentHint": True,
                            "openWorldHint": True}}


def _multipart(fields: list, files: list) -> tuple[bytes, str]:
    boundary = "----clicndone" + uuid.uuid4().hex
    out = []
    for name, value in fields:
        out.append(f'--{boundary}\r\nContent-Disposition: form-data; name="{name}"\r\n\r\n'
                   .encode() + str(value).encode("utf-8") + b"\r\n")
    for path in files:
        fname = path.name.replace('"', "'").replace("\r", " ").replace("\n", " ")
        out.append(f'--{boundary}\r\nContent-Disposition: form-data; name="files"; '
                   f'filename="{fname}"\r\nContent-Type: application/octet-stream\r\n\r\n'
                   .encode() + path.read_bytes() + b"\r\n")
    out.append(f"--{boundary}--\r\n".encode())
    return b"".join(out), f"multipart/form-data; boundary={boundary}"


def _free_name(folder: Path, name: str) -> Path:
    name = Path(name).name or "result"
    out, stem, suffix, n = folder / name, Path(name).stem, Path(name).suffix, 1
    while out.exists():
        out, n = folder / f"{stem} ({n}){suffix}", n + 1
    return out


def run(t: dict, args: dict) -> str:
    paths = [Path(os.path.expanduser(str(p))) for p in args.get("files") or []]
    if len(paths) < t["min_files"]:
        raise ApiError(f"this tool needs at least {t['min_files']} file(s)")
    for p in paths:
        if not p.is_file():
            raise ApiError(f"not a file: {p}")
    folder = Path(os.path.expanduser(str(args.get("output_dir") or paths[0].parent)))
    if not folder.is_dir():
        raise ApiError(f"not a folder: {folder}")
    fields = [("tool", t["tool"])]
    for o in t["options"]:  # lo que no se diga, con el valor por defecto de la página
        v = args.get(o["name"], o.get("default"))
        if v is None:
            continue
        if o["type"] == "array":
            fields += [(o["name"], "-")] + [(o["name"], x) for x in v]
        else:
            fields.append((o["name"], v))
    body, ctype = _multipart(fields, paths)
    job = _json("POST", "/jobs", body=body, headers={"Content-Type": ctype}, timeout=300)
    jid, end = job["id"], time.monotonic() + TIMEOUT
    while job.get("status") not in ("done", "failed"):
        if time.monotonic() > end:
            raise ApiError(f"the job took more than {TIMEOUT:.0f} s (id {jid})")
        time.sleep(1.0)
        job = _json("GET", f"/jobs/{jid}")
    if job["status"] == "failed":
        raise ApiError(f"the job failed: {job.get('error') or 'unknown error'}")
    with _request("GET", f"/jobs/{jid}/download", timeout=300) as r:
        cd = r.headers.get("Content-Disposition", "")
        m = re.search(r"filename\*=utf-8''([^;]+)", cd, re.IGNORECASE) or re.search(
            r'filename="?([^";]+)"?', cd)
        name = urllib.parse.unquote(m.group(1)) if m else "result"
        out = _free_name(folder, name)
        with open(out, "wb") as fh:
            while chunk := r.read(1 << 20):
                fh.write(chunk)
    try:
        _request("DELETE", f"/jobs/{jid}").close()
    except ApiError:
        pass  # se borra solo en unos minutos
    res = job.get("result") or {}
    extra = f", {res['pages']} page(s)" if res.get("pages") else ""
    return f"Saved {out} ({out.stat().st_size:,} bytes{extra})."


def handle(msg: dict) -> dict | None:
    method, mid = msg.get("method"), msg.get("id")
    if mid is None:  # notificaciones: nada que contestar
        return None
    try:
        if method == "initialize":
            asked = (msg.get("params") or {}).get("protocolVersion")
            result = {"protocolVersion": asked if asked in PROTOCOLS else PROTOCOLS[0],
                      "capabilities": {"tools": {"listChanged": False}},
                      "serverInfo": {"name": "clicndone-pdf", "title": "Clic'n Done PDF",
                                     "version": VERSION},
                      "instructions": INSTRUCTIONS}
        elif method == "ping":
            result = {}
        elif method == "tools/list":
            try:
                result = {"tools": [describe(t) for t in catalog()]}
            except ApiError as e:
                return {"jsonrpc": "2.0", "id": mid,
                        "error": {"code": -32603, "message": f"tool list unavailable: {e}"}}
        elif method == "tools/call":
            params = msg.get("params") or {}
            by_name = {tool_name(t): t for t in catalog()}
            t = by_name.get(params.get("name"))
            if t is None:
                return {"jsonrpc": "2.0", "id": mid, "error": {
                    "code": -32602, "message": f"unknown tool: {params.get('name')}"}}
            try:
                text, err = run(t, params.get("arguments") or {}), False
            except (ApiError, OSError) as e:
                text, err = f"Error: {e}", True
            result = {"content": [{"type": "text", "text": text}], "isError": err}
        else:
            return {"jsonrpc": "2.0", "id": mid,
                    "error": {"code": -32601, "message": f"method not found: {method}"}}
    except ApiError as e:
        return {"jsonrpc": "2.0", "id": mid, "error": {"code": -32603, "message": str(e)}}
    return {"jsonrpc": "2.0", "id": mid, "result": result}


def main() -> None:
    out = sys.stdout.buffer
    for line in sys.stdin.buffer:
        line = line.strip()
        if not line:
            continue
        try:
            msg = json.loads(line.decode("utf-8"))
        except ValueError:
            reply = {"jsonrpc": "2.0", "id": None,
                     "error": {"code": -32700, "message": "parse error"}}
        else:
            reply = handle(msg) if isinstance(msg, dict) else {
                "jsonrpc": "2.0", "id": None,
                "error": {"code": -32600, "message": "batches are not supported"}}
        if reply is not None:
            out.write(json.dumps(reply, ensure_ascii=False).encode("utf-8") + b"\n")
            out.flush()


if __name__ == "__main__":
    main()
