#!/usr/bin/env python3
"""
Minimal example: push a PolyApiIDE collection patch from an external
AI/MCP tool. Docs: https://polyapiclient.ru/docs/mcp

Get client_id / client_secret from PolyApiIDE -> Settings -> Integrations
(paid plans only). Set them as env vars before running:

  export POLYAPIIDE_CLIENT_ID=...
  export POLYAPIIDE_CLIENT_SECRET=...
  python3 example-mcp-client.py
"""
import json
import os
import urllib.error
import urllib.request

API_BASE = "https://polyapiclient.ru/api/v1"


def send_patch(payload: dict, source: str = "example-mcp-client") -> dict:
    body = json.dumps({"payload": payload, "source": source}).encode("utf-8")
    req = urllib.request.Request(
        f"{API_BASE}/collections/patches",
        data=body,
        method="POST",
        headers={
            "X-Client-Id": os.environ["POLYAPIIDE_CLIENT_ID"],
            "X-Client-Secret": os.environ["POLYAPIIDE_CLIENT_SECRET"],
            "Content-Type": "application/json",
        },
    )
    try:
        with urllib.request.urlopen(req) as res:
            return json.load(res)
    except urllib.error.HTTPError as e:
        return {"ok": False, "status": e.code, "body": e.read().decode("utf-8", "replace")}


def list_patches(status: str = "pending") -> dict:
    req = urllib.request.Request(
        f"{API_BASE}/collections/patches?status={status}",
        method="GET",
        headers={
            "X-Client-Id": os.environ["POLYAPIIDE_CLIENT_ID"],
            "X-Client-Secret": os.environ["POLYAPIIDE_CLIENT_SECRET"],
        },
    )
    with urllib.request.urlopen(req) as res:
        return json.load(res)


if __name__ == "__main__":
    example_patch = {
        "type": "polyapiide.collection-patch",
        "version": 1,
        "base": {"collectionId": "col_example", "collectionName": "My collection"},
        "ops": [
            {
                "op": "upsertRequest",
                "request": {
                    "id": "req_ping",
                    "name": "Ping",
                    "method": "GET",
                    "folderPath": [],
                    "url": {"raw": "https://api.example.com/ping", "query": []},
                    "headers": [
                        {"key": "Accept", "value": "application/json", "disabled": False}
                    ],
                },
            },
        ],
    }

    result = send_patch(example_patch)
    print(json.dumps(result, indent=2, ensure_ascii=False))
