"""
Remote MCP Server for Obris — streamable HTTP server with OAuth authentication.
"""

import os
from importlib.metadata import version

import httpx
from mcp.server.fastmcp import FastMCP
from mcp.server.transport_security import TransportSecuritySettings
from mcp.types import Icon

from .auth import current_token
from ..tools import register_tools
from ..client import ApiClient

API_BASE = os.environ.get("OBRIS_API_URL", "https://api.obris.ai")
API_TIMEOUT = 30.0

mcp_server_url = os.environ.get("MCP_SERVER_URL", "https://mcp.obris.ai")
mcp_host = mcp_server_url.split("://", 1)[-1].rstrip("/")

MCP_SERVER_VERSION = version("obris-mcp")

mcp = FastMCP(
    "obris",
    instructions="Obris gives AI assistants access to your personal knowledge base. Use the tools to list topics, retrieve saved knowledge, and save new knowledge from conversations.",
    website_url="https://obris.ai",
    icons=[Icon(src="https://raw.githubusercontent.com/obris-dev/obris-mcp/main/icon.svg")],
    streamable_http_path="/",
    stateless_http=True,
    transport_security=TransportSecuritySettings(
        allowed_hosts=[mcp_host, "localhost", "127.0.0.1"],
    ),
)
mcp._mcp_server.version = MCP_SERVER_VERSION


def _headers() -> dict:
    return {"Authorization": f"Bearer {current_token.get()}"}


async def api_get(path: str, params: dict = None) -> dict:
    async with httpx.AsyncClient() as client:
        resp = await client.get(f"{API_BASE}{path}", params=params, headers=_headers(), timeout=API_TIMEOUT)
        resp.raise_for_status()
        return resp.json()


async def api_post(path: str, json: dict) -> dict:
    async with httpx.AsyncClient() as client:
        resp = await client.post(f"{API_BASE}{path}", json=json, headers=_headers(), timeout=API_TIMEOUT)
        resp.raise_for_status()
        return resp.json()


async def api_patch(path: str, json: dict) -> dict:
    async with httpx.AsyncClient() as client:
        resp = await client.patch(f"{API_BASE}{path}", json=json, headers=_headers(), timeout=API_TIMEOUT)
        resp.raise_for_status()
        return resp.json()


register_tools(mcp, ApiClient(get=api_get, post=api_post, patch=api_patch), source_type="remote-mcp", open_world=True)