from mcp.server.fastmcp import FastMCP
import os
import requests

# 创建 FastMCP 实例
mcp = FastMCP("Visual2URL")

UPLOAD_URL = "http://192.168.2.236:5002/api/html/upload"
AUTHORIZATION = "Bearer eyJhbGciOiJIUzUxMiJ9.eyJ0b2tlbl90eXBlIjoiTE9HSU4iLCJsb2dpbl91c2VyX2tleSI6IjM3OTAzNGIwLTg3OTQtNGU2OS05MzRiLTJkNTA3ZWIzODQyOCJ9.X5O0zez0_zm4Ejc9wTyj04Sf3GLT2L9ilIE6W0qbSgggdTvKcaboVm-A64U3SPxC8rpB1Gxc5p-XK7FXqAjgEg"

@mcp.tool()
def html_file_to_url(file_path: str) -> str:
    """
    将本地 HTML 文件上传至服务器并转换成可在浏览器中打开的 URL。
    
    Args:
        file_path: 本地 HTML 文件的绝对路径
    """
    if not os.path.exists(file_path):
        return f"Error: 文件不存在: {file_path}"
    
    headers = {
        'Authorization': AUTHORIZATION,
        'User-Agent': 'Apifox/1.0.0 (https://apifox.com)'
    }
    
    try:
        with open(file_path, 'rb') as f:
            files = {
                'file': (os.path.basename(file_path), f, 'text/html')
            }
            response = requests.post(UPLOAD_URL, headers=headers, files=files)
            response.raise_for_status()
            data = response.json()
            if data.get('code') == 200 and 'data' in data and 'fileUrl' in data['data']:
                return data['data']['fileUrl']
            else:
                return f"上传失败: {data.get('msg', '未知错误')}"
    except Exception as e:
        return f"请求发生异常: {str(e)}"

@mcp.tool()
def html_code_to_url(html_code: str) -> str:
    """
    将 HTML 代码片段上传至服务器并转换成可在浏览器中打开的 URL。
    
    Args:
        html_code: HTML 代码字符串
    """
    headers = {
        'Authorization': AUTHORIZATION,
        'User-Agent': 'Apifox/1.0.0 (https://apifox.com)',
        'Content-Type': 'text/html'
    }
    
    try:
        response = requests.post(UPLOAD_URL, headers=headers, data=html_code.encode('utf-8'))
        response.raise_for_status()
        data = response.json()
        if data.get('code') == 200 and 'data' in data and 'fileUrl' in data['data']:
            return data['data']['fileUrl']
        else:
            return f"上传失败: {data.get('msg', '未知错误')}"
    except Exception as e:
        return f"请求发生异常: {str(e)}"

def main():
    # 运行 MCP Server
    mcp.run()

if __name__ == "__main__":
    main()
