#!/usr/bin/env python3
"""
TMDB (The Movie Database) MCP Server
Provide电影和电视节目Data
"""

import json
import requests
import os
from fastmcp import FastMCP

# Create MCP server
mcp = FastMCP("TMDB Movie Database")

@mcp.tool()
def search_movies(query: str, page: int = 1):
    """Search电影"""
    api_key = os.environ.get("TMDB_API_KEY")
    if not api_key:
        return {"error": "Need to set TMDB_API_KEY environment variable"}
    
    url = f"https://api.themoviedb.org/3/search/movie"
    params = {
        "api_key": api_key,
        "query": query,
        "page": page,
        "language": "en-US"
    }
    
    try:
        response = requests.get(url, params=params)
        data = response.json()
        
        movies = []
        for movie in data.get("results", []):
            movies.append({
                "id": movie.get("id"),
                "title": movie.get("title"),
                "overview": movie.get("overview"),
                "release_date": movie.get("release_date"),
                "vote_average": movie.get("vote_average"),
                "poster_path": f"https://image.tmdb.org/t/p/w500{movie.get('poster_path')}" if movie.get('poster_path') else None
            })
        
        return {
            "movies": movies,
            "total_results": data.get("total_results"),
            "total_pages": data.get("total_pages"),
            "current_page": page
        }
    except Exception as e:
        return {"error": f"API调用Failed: {str(e)}"}

@mcp.tool()
def get_movie_details(movie_id: int):
    """Get/Fetch电影DetailedInfo/Information"""
    api_key = os.environ.get("TMDB_API_KEY")
    if not api_key:
        return {"error": "Need to set TMDB_API_KEY environment variable"}
    
    url = f"https://api.themoviedb.org/3/movie/{movie_id}"
    params = {
        "api_key": api_key,
        "language": "en-US",
        "append_to_response": "credits,videos"
    }
    
    try:
        response = requests.get(url, params=params)
        data = response.json()
        
        return {
            "id": data.get("id"),
            "title": data.get("title"),
            "overview": data.get("overview"),
            "release_date": data.get("release_date"),
            "runtime": data.get("runtime"),
            "genres": [genre["name"] for genre in data.get("genres", [])],
            "vote_average": data.get("vote_average"),
            "vote_count": data.get("vote_count"),
            "budget": data.get("budget"),
            "revenue": data.get("revenue"),
            "poster_path": f"https://image.tmdb.org/t/p/w500{data.get('poster_path')}" if data.get('poster_path') else None,
            "backdrop_path": f"https://image.tmdb.org/t/p/w1280{data.get('backdrop_path')}" if data.get('backdrop_path') else None,
            "cast": [{"name": actor["name"], "character": actor["character"]} for actor in data.get("credits", {}).get("cast", [])[:10]],
            "director": next((crew["name"] for crew in data.get("credits", {}).get("crew", []) if crew["job"] == "Director"), None)
        }
    except Exception as e:
        return {"error": f"API调用Failed: {str(e)}"}

@mcp.tool()
def search_tv_shows(query: str, page: int = 1):
    """Search电视节目"""
    api_key = os.environ.get("TMDB_API_KEY")
    if not api_key:
        return {"error": "Need to set TMDB_API_KEY environment variable"}
    
    url = f"https://api.themoviedb.org/3/search/tv"
    params = {
        "api_key": api_key,
        "query": query,
        "page": page,
        "language": "en-US"
    }
    
    try:
        response = requests.get(url, params=params)
        data = response.json()
        
        tv_shows = []
        for show in data.get("results", []):
            tv_shows.append({
                "id": show.get("id"),
                "name": show.get("name"),
                "overview": show.get("overview"),
                "first_air_date": show.get("first_air_date"),
                "vote_average": show.get("vote_average"),
                "poster_path": f"https://image.tmdb.org/t/p/w500{show.get('poster_path')}" if show.get('poster_path') else None
            })
        
        return {
            "tv_shows": tv_shows,
            "total_results": data.get("total_results"),
            "total_pages": data.get("total_pages"),
            "current_page": page
        }
    except Exception as e:
        return {"error": f"API调用Failed: {str(e)}"}

@mcp.tool()
def get_popular_movies(page: int = 1):
    """Get/FetchTrending/Popular电影"""
    api_key = os.environ.get("TMDB_API_KEY")
    if not api_key:
        return {"error": "Need to set TMDB_API_KEY environment variable"}
    
    url = f"https://api.themoviedb.org/3/movie/popular"
    params = {
        "api_key": api_key,
        "page": page,
        "language": "en-US"
    }
    
    try:
        response = requests.get(url, params=params)
        data = response.json()
        
        movies = []
        for movie in data.get("results", []):
            movies.append({
                "id": movie.get("id"),
                "title": movie.get("title"),
                "overview": movie.get("overview"),
                "release_date": movie.get("release_date"),
                "vote_average": movie.get("vote_average"),
                "poster_path": f"https://image.tmdb.org/t/p/w500{movie.get('poster_path')}" if movie.get('poster_path') else None
            })
        
        return {
            "movies": movies,
            "total_results": data.get("total_results"),
            "total_pages": data.get("total_pages"),
            "current_page": page
        }
    except Exception as e:
        return {"error": f"API调用Failed: {str(e)}"}

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