import os
import sys
import httpx
from dotenv import load_dotenv
from mcp.server.fastmcp import FastMCP
from mcp.types import ToolAnnotations

from obris_mcp import routes
from obris_mcp.decorators import APIError, handle_api_errors

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", "")


async def api_request(path: str, params: dict = None) -> dict:
    async with httpx.AsyncClient() as client:
        resp = await client.get(
            f"{API_BASE}{path}",
            params=params,
            headers={"X-API-Key": API_KEY},
            timeout=30.0,
        )
        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()
        return resp.json()


@mcp.tool(annotations=ToolAnnotations(readOnlyHint=True, openWorldHint=True))
@handle_api_errors
async def list_projects() -> str:
    """List all projects available to the current user.
    Call this to help the user identify which project they want to work within.
    """
    data = await api_request(routes.projects())
    projects = data.get("results", [])
    if not projects:
        return "No projects found."
    lines = [f"- {p['name']} (id: {p['id']})" for p in projects]
    return "Projects:\n" + "\n".join(lines)


@mcp.tool(annotations=ToolAnnotations(readOnlyHint=True, openWorldHint=True))
@handle_api_errors
async def get_project_references(project_id: str) -> str:
    """Get saved references for a specific project.
    Call list_projects first to get the project ID.

    Args:
        project_id: The project ID (from list_projects).
    """
    data = await api_request(routes.project_context(project_id))
    if not data:
        return "No references found for this project."
    lines = []
    for ref in data:
        lines.append(f"### {ref['title']}\n{ref['content']}\n(source: {ref['url']})")
    return "\n---\n".join(lines)


def main():
    print("Obris MCP server running on stdio", file=sys.stderr)
    mcp.run(transport="stdio")


if __name__ == "__main__":
    main()