"""Grounded MCP Server — exposes fact lookup tools for AI agents."""

import os

import httpx
from mcp.server.fastmcp import FastMCP

API_BASE = os.environ.get("GROUNDED_API_URL", "https://api.grounded-api.dev")
API_KEY = os.environ.get("GROUNDED_API_KEY", "")

mcp = FastMCP(name="Grounded", instructions=(
    "Grounded provides real-time, source-attributed facts. "
    "Use these tools to check package versions, service statuses, "
    "and other factual data instead of guessing or searching the web."
))


async def _query_fact(source: str, entity: str, field: str) -> str:
    """Query the Grounded API and return a formatted result."""
    headers = {}
    if API_KEY:
        headers["X-API-Key"] = API_KEY
    async with httpx.AsyncClient() as client:
        resp = await client.get(
            f"{API_BASE}/v1/fact",
            params={"source": source, "entity": entity, "field": field},
            headers=headers,
            timeout=10.0,
        )

    if resp.status_code == 200:
        data = resp.json()
        return (
            f"Value: {data['value']}\n"
            f"Source: {data['source_url']}\n"
            f"Fetched at: {data['fetched_at']}\n"
            f"Hash: {data['raw_response_hash']}\n"
            f"Tier: {data['tier']} (TTL: {data['ttl_seconds']}s)"
        )
    elif resp.status_code == 404:
        detail = resp.json().get("detail", "Not found")
        return f"Not found: {detail}"
    else:
        return f"Error: HTTP {resp.status_code}"


@mcp.tool()
async def lookup_fact(source: str, entity: str, field: str) -> str:
    """Look up any fact tracked by Grounded.

    Args:
        source: The fact source — "npm", "pypi", or "statuspage"
        entity: The entity name — e.g. "react", "flask", "github"
        field: The fact field — e.g. "latest_version", "license", "deprecated", "dep_count", "required_runtime", "weekly_downloads", or "status"
    """
    return await _query_fact(source, entity, field)


@mcp.tool()
async def check_package_version(package_name: str, registry: str = "npm") -> str:
    """Check the latest version of a package on npm or PyPI.

    Args:
        package_name: The package name — e.g. "react", "express", "flask", "requests"
        registry: "npm" or "pypi" (defaults to "npm")
    """
    return await _query_fact(registry, package_name, "latest_version")


@mcp.tool()
async def check_downloads(package_name: str, registry: str = "npm") -> str:
    """Check the weekly download count of a package on npm or PyPI.

    Args:
        package_name: The package name — e.g. "react", "express", "flask", "requests"
        registry: "npm" or "pypi" (defaults to "npm")
    """
    return await _query_fact(registry, package_name, "weekly_downloads")


@mcp.tool()
async def check_service_status(service_name: str) -> str:
    """Check the current status of a cloud service (via its status page).

    Args:
        service_name: The service name — e.g. "github", "stripe", "openai", "cloudflare", "vercel"
    """
    return await _query_fact("statuspage", service_name, "status")


def main():
    """Entry point for the grounded-mcp CLI command."""
    mcp.run(transport="stdio")


if __name__ == "__main__":
    main()
