import os
import aiofiles
from mcp.server.fastmcp import FastMCP
from dotenv import load_dotenv


load_dotenv()
mcp = FastMCP()
SAVE_FILE_DIR = os.getenv("SAVE_FILE_DIR")
if not os.path.exists(SAVE_FILE_DIR):
    os.makedirs(SAVE_FILE_DIR)


@mcp.tool()
async def save_file(file_path, content):
    """
    将{content}内容生成文件并保存到指定的路径下
    :param file_path: 文件名
    :param content: 文件内容
    :return: 如果status是success，则返回文件的完整路径；否则只返回error
    """
    try:
        async with aiofiles.open(os.path.join(SAVE_FILE_DIR, file_path), 'wb') as file:
            await file.write(content)
        return {
            "file_path": os.path.join(SAVE_FILE_DIR, file_path),
            "status": "success"
        }
    except Exception as e:
        print(e)
        return {
            "status": "failed"
        }

