from __future__ import annotations

import logging
import os

log = logging.getLogger(__name__)

import httpx
from dotenv import load_dotenv
from mcp.server.fastmcp import FastMCP

from ..client import ApiClient
from ..decorators import APIError
from ..tools import register_tools

load_dotenv()

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


def _headers() -> dict:
    return {"X-API-Key": API_KEY}


def _check_response(resp: httpx.Response) -> None:
    if resp.status_code == 401:
        raise APIError("Invalid or missing API key. Ensure OBRIS_API_KEY is set in your environment.")
    if resp.status_code == 403:
        raise APIError("Access denied. Your API key doesn't have permission for this resource.")
    resp.raise_for_status()


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


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


def main():
    log.info("Obris MCP server running on stdio")
    mcp.run(transport="stdio")


if __name__ == "__main__":
    main()
