"""Sidecar MCP registration in ~/.claude.json (global)."""
import json
from pathlib import Path


def _global_claude_json() -> Path:
    """Return path to ~/.claude.json."""
    return Path.home() / ".claude.json"


class MCPMixin:
    """Register/unregister sidecar MCP server in global ~/.claude.json."""

    def register_mcp(self) -> bool:
        """Register the sidecar MCP server in ~/.claude.json. Returns True if added."""
        path = _global_claude_json()
        data: dict = {}
        if path.exists():
            try:
                data = json.loads(path.read_text(encoding="utf-8"))
            except Exception:
                pass

        servers = data.get("mcpServers", {})
        if "sidecar" in servers:
            return False

        servers["sidecar"] = {
            "command": "python",
            "args": ["-m", "cmdop_claude.sidecar.server"],
        }
        data["mcpServers"] = servers
        path.write_text(json.dumps(data, indent=2), encoding="utf-8")
        return True

    def unregister_mcp(self) -> bool:
        """Remove the sidecar MCP server from ~/.claude.json. Returns True if removed."""
        path = _global_claude_json()
        if not path.exists():
            return False

        try:
            data = json.loads(path.read_text(encoding="utf-8"))
        except Exception:
            return False

        servers = data.get("mcpServers", {})
        if "sidecar" not in servers:
            return False

        del servers["sidecar"]
        data["mcpServers"] = servers
        path.write_text(json.dumps(data, indent=2), encoding="utf-8")
        return True

    def is_mcp_registered(self) -> bool:
        """Check if the sidecar MCP server is in ~/.claude.json."""
        path = _global_claude_json()
        if not path.exists():
            return False
        try:
            data = json.loads(path.read_text(encoding="utf-8"))
            return "sidecar" in data.get("mcpServers", {})
        except Exception:
            return False
