"""Zero-dependency stdio-to-HTTP MCP bridge for Claude Desktop."""

from __future__ import annotations

import json
import os
import ssl
import sys
import urllib.error
import urllib.request


def main() -> int:
    endpoint = os.environ.get("OPENCLOUD_MCP_URL", "http://127.0.0.1:8765/mcp")
    api_key = os.environ.get("OPENCLOUD_MCP_API_KEY", "")
    insecure = os.environ.get("OPENCLOUD_MCP_INSECURE", "false").lower() in {"1", "true", "yes"}
    if not api_key:
        sys.stderr.write("Missing OPENCLOUD_MCP_API_KEY environment variable.\n")
        return 1

    ctx = ssl._create_unverified_context() if insecure else ssl.create_default_context()

    for line in sys.stdin:
        line = line.strip()
        if not line:
            continue
        req = urllib.request.Request(
            endpoint,
            data=line.encode("utf-8"),
            headers={
                "Content-Type": "application/json",
                "Authorization": f"Bearer {api_key}",
            },
            method="POST",
        )
        try:
            with urllib.request.urlopen(req, context=ctx) as resp:
                body = resp.read().decode("utf-8").strip()
                if body:
                    sys.stdout.write(body + "\n")
                    sys.stdout.flush()
        except urllib.error.HTTPError as exc:
            err_body = exc.read().decode("utf-8", errors="replace")
            try:
                req_id = json.loads(line).get("id")
            except json.JSONDecodeError:
                req_id = None
            if req_id is not None:
                sys.stdout.write(
                    json.dumps(
                        {
                            "jsonrpc": "2.0",
                            "id": req_id,
                            "error": {"code": -32000, "message": f"HTTP {exc.code}: {err_body}"},
                        }
                    )
                    + "\n"
                )
                sys.stdout.flush()
    return 0


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