"""HTTP client for the KiCad bridge server (port 8772)."""

import json
import urllib.request

BRIDGE_URL = "http://127.0.0.1:8772"


def send_command(command: str, args: dict | None = None, timeout: float = 30.0) -> dict:
    """Send a command to the KiCad bridge server. Returns the JSON response."""
    payload = json.dumps({"command": command, "args": args or {}}).encode("utf-8")
    req = urllib.request.Request(
        f"{BRIDGE_URL}/command",
        data=payload,
        headers={"Content-Type": "application/json"},
        method="POST",
    )
    try:
        with urllib.request.urlopen(req, timeout=timeout) as resp:
            return json.loads(resp.read().decode("utf-8"))
    except Exception as e:
        return {"success": False, "error": str(e)}


def health_check() -> dict | None:
    """Check if the bridge server is running. Returns health dict or None."""
    try:
        req = urllib.request.Request(f"{BRIDGE_URL}/health")
        with urllib.request.urlopen(req, timeout=5) as resp:
            return json.loads(resp.read().decode("utf-8"))
    except Exception:
        return None