import json
import requests
import os
import logging
from dotenv import load_dotenv
from fastmcp import FastMCP
mcp = FastMCP("Hello World")

# 设置logging
logger = logging.getLogger(__name__)

# 加载env文件
load_dotenv()

@mcp.tool()
def helloworld() -> str:
    """
    输入hello 或者 hello world
    返回helloworld
    """
    return "Hello World"
@mcp.tool()
def get_public_ip_address():
    """
    获取服务器公网 IP 地址
    根据IP所在的位置市一级地址再获取对应的天气信息
    返回: 
        str: 当前网络的公网 IP 地址
    """
    
    IP_API_URL = os.getenv("IP_API_URL")
    # 检查环境变量是否存在
    if not IP_API_URL:
        logger.error("Missing required environment variables for ip API.")
        return {"error": "Missing required environment variables."}
    
    try:
        logger.info("Getting public IP address URL: %s", IP_API_URL)
        response = requests.get(IP_API_URL) # type: ignore
        logger.info("Getting public IP address response: %s", response.json())
        response.raise_for_status()  # 检查 HTTP 请求是否成功
        return response.json() # 返回字典类型
    except requests.RequestException as e:
        print(f"请求错误: {e}")
        return "Request Failed"
    except json.JSONDecodeError as e:
        print(f"JSON 解码错误: {e}")
        return "Invalid Response"
    
@mcp.tool()
async def get_weather(city: str):
    """
    从 OpenWeather API 获取天气信息。
    :param city: 城市名称（需使用英文，如 Beijing）
    :return: 天气数据字典；若出错返回包含 error 信息的字典
    """
    OPENWEATHER_API_URL = os.getenv("OPENWEATHER_API_URL")
    OPENWEATHER_API_KEY = os.getenv("OPENWEATHER_API_KEY")
    USER_AGENT = "weather-app/1.0"

    # 检查环境变量是否存在
    if not OPENWEATHER_API_URL or not OPENWEATHER_API_KEY:
        logger.error("Missing required environment variables for OpenWeather API.")
        return {"error": "Missing required environment variables."}

    params = {
        "q": city,
        "appid": OPENWEATHER_API_KEY,
        "units": "metric",
        "lang": "zh_cn"
     }
    headers = {"User-Agent": USER_AGENT}

    logger.info("Getting weather apiurl %s", OPENWEATHER_API_URL)
    logger.info("Getting weather apikey %s", OPENWEATHER_API_KEY)
    logger.info("Getting weather params %s", params)
    logger.info("Getting weather headers %s", headers)
    response = requests.get(OPENWEATHER_API_URL, params=params, headers=headers)
    logger.info("Getting weather response %s", response.json())
    response.raise_for_status()
    return response.json() # 返回字典类型

def main():   
    log_level = os.environ.get("LOG_LEVEL", "INFO")
    logging.basicConfig(
        level=log_level.upper(),
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    )
    # mcp.run()
    mcp.run(transport = "streamable-http",
            host = "0.0.0.0", port = 9999, path = "/mcp")

if __name__ == "__main__":
    main()