#!/usr/bin/env python3
"""
National Parks MCP Server
Use/Using美国国家公园管理局APIProvide公园Info/Information
"""

import json
import requests
import os
from fastmcp import FastMCP

# Create MCP server
mcp = FastMCP("US National Parks")

@mcp.tool()
def search_parks(query: str = None, state_code: str = None, limit: int = 50):
    """Search国家公园"""
    api_key = os.environ.get("NPS_API_KEY")
    if not api_key:
        return {"error": "Need to set NPS_API_KEY environment variable"}
    
    url = "https://developer.nps.gov/api/v1/parks"
    params = {
        "api_key": api_key,
        "limit": limit
    }
    
    if query:
        params["q"] = query
    if state_code:
        params["stateCode"] = state_code
    
    try:
        response = requests.get(url, params=params, timeout=10)
        data = response.json()
        
        if response.status_code == 200:
            parks = []
            for park in data.get("data", []):
                parks.append({
                    "id": park.get("id"),
                    "name": park.get("fullName"),
                    "park_code": park.get("parkCode"),
                    "description": park.get("description"),
                    "designation": park.get("designation"),
                    "states": park.get("states"),
                    "url": park.get("url"),
                    "weather_info": park.get("weatherInfo"),
                    "directions_info": park.get("directionsInfo"),
                    "operating_hours": park.get("operatingHours", [])
                })
            
            return {
                "parks": parks,
                "total": data.get("total", 0),
                "limit": limit
            }
        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_park_details(park_code: str):
    """Get/Fetch公园DetailedInfo/Information"""
    api_key = os.environ.get("NPS_API_KEY")
    if not api_key:
        return {"error": "Need to set NPS_API_KEY environment variable"}
    
    url = f"https://developer.nps.gov/api/v1/parks"
    params = {
        "api_key": api_key,
        "parkCode": park_code
    }
    
    try:
        response = requests.get(url, params=params, timeout=10)
        data = response.json()
        
        if response.status_code == 200 and data.get("data"):
            park = data["data"][0]
            return {
                "id": park.get("id"),
                "name": park.get("fullName"),
                "park_code": park.get("parkCode"),
                "description": park.get("description"),
                "designation": park.get("designation"),
                "states": park.get("states"),
                "latitude": park.get("latitude"),
                "longitude": park.get("longitude"),
                "acres": park.get("acres"),
                "url": park.get("url"),
                "weather_info": park.get("weatherInfo"),
                "directions_info": park.get("directionsInfo"),
                "operating_hours": park.get("operatingHours", []),
                "contacts": park.get("contacts", {}),
                "entrance_fees": park.get("entranceFees", []),
                "entrance_passes": park.get("entrancePasses", []),
                "images": [{"url": img.get("url"), "title": img.get("title")} for img in park.get("images", [])[:5]]
            }
        else:
            return {"error": f"Not found公园代码为 {park_code} 的公园"}
    except Exception as e:
        return {"error": f"Get/Fetch详情Failed: {str(e)}"}

@mcp.tool()
def get_park_activities(park_code: str = None, activity_id: str = None):
    """Get/Fetch公园活动Info/Information"""
    api_key = os.environ.get("NPS_API_KEY")
    if not api_key:
        return {"error": "Need to set NPS_API_KEY environment variable"}
    
    url = "https://developer.nps.gov/api/v1/activities"
    params = {
        "api_key": api_key
    }
    
    if park_code:
        params["parkCode"] = park_code
    if activity_id:
        params["id"] = activity_id
    
    try:
        response = requests.get(url, params=params, timeout=10)
        data = response.json()
        
        if response.status_code == 200:
            activities = []
            for activity in data.get("data", []):
                activities.append({
                    "id": activity.get("id"),
                    "name": activity.get("name"),
                    "parks": [{"name": park.get("fullName"), "code": park.get("parkCode")} 
                             for park in activity.get("parks", [])[:10]]
                })
            
            return {
                "activities": activities,
                "total": len(activities)
            }
        else:
            return {"error": f"API调用Failed: {data.get('message', 'Unknown error')}"}
    except Exception as e:
        return {"error": f"Get/Fetch活动Failed: {str(e)}"}

@mcp.tool()
def get_campgrounds(park_code: str = None, state_code: str = None, limit: int = 50):
    """Get/Fetch露营地Info/Information"""
    api_key = os.environ.get("NPS_API_KEY")
    if not api_key:
        return {"error": "Need to set NPS_API_KEY environment variable"}
    
    url = "https://developer.nps.gov/api/v1/campgrounds"
    params = {
        "api_key": api_key,
        "limit": limit
    }
    
    if park_code:
        params["parkCode"] = park_code
    if state_code:
        params["stateCode"] = state_code
    
    try:
        response = requests.get(url, params=params, timeout=10)
        data = response.json()
        
        if response.status_code == 200:
            campgrounds = []
            for camp in data.get("data", []):
                campgrounds.append({
                    "id": camp.get("id"),
                    "name": camp.get("name"),
                    "park_code": camp.get("parkCode"),
                    "description": camp.get("description"),
                    "latitude": camp.get("latitude"),
                    "longitude": camp.get("longitude"),
                    "reservations_description": camp.get("reservationsDescription"),
                    "reservations_url": camp.get("reservationsUrl"),
                    "regulations_overview": camp.get("regulationsOverview"),
                    "fees": camp.get("fees", []),
                    "number_of_sites": camp.get("numberOfSites", {})
                })
            
            return {
                "campgrounds": campgrounds,
                "total": data.get("total", 0),
                "limit": limit
            }
        else:
            return {"error": f"API调用Failed: {data.get('message', 'Unknown error')}"}
    except Exception as e:
        return {"error": f"Get/Fetch露营地Failed: {str(e)}"}

@mcp.tool()
def get_visitor_centers(park_code: str = None, state_code: str = None, limit: int = 50):
    """Get/Fetch游客中心Info/Information"""
    api_key = os.environ.get("NPS_API_KEY")
    if not api_key:
        return {"error": "Need to set NPS_API_KEY environment variable"}
    
    url = "https://developer.nps.gov/api/v1/visitorcenters"
    params = {
        "api_key": api_key,
        "limit": limit
    }
    
    if park_code:
        params["parkCode"] = park_code
    if state_code:
        params["stateCode"] = state_code
    
    try:
        response = requests.get(url, params=params, timeout=10)
        data = response.json()
        
        if response.status_code == 200:
            centers = []
            for center in data.get("data", []):
                centers.append({
                    "id": center.get("id"),
                    "name": center.get("name"),
                    "park_code": center.get("parkCode"),
                    "description": center.get("description"),
                    "latitude": center.get("latitude"),
                    "longitude": center.get("longitude"),
                    "directions_info": center.get("directionsInfo"),
                    "operating_hours": center.get("operatingHours", []),
                    "contacts": center.get("contacts", {})
                })
            
            return {
                "visitor_centers": centers,
                "total": data.get("total", 0),
                "limit": limit
            }
        else:
            return {"error": f"API调用Failed: {data.get('message', 'Unknown error')}"}
    except Exception as e:
        return {"error": f"Get/Fetch游客中心Failed: {str(e)}"}

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