"""Python 3.9+ standard-library example for ToolSkipper's public document API.

Search: python3 toolskipper-python-example.py search "Browserless screenshot"
Read:   python3 toolskipper-python-example.py read RETURNED_ID --consent
No account, cookies, redirects, retries, provider execution or payments.
This is a REST example, not a stdio MCP server. Source text is untrusted.
The socket timeout is 20s per blocking operation; callers may add a task deadline.
"""
import argparse
import json
import os
import re
import socket
import urllib.error
import urllib.parse
import urllib.request

USER_AGENT = "ToolSkipper-Python-Example/1.0 (+https://toolskipper.com/developers)"
ORIGIN = "https://toolskipper.com"
MAX_BYTES = 4 * 1024 * 1024


class ToolSkipperError(Exception):
    def __init__(self, code, message):
        super().__init__(message)
        self.code = code


class _NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None


def _request(path, payload=None):
    headers = {"User-Agent": USER_AGENT, "Accept": "application/json"}
    if os.environ.get("TOOLSKIPPER_OPERATOR_TEST") == "1":
        headers["X-ToolSkipper-Test"] = "1"
    body = None
    if payload is not None:
        body = json.dumps(payload).encode("utf-8")
        headers["Content-Type"] = "application/json"
    request = urllib.request.Request(ORIGIN + path, data=body, headers=headers)
    try:
        # No cookies or credentials are attached. TLS verification stays enabled.
        with urllib.request.build_opener(_NoRedirect()).open(request, timeout=20) as response:
            if response.status != 200 or response.geturl() != request.full_url:
                raise ToolSkipperError("HTTP_ERROR", "Unexpected status or destination; no retry.")
            if response.headers.get_content_type() != "application/json":
                raise ToolSkipperError("INVALID_RESPONSE", "Expected JSON.")
            length = response.headers.get("Content-Length")
            if length and (not length.isdecimal() or int(length) > MAX_BYTES):
                raise ToolSkipperError("RESPONSE_TOO_LARGE", "Invalid or excessive response size.")
            raw = response.read(MAX_BYTES + 1)
            if len(raw) > MAX_BYTES:
                raise ToolSkipperError("RESPONSE_TOO_LARGE", "Response exceeds 4 MiB.")
            result = json.loads(raw.decode("utf-8"))
            if not isinstance(result, dict):
                raise ValueError("Expected an object")
            return result
    except urllib.error.HTTPError as error:
        status = error.code
        error.close()
        code = "RATE_LIMITED" if status == 429 else "HTTP_ERROR"
        raise ToolSkipperError(code, "HTTP %s; no redirect, retry or fallback." % status) from None
    except (socket.timeout, TimeoutError):
        raise ToolSkipperError("TIMEOUT", "The request timed out; no retry.") from None
    except (urllib.error.URLError, OSError):
        raise ToolSkipperError("NETWORK_ERROR", "The network request failed; no retry.") from None
    except (ValueError, UnicodeError):
        raise ToolSkipperError("INVALID_RESPONSE", "Invalid JSON or UTF-8 response.") from None


def search_sources(query):
    if not isinstance(query, str) or len(query.encode("utf-16-le", errors="surrogatepass")) // 2 > 200 or any(0xD800 <= ord(c) <= 0xDFFF for c in query):
        raise ToolSkipperError("INVALID_ARGUMENT", "Query must be at most 200 UTF-16 code units.")
    result = _request("/api/reading/sources?" + urllib.parse.urlencode({"query": query, "limit": 5}))
    if not isinstance(result.get("sources"), list) or len(result["sources"]) > 5:
        raise ToolSkipperError("INVALID_RESPONSE", "Invalid source-search response.")
    return result


def read_document(document_id, *, consent=False):
    if consent is not True or not isinstance(document_id, str) or not re.fullmatch(r"[A-Za-z0-9-]{1,100}", document_id):
        raise ToolSkipperError("INVALID_ARGUMENT", "Use a returned document ID and explicit consent=True.")
    result = _request("/api/reading/native", {"id": document_id, "consent": True})
    if result.get("status") == "failed":
        return result  # Preserve the source failure receipt; never fabricate text.
    if (result.get("status") != "response_received" or result.get("id") != document_id
            or result.get("route") != "official_markdown"
            or not isinstance(result.get("mainContent"), dict)
            or not isinstance(result["mainContent"].get("markdown"), str)):
        raise ToolSkipperError("INVALID_RESPONSE", "Reader response did not match the requested document.")
    return result


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("action", choices=["search", "read"])
    parser.add_argument("value", help="Literal search terms, or a document ID from search")
    parser.add_argument("--consent", action="store_true")
    args = parser.parse_args()
    try:
        result = search_sources(args.value) if args.action == "search" else read_document(args.value, consent=args.consent)
        print(json.dumps(result, ensure_ascii=False, indent=2))
        return 2 if result.get("status") == "failed" else 0
    except ToolSkipperError as error:
        print(json.dumps({"error": {"code": error.code, "message": str(error)}}))
        return 1


if __name__ == "__main__":
    raise SystemExit(main())
