#!/usr/bin/env python3
"""
Public Holidays MCP Server
Use/UsingFree的公共假期APIProvide假期Info/Information
"""

import json
import requests
from datetime import datetime, timedelta
from fastmcp import FastMCP

# Create MCP server
mcp = FastMCP("Public Holidays")

@mcp.tool()
def get_holidays_by_country(country_code: str, year: int = None):
    """Get/Fetch指定国家的公共假期"""
    if year is None:
        year = datetime.now().year
    
    url = f"https://date.nager.at/api/v3/PublicHolidays/{year}/{country_code}"
    
    try:
        response = requests.get(url, timeout=10)
        
        if response.status_code == 200:
            holidays = response.json()
            
            result = []
            for holiday in holidays:
                result.append({
                    "date": holiday.get("date"),
                    "local_name": holiday.get("localName"),
                    "name": holiday.get("name"),
                    "country_code": holiday.get("countryCode"),
                    "fixed": holiday.get("fixed"),
                    "global": holiday.get("global"),
                    "launch_year": holiday.get("launchYear"),
                    "types": holiday.get("types", [])
                })
            
            return {
                "country_code": country_code,
                "year": year,
                "holidays": result,
                "total_holidays": len(result)
            }
        elif response.status_code == 404:
            return {"error": f"国家代码 '{country_code}' 不Support或年份 '{year}' 无Data"}
        else:
            return {"error": f"API调用Failed: HTTP {response.status_code}"}
    except Exception as e:
        return {"error": f"Get/Fetch假期Failed: {str(e)}"}

@mcp.tool()
def get_next_holidays(country_code: str, days_ahead: int = 30):
    """Get/Fetch未来指定天数内的假期"""
    today = datetime.now()
    current_year = today.year
    next_year = current_year + 1
    
    # Get/Fetch当年和下一年的假期
    holidays_current = get_holidays_by_country(country_code, current_year)
    holidays_next = get_holidays_by_country(country_code, next_year)
    
    if "error" in holidays_current:
        return holidays_current
    
    all_holidays = holidays_current.get("holidays", [])
    if "holidays" in holidays_next:
        all_holidays.extend(holidays_next["holidays"])
    
    # 筛选未来的假期
    future_holidays = []
    end_date = today + timedelta(days=days_ahead)
    
    for holiday in all_holidays:
        holiday_date = datetime.strptime(holiday["date"], "%Y-%m-%d")
        if today <= holiday_date <= end_date:
            days_until = (holiday_date - today).days
            holiday["days_until"] = days_until
            future_holidays.append(holiday)
    
    # 按日期排序
    future_holidays.sort(key=lambda x: x["date"])
    
    return {
        "country_code": country_code,
        "search_period": f"{days_ahead} days",
        "upcoming_holidays": future_holidays,
        "total_upcoming": len(future_holidays)
    }

@mcp.tool()
def check_if_holiday(country_code: str, date: str):
    """检查指定日期是否为假期"""
    try:
        check_date = datetime.strptime(date, "%Y-%m-%d")
        year = check_date.year
        
        holidays = get_holidays_by_country(country_code, year)
        
        if "error" in holidays:
            return holidays
        
        for holiday in holidays.get("holidays", []):
            if holiday["date"] == date:
                return {
                    "date": date,
                    "is_holiday": True,
                    "holiday_info": holiday
                }
        
        return {
            "date": date,
            "is_holiday": False,
            "country_code": country_code
        }
    except ValueError:
        return {"error": "日期格式Error，请Use/Using YYYY-MM-DD 格式"}
    except Exception as e:
        return {"error": f"检查Failed: {str(e)}"}

@mcp.tool()
def get_available_countries():
    """Get/FetchSupport的国家List"""
    url = "https://date.nager.at/api/v3/AvailableCountries"
    
    try:
        response = requests.get(url, timeout=10)
        
        if response.status_code == 200:
            countries = response.json()
            
            result = []
            for country in countries:
                result.append({
                    "country_code": country.get("countryCode"),
                    "name": country.get("name")
                })
            
            return {
                "countries": result,
                "total_countries": len(result)
            }
        else:
            return {"error": f"Get/Fetch国家ListFailed: HTTP {response.status_code}"}
    except Exception as e:
        return {"error": f"Get/Fetch国家ListFailed: {str(e)}"}

@mcp.tool()
def get_long_weekends(country_code: str, year: int = None):
    """Get/Fetch长周末（Include/Contains假期的周末）"""
    if year is None:
        year = datetime.now().year
    
    holidays = get_holidays_by_country(country_code, year)
    
    if "error" in holidays:
        return holidays
    
    long_weekends = []
    
    for holiday in holidays.get("holidays", []):
        holiday_date = datetime.strptime(holiday["date"], "%Y-%m-%d")
        weekday = holiday_date.weekday()  # 0=Monday, 6=Sunday
        
        # 检查是否形成长周末
        if weekday == 0:  # Monday
            weekend_start = holiday_date - timedelta(days=2)  # Saturday
            long_weekends.append({
                "start_date": weekend_start.strftime("%Y-%m-%d"),
                "end_date": holiday["date"],
                "days": 3,
                "holiday": holiday["name"],
                "type": "Monday holiday"
            })
        elif weekday == 4:  # Friday
            weekend_end = holiday_date + timedelta(days=2)  # Sunday
            long_weekends.append({
                "start_date": holiday["date"],
                "end_date": weekend_end.strftime("%Y-%m-%d"),
                "days": 3,
                "holiday": holiday["name"],
                "type": "Friday holiday"
            })
    
    return {
        "country_code": country_code,
        "year": year,
        "long_weekends": long_weekends,
        "total_long_weekends": len(long_weekends)
    }

@mcp.tool()
def get_holidays_by_month(country_code: str, year: int = None, month: int = None):
    """Get/Fetch指定月份的假期"""
    if year is None:
        year = datetime.now().year
    if month is None:
        month = datetime.now().month
    
    holidays = get_holidays_by_country(country_code, year)
    
    if "error" in holidays:
        return holidays
    
    month_holidays = []
    for holiday in holidays.get("holidays", []):
        holiday_date = datetime.strptime(holiday["date"], "%Y-%m-%d")
        if holiday_date.month == month:
            month_holidays.append(holiday)
    
    return {
        "country_code": country_code,
        "year": year,
        "month": month,
        "holidays": month_holidays,
        "total_holidays": len(month_holidays)
    }

@mcp.tool()
def compare_countries_holidays(country_codes: list, year: int = None):
    """比较多个国家的假期"""
    if year is None:
        year = datetime.now().year
    
    if len(country_codes) > 5:
        return {"error": "At mostSupport比较5个国家"}
    
    comparison = {}
    
    for country_code in country_codes:
        holidays = get_holidays_by_country(country_code, year)
        if "error" not in holidays:
            comparison[country_code] = {
                "total_holidays": holidays["total_holidays"],
                "holidays": holidays["holidays"]
            }
        else:
            comparison[country_code] = {"error": holidays["error"]}
    
    return {
        "year": year,
        "countries_comparison": comparison,
        "countries_count": len(country_codes)
    }

@mcp.tool()
def get_api_info():
    """Get/Fetch公共假期APIInfo/Information"""
    return {
        "service": "Nager.Date Public Holidays API",
        "description": "Free的全球公共假期API",
        "features": [
            "100+国家假期Data",
            "历史和未来假期",
            "假期Type分类",
            "长周末检测",
            "多国比较"
        ],
        "supported_countries": "100+个国家和地区",
        "data_sources": "官方政府来源",
        "rate_limit": "无明确Limit",
        "note": "Free服务，无需API密钥",
        "documentation": "https://date.nager.at/",
        "date_format": "YYYY-MM-DD",
        "country_code_format": "ISO 3166-1 alpha-2"
    }

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