"""DataEyes MCP Server — shared infrastructure."""

import os

import httpx
from mcp.server.fastmcp import FastMCP

API_BASE_URL = os.environ.get("DATAEYES_API_BASE_URL", "https://api.dataeyes.ai")
API_KEY = os.environ.get("DATAEYES_API_KEY", "")

mcp = FastMCP("dataeyes_mcp")


async def send_request(
    endpoint: str,
    *,
    method: str = "POST",
    payload: dict | None = None,
    timeout: float = 60.0,
) -> dict:
    """Send a request to the DataEyes API and return the parsed response data."""
    url = f"{API_BASE_URL}{endpoint}"
    headers = {"Authorization": f"Bearer {API_KEY}"} if API_KEY else None

    async with httpx.AsyncClient() as client:
        response = await client.request(
            method,
            url,
            headers=headers,
            json=payload,
            timeout=timeout,
        )
        response.raise_for_status()
        body = response.json()

    code = body.get("code", -1)
    if code != 0:
        msg = body.get("message", "unknown error")
        raise RuntimeError(f"API error (code={code}): {msg}")

    return body.get("data", {})
