#!/usr/bin/env python3
"""
GIPHY MCP Server
Use/UsingGIPHY APIProvideGIFSearch和管理功能
"""

import json
import requests
import os
from fastmcp import FastMCP

# Create MCP server
mcp = FastMCP("GIPHY GIF Search")

# GIPHY API密钥 - 优先从environment variable读取
GIPHY_API_KEY = os.environ.get("GIPHY_API_KEY", "dc6zaTOxFJmzC")  # 如果没有environment variable，Use/Using公共测试密钥

@mcp.tool()
def search_gifs(query: str, limit: int = 25, offset: int = 0, rating: str = "g"):
    """SearchGIF"""
    url = "https://api.giphy.com/v1/gifs/search"
    params = {
        "api_key": GIPHY_API_KEY,
        "q": query,
        "limit": min(limit, 50),  # LimitMaximum50
        "offset": offset,
        "rating": rating,
        "lang": "en"
    }
    
    try:
        response = requests.get(url, params=params, timeout=10)
        data = response.json()
        
        if response.status_code == 200:
            gifs = []
            for gif in data.get("data", []):
                gifs.append({
                    "id": gif.get("id"),
                    "title": gif.get("title"),
                    "url": gif.get("url"),
                    "embed_url": gif.get("embed_url"),
                    "images": {
                        "original": gif.get("images", {}).get("original", {}).get("url"),
                        "preview": gif.get("images", {}).get("preview_gif", {}).get("url"),
                        "fixed_height": gif.get("images", {}).get("fixed_height", {}).get("url"),
                        "fixed_width": gif.get("images", {}).get("fixed_width", {}).get("url")
                    },
                    "rating": gif.get("rating"),
                    "username": gif.get("username", ""),
                    "source": gif.get("source", ""),
                    "trending_datetime": gif.get("trending_datetime", "")
                })
            
            return {
                "gifs": gifs,
                "pagination": {
                    "total_count": data.get("pagination", {}).get("total_count", 0),
                    "count": data.get("pagination", {}).get("count", 0),
                    "offset": data.get("pagination", {}).get("offset", 0)
                },
                "query": query
            }
        else:
            return {"error": f"API调用Failed: {data.get('message', 'Unknown error')}"}
    except Exception as e:
        return {"error": f"SearchFailed: {str(e)}"}

@mcp.tool()
def get_trending_gifs(limit: int = 25, rating: str = "g"):
    """Get/FetchTrending/PopularGIF"""
    url = "https://api.giphy.com/v1/gifs/trending"
    params = {
        "api_key": GIPHY_API_KEY,
        "limit": min(limit, 50),
        "rating": rating
    }
    
    try:
        response = requests.get(url, params=params, timeout=10)
        data = response.json()
        
        if response.status_code == 200:
            gifs = []
            for gif in data.get("data", []):
                gifs.append({
                    "id": gif.get("id"),
                    "title": gif.get("title"),
                    "url": gif.get("url"),
                    "images": {
                        "original": gif.get("images", {}).get("original", {}).get("url"),
                        "preview": gif.get("images", {}).get("preview_gif", {}).get("url"),
                        "fixed_height": gif.get("images", {}).get("fixed_height", {}).get("url")
                    },
                    "rating": gif.get("rating"),
                    "trending_datetime": gif.get("trending_datetime", "")
                })
            
            return {
                "trending_gifs": gifs,
                "total": len(gifs)
            }
        else:
            return {"error": f"API调用Failed: {data.get('message', 'Unknown error')}"}
    except Exception as e:
        return {"error": f"Get/FetchTrending/PopularGIFFailed: {str(e)}"}

@mcp.tool()
def translate_to_gif(text: str, rating: str = "g"):
    """将文本翻译为GIF"""
    url = "https://api.giphy.com/v1/gifs/translate"
    params = {
        "api_key": GIPHY_API_KEY,
        "s": text,
        "rating": rating
    }
    
    try:
        response = requests.get(url, params=params, timeout=10)
        data = response.json()
        
        if response.status_code == 200 and data.get("data"):
            gif = data["data"]
            return {
                "text": text,
                "gif": {
                    "id": gif.get("id"),
                    "title": gif.get("title"),
                    "url": gif.get("url"),
                    "embed_url": gif.get("embed_url"),
                    "images": {
                        "original": gif.get("images", {}).get("original", {}).get("url"),
                        "preview": gif.get("images", {}).get("preview_gif", {}).get("url"),
                        "fixed_height": gif.get("images", {}).get("fixed_height", {}).get("url")
                    },
                    "rating": gif.get("rating")
                }
            }
        else:
            return {"error": f"无法为文本 '{text}' 找到合适的GIF"}
    except Exception as e:
        return {"error": f"翻译Failed: {str(e)}"}

@mcp.tool()
def get_random_gif(tag: str = None, rating: str = "g"):
    """Get/Fetch随机GIF"""
    url = "https://api.giphy.com/v1/gifs/random"
    params = {
        "api_key": GIPHY_API_KEY,
        "rating": rating
    }
    
    if tag:
        params["tag"] = tag
    
    try:
        response = requests.get(url, params=params, timeout=10)
        data = response.json()
        
        if response.status_code == 200 and data.get("data"):
            gif = data["data"]
            return {
                "random_gif": {
                    "id": gif.get("id"),
                    "title": gif.get("title"),
                    "url": gif.get("url"),
                    "images": {
                        "original": gif.get("images", {}).get("original", {}).get("url"),
                        "preview": gif.get("images", {}).get("preview_gif", {}).get("url"),
                        "fixed_height": gif.get("images", {}).get("fixed_height", {}).get("url")
                    },
                    "rating": gif.get("rating"),
                    "username": gif.get("username", "")
                },
                "tag": tag or "random"
            }
        else:
            return {"error": "无法Get/Fetch随机GIF"}
    except Exception as e:
        return {"error": f"Get/Fetch随机GIFFailed: {str(e)}"}

@mcp.tool()
def get_gif_by_id(gif_id: str):
    """根据IDGet/FetchGIFDetailedInfo/Information"""
    url = f"https://api.giphy.com/v1/gifs/{gif_id}"
    params = {
        "api_key": GIPHY_API_KEY
    }
    
    try:
        response = requests.get(url, params=params, timeout=10)
        data = response.json()
        
        if response.status_code == 200 and data.get("data"):
            gif = data["data"]
            return {
                "id": gif.get("id"),
                "title": gif.get("title"),
                "url": gif.get("url"),
                "embed_url": gif.get("embed_url"),
                "images": {
                    "original": gif.get("images", {}).get("original", {}),
                    "preview": gif.get("images", {}).get("preview_gif", {}),
                    "fixed_height": gif.get("images", {}).get("fixed_height", {}),
                    "fixed_width": gif.get("images", {}).get("fixed_width", {})
                },
                "rating": gif.get("rating"),
                "username": gif.get("username", ""),
                "source": gif.get("source", ""),
                "import_datetime": gif.get("import_datetime", ""),
                "trending_datetime": gif.get("trending_datetime", ""),
                "user": gif.get("user", {})
            }
        else:
            return {"error": f"Not foundID为 {gif_id} 的GIF"}
    except Exception as e:
        return {"error": f"Get/FetchGIFFailed: {str(e)}"}

@mcp.tool()
def search_stickers(query: str, limit: int = 25, offset: int = 0, rating: str = "g"):
    """Search贴纸"""
    url = "https://api.giphy.com/v1/stickers/search"
    params = {
        "api_key": GIPHY_API_KEY,
        "q": query,
        "limit": min(limit, 50),
        "offset": offset,
        "rating": rating,
        "lang": "en"
    }
    
    try:
        response = requests.get(url, params=params, timeout=10)
        data = response.json()
        
        if response.status_code == 200:
            stickers = []
            for sticker in data.get("data", []):
                stickers.append({
                    "id": sticker.get("id"),
                    "title": sticker.get("title"),
                    "url": sticker.get("url"),
                    "images": {
                        "original": sticker.get("images", {}).get("original", {}).get("url"),
                        "preview": sticker.get("images", {}).get("preview_gif", {}).get("url"),
                        "fixed_height": sticker.get("images", {}).get("fixed_height", {}).get("url")
                    },
                    "rating": sticker.get("rating")
                })
            
            return {
                "stickers": stickers,
                "pagination": {
                    "total_count": data.get("pagination", {}).get("total_count", 0),
                    "count": data.get("pagination", {}).get("count", 0),
                    "offset": data.get("pagination", {}).get("offset", 0)
                },
                "query": query
            }
        else:
            return {"error": f"Search贴纸Failed: {data.get('message', 'Unknown error')}"}
    except Exception as e:
        return {"error": f"Search贴纸Failed: {str(e)}"}

@mcp.tool()
def get_api_info():
    """Get/FetchGIPHY APIInfo/Information"""
    return {
        "service": "GIPHY API",
        "api_key": "Use/Using公共测试密钥",
        "rate_limit": "42次Request/小时 (公共密钥)",
        "features": [
            "GIFSearch",
            "Trending/PopularGIF",
            "随机GIF",
            "文本到GIF翻译",
            "贴纸Search",
            "GIFDetailedInfo/Information"
        ],
        "supported_ratings": ["y", "g", "pg", "pg-13", "r"],
        "image_formats": [
            "original - 原始尺寸",
            "fixed_height - 固定高度200px",
            "fixed_width - 固定宽度200px",
            "preview_gif - 预览版本"
        ],
        "note": "生产环境请申请专用API密钥",
        "documentation": "https://developers.giphy.com/docs/api"
    }

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