#!/usr/bin/env python3
"""
Sports Data MCP Server
Use/UsingESPNFreeAPIProvide体育Data
"""

import json
import requests
from datetime import datetime
from fastmcp import FastMCP

# Create MCP server
mcp = FastMCP("ESPN Sports Data")

# ESPN API基础URL
ESPN_BASE_URL = "https://site.api.espn.com/apis/site/v2/sports"

@mcp.tool()
def get_nfl_scores(week: int = None, year: int = None):
    """Get/FetchNFL比分"""
    if year is None:
        year = datetime.now().year
    
    url = f"{ESPN_BASE_URL}/football/nfl/scoreboard"
    params = {}
    
    if week:
        params["week"] = week
    if year:
        params["dates"] = year
    
    try:
        response = requests.get(url, params=params, timeout=10)
        data = response.json()
        
        games = []
        for event in data.get("events", []):
            game = {
                "id": event.get("id"),
                "name": event.get("name"),
                "short_name": event.get("shortName"),
                "date": event.get("date"),
                "status": event.get("status", {}).get("type", {}).get("description"),
                "week": event.get("week", {}).get("number"),
                "season_type": event.get("season", {}).get("type"),
                "teams": []
            }
            
            for competition in event.get("competitions", []):
                for competitor in competition.get("competitors", []):
                    team = competitor.get("team", {})
                    game["teams"].append({
                        "id": team.get("id"),
                        "name": team.get("displayName"),
                        "abbreviation": team.get("abbreviation"),
                        "score": competitor.get("score"),
                        "home_away": competitor.get("homeAway"),
                        "winner": competitor.get("winner", False),
                        "record": competitor.get("records", [{}])[0].get("summary", "") if competitor.get("records") else ""
                    })
            
            games.append(game)
        
        return {
            "league": "NFL",
            "games": games,
            "total_games": len(games)
        }
    except Exception as e:
        return {"error": f"Get/FetchNFL比分Failed: {str(e)}"}

@mcp.tool()
def get_nba_scores(date: str = None):
    """Get/FetchNBA比分"""
    url = f"{ESPN_BASE_URL}/basketball/nba/scoreboard"
    params = {}
    
    if date:
        params["dates"] = date.replace("-", "")
    
    try:
        response = requests.get(url, params=params, timeout=10)
        data = response.json()
        
        games = []
        for event in data.get("events", []):
            game = {
                "id": event.get("id"),
                "name": event.get("name"),
                "short_name": event.get("shortName"),
                "date": event.get("date"),
                "status": event.get("status", {}).get("type", {}).get("description"),
                "teams": []
            }
            
            for competition in event.get("competitions", []):
                for competitor in competition.get("competitors", []):
                    team = competitor.get("team", {})
                    game["teams"].append({
                        "id": team.get("id"),
                        "name": team.get("displayName"),
                        "abbreviation": team.get("abbreviation"),
                        "score": competitor.get("score"),
                        "home_away": competitor.get("homeAway"),
                        "winner": competitor.get("winner", False),
                        "record": competitor.get("records", [{}])[0].get("summary", "") if competitor.get("records") else ""
                    })
            
            games.append(game)
        
        return {
            "league": "NBA",
            "games": games,
            "total_games": len(games)
        }
    except Exception as e:
        return {"error": f"Get/FetchNBA比分Failed: {str(e)}"}

@mcp.tool()
def get_mlb_scores(date: str = None):
    """Get/FetchMLB比分"""
    url = f"{ESPN_BASE_URL}/baseball/mlb/scoreboard"
    params = {}
    
    if date:
        params["dates"] = date.replace("-", "")
    
    try:
        response = requests.get(url, params=params, timeout=10)
        data = response.json()
        
        games = []
        for event in data.get("events", []):
            game = {
                "id": event.get("id"),
                "name": event.get("name"),
                "short_name": event.get("shortName"),
                "date": event.get("date"),
                "status": event.get("status", {}).get("type", {}).get("description"),
                "teams": []
            }
            
            for competition in event.get("competitions", []):
                for competitor in competition.get("competitors", []):
                    team = competitor.get("team", {})
                    game["teams"].append({
                        "id": team.get("id"),
                        "name": team.get("displayName"),
                        "abbreviation": team.get("abbreviation"),
                        "score": competitor.get("score"),
                        "home_away": competitor.get("homeAway"),
                        "winner": competitor.get("winner", False),
                        "record": competitor.get("records", [{}])[0].get("summary", "") if competitor.get("records") else ""
                    })
            
            games.append(game)
        
        return {
            "league": "MLB",
            "games": games,
            "total_games": len(games)
        }
    except Exception as e:
        return {"error": f"Get/FetchMLB比分Failed: {str(e)}"}

@mcp.tool()
def get_soccer_scores(league: str = "eng.1", date: str = None):
    """Get/Fetch足球比分"""
    url = f"{ESPN_BASE_URL}/soccer/{league}/scoreboard"
    params = {}
    
    if date:
        params["dates"] = date.replace("-", "")
    
    try:
        response = requests.get(url, params=params, timeout=10)
        data = response.json()
        
        games = []
        for event in data.get("events", []):
            game = {
                "id": event.get("id"),
                "name": event.get("name"),
                "short_name": event.get("shortName"),
                "date": event.get("date"),
                "status": event.get("status", {}).get("type", {}).get("description"),
                "teams": []
            }
            
            for competition in event.get("competitions", []):
                for competitor in competition.get("competitors", []):
                    team = competitor.get("team", {})
                    game["teams"].append({
                        "id": team.get("id"),
                        "name": team.get("displayName"),
                        "abbreviation": team.get("abbreviation"),
                        "score": competitor.get("score"),
                        "home_away": competitor.get("homeAway"),
                        "winner": competitor.get("winner", False)
                    })
            
            games.append(game)
        
        return {
            "league": f"Soccer ({league})",
            "games": games,
            "total_games": len(games)
        }
    except Exception as e:
        return {"error": f"Get/Fetch足球比分Failed: {str(e)}"}

@mcp.tool()
def get_team_info(sport: str, league: str, team_id: str):
    """Get/Fetch球队Info/Information"""
    url = f"{ESPN_BASE_URL}/{sport}/{league}/teams/{team_id}"
    
    try:
        response = requests.get(url, timeout=10)
        data = response.json()
        
        team = data.get("team", {})
        
        return {
            "id": team.get("id"),
            "name": team.get("displayName"),
            "abbreviation": team.get("abbreviation"),
            "nickname": team.get("nickname"),
            "color": team.get("color"),
            "alternate_color": team.get("alternateColor"),
            "location": team.get("location"),
            "venue": team.get("venue", {}).get("fullName"),
            "founded": team.get("founded"),
            "record": team.get("record", {})
        }
    except Exception as e:
        return {"error": f"Get/Fetch球队Info/InformationFailed: {str(e)}"}

@mcp.tool()
def get_standings(sport: str, league: str):
    """Get/Fetch联盟排名"""
    url = f"{ESPN_BASE_URL}/{sport}/{league}/standings"
    
    try:
        response = requests.get(url, timeout=10)
        data = response.json()
        
        standings = []
        
        for group in data.get("children", []):
            division = {
                "name": group.get("name"),
                "abbreviation": group.get("abbreviation"),
                "teams": []
            }
            
            for standing in group.get("standings", {}).get("entries", []):
                team = standing.get("team", {})
                stats = standing.get("stats", [])
                
                team_stats = {}
                for stat in stats:
                    team_stats[stat.get("name", "")] = stat.get("displayValue", "")
                
                division["teams"].append({
                    "id": team.get("id"),
                    "name": team.get("displayName"),
                    "abbreviation": team.get("abbreviation"),
                    "stats": team_stats
                })
            
            standings.append(division)
        
        return {
            "league": f"{sport.upper()} {league.upper()}",
            "standings": standings
        }
    except Exception as e:
        return {"error": f"Get/Fetch排名Failed: {str(e)}"}

@mcp.tool()
def get_available_leagues():
    """Get/Fetch可用的联盟List"""
    return {
        "american_football": {
            "nfl": "National Football League",
            "college-football": "College Football"
        },
        "basketball": {
            "nba": "National Basketball Association",
            "wnba": "Women's National Basketball Association",
            "mens-college-basketball": "Men's College Basketball",
            "womens-college-basketball": "Women's College Basketball"
        },
        "baseball": {
            "mlb": "Major League Baseball",
            "college-baseball": "College Baseball"
        },
        "soccer": {
            "eng.1": "English Premier League",
            "esp.1": "Spanish La Liga",
            "ger.1": "German Bundesliga",
            "ita.1": "Italian Serie A",
            "fra.1": "French Ligue 1",
            "usa.1": "Major League Soccer",
            "uefa.champions": "UEFA Champions League"
        },
        "hockey": {
            "nhl": "National Hockey League"
        },
        "note": "Use/UsingESPNFreeAPI，无需API密钥"
    }

@mcp.tool()
def get_api_info():
    """Get/FetchESPN APIInfo/Information"""
    return {
        "service": "ESPN API",
        "description": "Free的体育DataAPI",
        "features": [
            "实时比分",
            "球队Info/Information",
            "联盟排名",
            "多种运动",
            "历史Data"
        ],
        "supported_sports": [
            "美式足球 (NFL, College)",
            "篮球 (NBA, WNBA, College)",
            "棒球 (MLB, College)",
            "足球 (多个联赛)",
            "冰球 (NHL)"
        ],
        "rate_limit": "无明确Limit",
        "note": "Free服务，无需API密钥",
        "documentation": "https://www.espn.com/apis/devcenter/",
        "data_freshness": "实时更新"
    }

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