#!/usr/bin/env python3
"""THE TEA — MCP server. Exposes the public Content API as MCP tools so any
MCP-compatible AI (Claude Desktop, Cowork, etc.) can answer questions about
Chinese tea in 72 languages.

Free tier needs no credentials (English). A paid key from tea.support unlocks 7 languages
(Pro) or all 72 (Expert / Lifetime) — pass it as THETEA_KEY.

Install:  pip install "mcp[cli]" httpx
Run:      python3 server.py         (stdio)
Claude Desktop config (claude_desktop_config.json):
  "mcpServers": {
    "thetea": {
      "command": "python3",
      "args": ["/abs/path/server.py"],
      "env": { "THETEA_KEY": "tt_your_paid_key" }   // optional
    }
  }
"""
import os, httpx
from mcp.server.fastmcp import FastMCP

API = os.environ.get("THETEA_API", "https://api.thetea.app")
KEY = os.environ.get("THETEA_KEY", "")           # paid key (tt_…) → unlocks languages by tier
_headers = {"user-agent": "thetea-mcp/1.0"}
if KEY:
    _headers["authorization"] = f"Bearer {KEY}"
mcp = FastMCP("thetea")
_client = httpx.Client(base_url=API, timeout=30, headers=_headers)

def _get(path, **params):
    r = _client.get(path, params={k: v for k, v in params.items() if v not in (None, "")})
    r.raise_for_status()
    return r.json()

@mcp.tool()
def search_tea(query: str, lang: str = "en", limit: int = 10) -> list:
    """Search Chinese teas by name in any script (Cyrillic, 汉字, pinyin, Latin).
    Returns matching teas with slug, name, type, coordinates."""
    return _get("/api/v2/search", q=query, lang=lang, limit=limit).get("items", [])

@mcp.tool()
def list_teas(tea_type: str = "", province: str = "", brew_temp_max: int = 0,
              altitude_min: int = 0, tag: str = "", lang: str = "en", limit: int = 30) -> dict:
    """Filter teas by type (green/white/yellow/oolong/red/dark/puer), province,
    max brewing temperature (°C), min altitude (m), or tag (e.g. ten-famous-teas)."""
    return _get("/api/v2/teas", tea_type=tea_type, province=province,
                brew_temp_max=brew_temp_max or None, altitude_min=altitude_min or None,
                tag=tag, lang=lang, limit=limit)

@mcp.tool()
def get_tea(slug: str, lang: str = "en") -> str:
    """Get a full tea profile (Markdown): classification, history, terroir, brewing,
    organoleptics, chemistry, recipes, tags. `slug` is toneless pinyin (e.g. biluochun)."""
    r = _client.get(f"/api/v2/tea/{slug}.md", params={"lang": lang}); r.raise_for_status()
    return r.text

@mcp.tool()
def get_field(slug: str, code: str, lang: str = "en") -> dict:
    """Get one specific field of a tea (e.g. code='water_temp', 'taste', 'origin',
    'cultivar', 'liquor_color', 'climate'). Fast, precise."""
    return _get(f"/api/v2/tea/{slug}/{lang}/field/{code}")

@mcp.tool()
def compare_teas(slugs: str, lang: str = "en") -> dict:
    """Compare 2–5 teas side by side on key fields. `slugs` is comma-separated
    (e.g. 'biluochun,xihu-longjing')."""
    return _get("/api/v2/compare", slugs=slugs, lang=lang)

@mcp.tool()
def random_tea(lang: str = "en") -> dict:
    """Get a random tea profile — useful for discovery / tea of the day."""
    return _get("/api/v2/random", lang=lang)

@mcp.tool()
def glossary(query: str = "", category: str = "", lang: str = "en", limit: int = 20) -> list:
    """Look up tea terminology in any language. category e.g. tasting, processing,
    chemical, botanical, terroir, brewing."""
    return _get("/api/v2/glossary", q=query, category=category, lang=lang, limit=limit).get("terms", [])

@mcp.tool()
def tea_map(lang: str = "en") -> dict:
    """Coordinates of all teas with known origin — for mapping/geography questions."""
    return _get("/api/v2/map", lang=lang)

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