"""Simmer MCP Server — exposes API docs and error lookup to AI agents."""

import time
import tempfile
import hashlib
from pathlib import Path

import httpx
from mcp.server.fastmcp import FastMCP

from simmer_mcp.errors import lookup_error

mcp = FastMCP("simmer", instructions="Simmer prediction market API docs and error troubleshooting. Read the docs resource for the full reference, use troubleshoot_error to diagnose trade failures.")

DOCS_URL = "https://docs.simmer.markets/llms-full.txt"
CACHE_TTL = 6 * 3600  # 6 hours
CACHE_DIR = Path(tempfile.gettempdir()) / "simmer-mcp-cache"


def _fetch_cached(url: str) -> str:
    """Fetch a URL with local file cache (6h TTL)."""
    CACHE_DIR.mkdir(exist_ok=True)
    cache_key = hashlib.md5(url.encode()).hexdigest()
    cache_file = CACHE_DIR / f"{cache_key}.md"
    meta_file = CACHE_DIR / f"{cache_key}.meta"

    # Check cache freshness
    if cache_file.exists() and meta_file.exists():
        cached_at = float(meta_file.read_text().strip())
        if time.time() - cached_at < CACHE_TTL:
            return cache_file.read_text()

    # Fetch fresh
    try:
        resp = httpx.get(url, timeout=15, follow_redirects=True)
        resp.raise_for_status()
        content = resp.text
        cache_file.write_text(content)
        meta_file.write_text(str(time.time()))
        return content
    except httpx.HTTPError:
        # Fall back to stale cache if available
        if cache_file.exists():
            return cache_file.read_text()
        return f"Failed to fetch {url} and no cached version available."


@mcp.resource("simmer://docs/full")
def full_docs() -> str:
    """Complete Simmer documentation — endpoints, SDK, skills, wallets, FAQ. Auto-generated from docs.simmer.markets."""
    return _fetch_cached(DOCS_URL)


@mcp.tool()
def troubleshoot_error(error_text: str) -> dict:
    """Look up a Simmer API error and get a fix.

    Pass the error message or JSON response from a failed API call.
    Returns a matched fix if the error is a known pattern, or a fallback
    pointing to the full docs.

    Args:
        error_text: The error message or response body from a failed Simmer API call.
    """
    return lookup_error(error_text)
