import json
from typing import Any, Optional
import httpx
from core.exceptions import ExternalServiceError, ValidationError


class MCPClient:
    """
    Standard MCP Client for connecting to external third-party MCP servers
    (e.g., GitHub, Google Drive, Postgres, CRM, User Custom MCP Servers).
    """

    def __init__(self, timeout_seconds: float = 15.0):
        self.timeout = timeout_seconds

    async def ping_server(self, endpoint_url: str, auth_token: Optional[str] = None) -> bool:
        """Pings an external MCP server to verify reachability."""
        headers = {"Content-Type": "application/json"}
        if auth_token:
            headers["Authorization"] = f"Bearer {auth_token}"

        payload = {
            "jsonrpc": "2.0",
            "id": "ping_check",
            "method": "ping",
            "params": {},
        }

        try:
            async with httpx.AsyncClient(timeout=self.timeout) as client:
                resp = await client.post(endpoint_url, json=payload, headers=headers)
                return resp.status_code == 200
        except Exception:
            return False

    async def discover_tools(self, endpoint_url: str, auth_token: Optional[str] = None) -> list[dict[str, Any]]:
        """Queries `tools/list` on external MCP server to discover capabilities."""
        headers = {"Content-Type": "application/json"}
        if auth_token:
            headers["Authorization"] = f"Bearer {auth_token}"

        payload = {
            "jsonrpc": "2.0",
            "id": "discover_tools",
            "method": "tools/list",
            "params": {},
        }

        try:
            async with httpx.AsyncClient(timeout=self.timeout) as client:
                resp = await client.post(endpoint_url, json=payload, headers=headers)
                if resp.status_code != 200:
                    raise ExternalServiceError(f"MCP server responded with status {resp.status_code}")
                data = resp.json()
                if "error" in data:
                    raise ExternalServiceError(f"MCP error: {data['error'].get('message')}")
                return data.get("result", {}).get("tools", [])
        except httpx.RequestError as exc:
            raise ExternalServiceError(f"Failed to connect to remote MCP server: {str(exc)}")

    async def call_tool(
        self,
        endpoint_url: str,
        tool_name: str,
        arguments: dict[str, Any],
        auth_token: Optional[str] = None,
    ) -> dict[str, Any]:
        """Calls a specific tool on remote MCP server."""
        headers = {"Content-Type": "application/json"}
        if auth_token:
            headers["Authorization"] = f"Bearer {auth_token}"

        payload = {
            "jsonrpc": "2.0",
            "id": f"call_{tool_name}",
            "method": "tools/call",
            "params": {
                "name": tool_name,
                "arguments": arguments,
            },
        }

        try:
            async with httpx.AsyncClient(timeout=self.timeout) as client:
                resp = await client.post(endpoint_url, json=payload, headers=headers)
                if resp.status_code != 200:
                    raise ExternalServiceError(f"MCP tool call failed with status {resp.status_code}")
                data = resp.json()
                if "error" in data:
                    raise ExternalServiceError(f"Remote MCP execution error: {data['error'].get('message')}")
                return data.get("result", {})
        except httpx.RequestError as exc:
            raise ExternalServiceError(f"Connection error during MCP tool execution: {str(exc)}")
