import json
from typing import Optional, List, Any
import requests
from mcp.server.fastmcp import FastMCP

# Initialize FastMCP server
mcp = FastMCP("Anitabi_MCPserver")

API_BASE_URL = "https://api.anitabi.cn"

def _safe_execute(func, *args, **kwargs) -> str:
    """Helper to safely execute API calls and serialize complex objects to JSON strings."""
    try:
        result = func(*args, **kwargs)
        return json.dumps(result, indent=2, ensure_ascii=False)
    except requests.RequestException as e:
        return f"API Request Error: {str(e)}"
    except Exception as e:
        return f"Error: {str(e)}"

def fetch_lite_info(subject_id: int) -> dict:
    url = f"{API_BASE_URL}/bangumi/{subject_id}/lite"
    response = requests.get(url)
    response.raise_for_status()
    return response.json()

def fetch_detail_points(subject_id: int, have_image: Optional[bool] = None) -> list:
    url = f"{API_BASE_URL}/bangumi/{subject_id}/points/detail"
    params = {}
    if have_image:
        params["haveImage"] = "true"
    response = requests.get(url, params=params)
    response.raise_for_status()
    return response.json()

@mcp.tool()
def get_anime_lite_info(subject_id: int) -> str:
    """
    Fetches the lite information of an anime's pilgrimage landmarks based on its Bangumi subject ID.
    This includes basic info like Chinese and original titles, the main city of pilgrimage, cover image, and the first 10 iconic landmarks.
    
    Args:
        subject_id: The Bangumi subject ID of the anime (e.g., 115908 for Sound! Euphonium).
    """
    return _safe_execute(fetch_lite_info, subject_id)

@mcp.tool()
def get_anime_detail_points(subject_id: int, have_image: Optional[bool] = None) -> str:
    """
    Fetches the detailed landmark information of an anime based on its Bangumi subject ID.
    Can optionally filter to only return landmarks that have images.
    
    Args:
        subject_id: The Bangumi subject ID of the anime.
        have_image: Optional. Set to True to filter and only include landmarks with an image.
    """
    return _safe_execute(fetch_detail_points, subject_id, have_image)

@mcp.tool()
def get_map_url(subject_id: int) -> str:
    """
    Generates the Anitabi pilgrimage map URL for a specific anime based on its Bangumi subject ID.
    
    Args:
        subject_id: The Bangumi subject ID of the anime.
    """
    url = f"https://anitabi.cn/map?bangumiId={subject_id}"
    return json.dumps({"map_url": url}, indent=2)

def main():
    mcp.run()

if __name__ == "__main__":
    main()
