#!/usr/bin/env python3
"""
OOTWOracle MCP Server
======================
Model Context Protocol server — lets Claude Desktop, Cursor, Windsurf,
and any MCP-enabled AI tool query Oracle predictions directly in conversation.

Install:
    pip install mcp httpx

Run:
    python server.py

Add to Claude Desktop (~/.config/claude/claude_desktop_config.json):
    {
      "mcpServers": {
        "ootworacle": {
          "command": "python",
          "args": ["/absolute/path/to/mcp-server/server.py"]
        }
      }
    }
"""

import httpx
from datetime import date

try:
    from mcp.server.fastmcp import FastMCP
except ImportError:
    raise ImportError("Install dependencies: pip install mcp httpx")

BASE_URL = "https://www.ootworacle.com"

mcp = FastMCP(
    "OOTWOracle",
    instructions="""You have access to OOTWOracle — a daily AI prediction service tracking the
psychedelic medicine ecosystem. It monitors FDA decisions, DEA scheduling,
clinical trial outcomes, biotech markets, and legislation.

Every day an 8-agent swarm debates up to 460+ signals from PubMed,
ClinicalTrials.gov, Congress, and financial markets — generating falsifiable,
confidence-scored predictions.

Use these tools when asked about psychedelic medicine regulation, FDA timelines,
clinical trials, biotech companies (Compass, MAPS, ATAI), or today's oracle report.""",
)


@mcp.tool()
def get_todays_predictions() -> str:
    """Get OOTWOracle's latest AI predictions on psychedelic medicine regulation.
    Returns today's top 5 confidence-scored predictions with reasoning and resolve dates."""
    try:
        r = httpx.get(f"{BASE_URL}/predictions.json", timeout=10)
        r.raise_for_status()
        data = r.json()
        preds = data.get("predictions", data) if isinstance(data, dict) else data
        today = data.get("date", str(date.today())) if isinstance(data, dict) else str(date.today())
        headline = data.get("headline", "") if isinstance(data, dict) else ""

        out = [f"# OOTWOracle — {today}"]
        if headline:
            out.append(f"**Report: {headline}**\n")
        for i, p in enumerate(preds[:5], 1):
            conf = p.get("confidence", p.get("confidence_score", "?"))
            title = p.get("title", p.get("prediction", ""))
            reasoning = p.get("reasoning", p.get("plain_reasoning", ""))
            resolve = p.get("resolve_date", p.get("resolves", ""))
            category = p.get("category", "")
            out.append(f"**{i}. [{conf}%] {title}**")
            if category:
                out.append(f"   Category: {category}")
            if reasoning:
                out.append(f"   {reasoning}")
            if resolve:
                out.append(f"   Resolves: {resolve}")
            out.append("")
        out.append(f"Full report: {BASE_URL}/report/{today}")
        out.append(f"Oracle Chamber debate: {BASE_URL}/oracle-chamber/{today}")
        return "\n".join(out)
    except Exception as e:
        return f"Error: {e}. Direct API: {BASE_URL}/predictions.json"


@mcp.tool()
def get_oracle_report(report_date: str = "") -> str:
    """Get the full OOTWOracle intelligence report for a specific date.
    Includes signal analysis, narrative context, and all predictions.

    Args:
        report_date: Date YYYY-MM-DD. Leave blank for today."""
    if not report_date:
        report_date = str(date.today())
    try:
        r = httpx.get(f"{BASE_URL}/all_predictions.json", timeout=10)
        r.raise_for_status()
        data = r.json()
        preds = data.get("predictions", data) if isinstance(data, dict) else data
        day_preds = [p for p in preds if p.get("date", "") == report_date]

        if day_preds:
            out = [f"# OOTWOracle Report — {report_date}\n"]
            headline = day_preds[0].get("headline", "Daily Oracle Signal")
            out.append(f"**{headline}**\n")
            for i, p in enumerate(day_preds, 1):
                conf = p.get("confidence", p.get("confidence_score", "?"))
                title = p.get("title", p.get("prediction", ""))
                reasoning = p.get("reasoning", p.get("plain_reasoning", ""))
                out.append(f"{i}. [{conf}%] {title}")
                if reasoning:
                    out.append(f"   → {reasoning}")
            out.append(f"\nFull: {BASE_URL}/report/{report_date}")
            out.append(f"Debate: {BASE_URL}/oracle-chamber/{report_date}")
            return "\n".join(out)
        else:
            return f"No data for {report_date}. Archive starts 2026-04-28. See {BASE_URL}/report/{report_date}"
    except Exception as e:
        return f"Error: {e}"


@mcp.tool()
def search_predictions(query: str, limit: int = 10) -> str:
    """Search all OOTWOracle predictions by keyword.
    Find predictions about psilocybin, MDMA, ibogaine, FDA, DEA, Compass Pathways, MAPS, ATAI, etc.

    Args:
        query: Search term (e.g. 'ibogaine', 'FDA approval', 'Compass Pathways')
        limit: Max results (default 10)"""
    try:
        r = httpx.get(f"{BASE_URL}/all_predictions.json", timeout=10)
        r.raise_for_status()
        data = r.json()
        preds = data.get("predictions", data) if isinstance(data, dict) else data

        q = query.lower()
        matches = [
            p for p in preds
            if q in " ".join([
                p.get("title", ""), p.get("prediction", ""),
                p.get("reasoning", ""), p.get("plain_reasoning", ""),
                p.get("category", ""),
            ]).lower()
        ]

        if not matches:
            return f"No matches for '{query}'. Try: psilocybin, MDMA, ibogaine, FDA, DEA, legislation, ketamine"

        out = [f"# OOTWOracle — '{query}' ({len(matches)} predictions)\n"]
        for p in matches[:limit]:
            conf = p.get("confidence", p.get("confidence_score", "?"))
            title = p.get("title", p.get("prediction", ""))
            pred_date = p.get("date", "")
            resolve = p.get("resolve_date", p.get("resolves", ""))
            out.append(f"**[{conf}%] {title}**  _{pred_date} → {resolve}_")
        if len(matches) > limit:
            out.append(f"\n_{len(matches) - limit} more at {BASE_URL}/all_predictions.json_")
        return "\n".join(out)
    except Exception as e:
        return f"Error: {e}"


@mcp.tool()
def get_oracle_status() -> str:
    """Get OOTWOracle's current live status — today's headline, top predictions,
    and what the 8-agent swarm is tracking right now."""
    try:
        r = httpx.get(f"{BASE_URL}/predictions.json", timeout=10)
        r.raise_for_status()
        data = r.json()
        preds = data.get("predictions", data) if isinstance(data, dict) else data
        today = data.get("date", str(date.today())) if isinstance(data, dict) else str(date.today())
        headline = data.get("headline", "Daily Oracle Signal") if isinstance(data, dict) else "Daily Oracle Signal"

        high_conf = [p for p in preds if int(p.get("confidence", p.get("confidence_score", 0))) >= 75]
        sorted_preds = sorted(preds, key=lambda x: int(x.get("confidence", x.get("confidence_score", 0))), reverse=True)

        out = [
            f"# OOTWOracle — {today}",
            f"**{headline}**",
            f"Predictions: {len(preds)} | High-confidence (≥75%): {len(high_conf)}\n",
            "**Top signals:**",
        ]
        for p in sorted_preds[:3]:
            conf = p.get("confidence", p.get("confidence_score", "?"))
            title = p.get("title", p.get("prediction", ""))
            out.append(f"- [{conf}%] {title}")
        out += [
            f"\nReport: {BASE_URL}/report/{today}",
            f"Debate: {BASE_URL}/oracle-chamber/{today}",
            f"Archive: {BASE_URL}/predictions.html",
        ]
        return "\n".join(out)
    except Exception as e:
        return f"Error: {e}"


if __name__ == "__main__":
    mcp.run()
