#!/usr/bin/env python3
"""
Spoonacular MCP Server
Provide食谱和营养Data
"""

import json
import requests
import os
from fastmcp import FastMCP

# Create MCP server
mcp = FastMCP("Spoonacular Recipe & Nutrition")

@mcp.tool()
def search_recipes(query: str, number: int = 10, diet: str = None, intolerances: str = None):
    """Search食谱"""
    api_key = os.environ.get("SPOONACULAR_API_KEY")
    if not api_key:
        return {"error": "Need to set SPOONACULAR_API_KEY environment variable"}
    
    url = "https://api.spoonacular.com/recipes/complexSearch"
    params = {
        "apiKey": api_key,
        "query": query,
        "number": number,
        "addRecipeInformation": True,
        "fillIngredients": True
    }
    
    if diet:
        params["diet"] = diet
    if intolerances:
        params["intolerances"] = intolerances
    
    try:
        response = requests.get(url, params=params)
        data = response.json()
        
        recipes = []
        for recipe in data.get("results", []):
            recipes.append({
                "id": recipe.get("id"),
                "title": recipe.get("title"),
                "image": recipe.get("image"),
                "ready_in_minutes": recipe.get("readyInMinutes"),
                "servings": recipe.get("servings"),
                "summary": recipe.get("summary"),
                "source_url": recipe.get("sourceUrl"),
                "health_score": recipe.get("healthScore"),
                "price_per_serving": recipe.get("pricePerServing"),
                "vegetarian": recipe.get("vegetarian"),
                "vegan": recipe.get("vegan"),
                "gluten_free": recipe.get("glutenFree"),
                "dairy_free": recipe.get("dairyFree")
            })
        
        return {
            "recipes": recipes,
            "total_results": data.get("totalResults"),
            "number": number
        }
    except Exception as e:
        return {"error": f"API调用Failed: {str(e)}"}

@mcp.tool()
def get_recipe_details(recipe_id: int):
    """Get/Fetch食谱DetailedInfo/Information"""
    api_key = os.environ.get("SPOONACULAR_API_KEY")
    if not api_key:
        return {"error": "Need to set SPOONACULAR_API_KEY environment variable"}
    
    url = f"https://api.spoonacular.com/recipes/{recipe_id}/information"
    params = {
        "apiKey": api_key,
        "includeNutrition": True
    }
    
    try:
        response = requests.get(url, params=params)
        data = response.json()
        
        # 提取营养Info/Information
        nutrition = {}
        if "nutrition" in data:
            for nutrient in data["nutrition"].get("nutrients", []):
                nutrition[nutrient["name"]] = {
                    "amount": nutrient["amount"],
                    "unit": nutrient["unit"]
                }
        
        return {
            "id": data.get("id"),
            "title": data.get("title"),
            "image": data.get("image"),
            "ready_in_minutes": data.get("readyInMinutes"),
            "servings": data.get("servings"),
            "summary": data.get("summary"),
            "instructions": data.get("instructions"),
            "ingredients": [{"name": ing["name"], "amount": ing["amount"], "unit": ing["unit"]} 
                          for ing in data.get("extendedIngredients", [])],
            "nutrition": nutrition,
            "health_score": data.get("healthScore"),
            "price_per_serving": data.get("pricePerServing"),
            "cuisines": data.get("cuisines", []),
            "dish_types": data.get("dishTypes", []),
            "diets": data.get("diets", [])
        }
    except Exception as e:
        return {"error": f"API调用Failed: {str(e)}"}

@mcp.tool()
def get_random_recipes(number: int = 5, tags: str = None):
    """Get/Fetch随机食谱"""
    api_key = os.environ.get("SPOONACULAR_API_KEY")
    if not api_key:
        return {"error": "Need to set SPOONACULAR_API_KEY environment variable"}
    
    url = "https://api.spoonacular.com/recipes/random"
    params = {
        "apiKey": api_key,
        "number": number
    }
    
    if tags:
        params["tags"] = tags
    
    try:
        response = requests.get(url, params=params)
        data = response.json()
        
        recipes = []
        for recipe in data.get("recipes", []):
            recipes.append({
                "id": recipe.get("id"),
                "title": recipe.get("title"),
                "image": recipe.get("image"),
                "ready_in_minutes": recipe.get("readyInMinutes"),
                "servings": recipe.get("servings"),
                "summary": recipe.get("summary"),
                "source_url": recipe.get("sourceUrl"),
                "health_score": recipe.get("healthScore"),
                "vegetarian": recipe.get("vegetarian"),
                "vegan": recipe.get("vegan"),
                "cuisines": recipe.get("cuisines", []),
                "dish_types": recipe.get("dishTypes", [])
            })
        
        return {"recipes": recipes}
    except Exception as e:
        return {"error": f"API调用Failed: {str(e)}"}

@mcp.tool()
def analyze_nutrition(ingredients: str):
    """分析食材营养成分"""
    api_key = os.environ.get("SPOONACULAR_API_KEY")
    if not api_key:
        return {"error": "Need to set SPOONACULAR_API_KEY environment variable"}
    
    url = "https://api.spoonacular.com/recipes/parseIngredients"
    params = {
        "apiKey": api_key,
        "ingredientList": ingredients,
        "servings": 1,
        "includeNutrition": True
    }
    
    try:
        response = requests.post(url, data=params)
        data = response.json()
        
        result = []
        for ingredient in data:
            nutrition = {}
            if "nutrition" in ingredient:
                for nutrient in ingredient["nutrition"].get("nutrients", []):
                    nutrition[nutrient["name"]] = {
                        "amount": nutrient["amount"],
                        "unit": nutrient["unit"]
                    }
            
            result.append({
                "name": ingredient.get("name"),
                "original": ingredient.get("original"),
                "amount": ingredient.get("amount"),
                "unit": ingredient.get("unit"),
                "nutrition": nutrition
            })
        
        return {"ingredients": result}
    except Exception as e:
        return {"error": f"API调用Failed: {str(e)}"}

@mcp.tool()
def search_food_products(query: str, number: int = 10):
    """Search食品产品"""
    api_key = os.environ.get("SPOONACULAR_API_KEY")
    if not api_key:
        return {"error": "Need to set SPOONACULAR_API_KEY environment variable"}
    
    url = "https://api.spoonacular.com/food/products/search"
    params = {
        "apiKey": api_key,
        "query": query,
        "number": number
    }
    
    try:
        response = requests.get(url, params=params)
        data = response.json()
        
        products = []
        for product in data.get("products", []):
            products.append({
                "id": product.get("id"),
                "title": product.get("title"),
                "image": product.get("image"),
                "image_type": product.get("imageType"),
                "price": product.get("price"),
                "brand": product.get("brand")
            })
        
        return {
            "products": products,
            "total_products": data.get("totalProducts"),
            "number": number
        }
    except Exception as e:
        return {"error": f"API调用Failed: {str(e)}"}

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