#!/usr/bin/env python3


from mcp.types import Tool, TextContent
from mcp.server.stdio import stdio_server
from mcp.server import Server
from typing import Any, Dict
from pathlib import Path
import sys
import logging
import json
import asyncio
import argparse


# 动态导入图片压缩功能模块（延迟导入以避免模块级别导入错误）
def _import_compress_functions():
    """动态导入图片压缩函数"""
    compress_image_pkg = Path(__file__).resolve(
    ).parent / "packages" / "compress_image"

    # 只在不存在时才添加到sys.path
    pkg_parent = str(compress_image_pkg.parent)
    if pkg_parent not in sys.path:
        sys.path.insert(0, pkg_parent)

    try:
        from compress_image.entry import (
            compress_image_lossless,
            compress_image_extreme,
            compress_image_force_lossless,
            compress_image_ultra,
            convert_to_webp,
            convert_to_avif,
        )
        return {
            "compress_image_lossless": compress_image_lossless,
            "compress_image_extreme": compress_image_extreme,
            "compress_image_force_lossless": compress_image_force_lossless,
            "compress_image_ultra": compress_image_ultra,
            "convert_to_webp": convert_to_webp,
            "convert_to_avif": convert_to_avif,
        }
    except ImportError as e:
        logger.error(f"无法导入图片压缩模块: {str(e)}")
        raise


# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)


# 创建MCP服务器实例
app = Server("acg-frontend-mcp-server")


@app.list_tools()
async def list_tools() -> list[Tool]:
    """列出所有可用的工具"""
    return [
        Tool(
            name="compress_images",
            description=(
                "批量压缩图片，支持多种压缩类型和格式转换。"
                "支持的压缩类型：image_lossless（通用图片无损压缩）、"
                "image_extreme（通用图片极度压缩）、"
                "image_force_lossless（通用图片强制无损压缩）、"
                "image_ultra（通用图片超强压缩）、"
                "webp（转换为WebP格式）、"
                "avif（转换为AVIF格式）。"
                "支持的输入格式：PNG, JPG, JPEG, BMP, TIFF, GIF。"
            ),
            inputSchema={
                "type": "object",
                "properties": {
                    "input_dir": {
                        "type": "string",
                        "description": "包含图片文件的输入目录路径"
                    },
                    "output_dir": {
                        "type": "string",
                        "description": "压缩后图片的输出目录路径"
                    },
                    "compression_type": {
                        "type": "string",
                        "description": "压缩类型: image_lossless, image_extreme, image_force_lossless, image_ultra, webp, avif",
                        "enum": ["image_lossless", "image_extreme", "image_force_lossless", "image_ultra", "webp", "avif"]
                    },
                    "max_size_kb": {
                        "type": "integer",
                        "description": "目标最大文件大小(KB)，默认50",
                        "default": 50
                    },
                    "quality": {
                        "type": "integer",
                        "description": "WebP/AVIF质量 (0-100)，默认80",
                        "default": 80,
                        "minimum": 0,
                        "maximum": 100
                    },
                    "keep_original_size": {
                        "type": "boolean",
                        "description": "是否保持原始尺寸，默认False",
                        "default": False
                    },
                    "optimize": {
                        "type": "boolean",
                        "description": "是否启用优化，默认True",
                        "default": True
                    },
                    "method": {
                        "type": "integer",
                        "description": "压缩方法 (0-6)，默认6（最强压缩）",
                        "default": 6,
                        "minimum": 0,
                        "maximum": 6
                    }
                },
                "required": ["input_dir", "output_dir", "compression_type"]
            }
        )
    ]


@app.call_tool()
async def call_tool(name: str, arguments: Dict[str, Any]) -> list[TextContent]:
    """处理工具调用"""

    try:
        if name == "compress_images":
            logger.info(f"调用 compress_images，参数: {arguments}")

            # 验证必需参数
            if "input_dir" not in arguments:
                return [TextContent(
                    type="text",
                    text="错误：缺少必需参数 'input_dir'"
                )]
            if "output_dir" not in arguments:
                return [TextContent(
                    type="text",
                    text="错误：缺少必需参数 'output_dir'"
                )]
            if "compression_type" not in arguments:
                return [TextContent(
                    type="text",
                    text="错误：缺少必需参数 'compression_type'"
                )]

            input_dir = Path(arguments["input_dir"])
            output_dir = Path(arguments["output_dir"])
            compression_type = arguments["compression_type"]

            # 验证输入目录存在
            if not input_dir.exists() or not input_dir.is_dir():
                return [TextContent(
                    type="text",
                    text=f"错误：输入目录不存在或不是目录: {input_dir}"
                )]

            # 获取可选参数
            max_size_kb = arguments.get("max_size_kb", 50)
            quality = arguments.get("quality", 80)
            keep_original_size = arguments.get("keep_original_size", False)
            optimize = arguments.get("optimize", True)
            method = arguments.get("method", 6)

            try:
                # 动态导入图片压缩函数
                compress_funcs = _import_compress_functions()

                # 根据压缩类型进行压缩
                if compression_type == "image_lossless":
                    success = compress_funcs["compress_image_lossless"](
                        str(input_dir), str(output_dir), max_size_kb=max_size_kb
                    )
                elif compression_type == "image_extreme":
                    success = compress_funcs["compress_image_extreme"](
                        str(input_dir),
                        str(output_dir),
                        max_size_kb=max_size_kb,
                        keep_original_size=keep_original_size,
                    )
                elif compression_type == "image_force_lossless":
                    success = compress_funcs["compress_image_force_lossless"](
                        str(input_dir), str(output_dir)
                    )
                elif compression_type == "image_ultra":
                    success = compress_funcs["compress_image_ultra"](
                        str(input_dir),
                        str(output_dir),
                        max_size_kb=max_size_kb,
                        lossless=(quality >= 95),
                        keep_original_size=keep_original_size,
                    )
                elif compression_type == "webp":
                    compress_funcs["convert_to_webp"](
                        str(input_dir),
                        str(output_dir),
                        quality=quality,
                        optimize=optimize,
                        method=method,
                    )
                    success = True
                elif compression_type == "avif":
                    compress_funcs["convert_to_avif"](
                        str(input_dir), str(output_dir))
                    success = True
                else:
                    return [TextContent(
                        type="text",
                        text=f"错误：不支持的压缩类型 '{compression_type}'"
                    )]

                if success:
                    result = {
                        "status": "success",
                        "message": f"图片压缩完成：{compression_type}",
                        "input_dir": str(input_dir),
                        "output_dir": str(output_dir),
                        "compression_type": compression_type,
                        "parameters": {
                            "max_size_kb": max_size_kb,
                            "quality": quality,
                            "keep_original_size": keep_original_size,
                            "optimize": optimize,
                            "method": method,
                        }
                    }
                    return [TextContent(
                        type="text",
                        text=json.dumps(result, ensure_ascii=False, indent=2)
                    )]
                else:
                    return [TextContent(
                        type="text",
                        text="错误：图片压缩失败，请检查输入目录是否包含支持的图片文件"
                    )]

            except Exception as e:
                logger.error(f"图片压缩过程中发生错误: {str(e)}", exc_info=True)
                return [TextContent(
                    type="text",
                    text=f"错误：图片压缩失败: {str(e)}"
                )]

        else:
            return [TextContent(
                type="text",
                text=f"未知的工具: {name}"
            )]

    except Exception as e:
        logger.error(f"调用工具 {name} 时发生错误: {str(e)}", exc_info=True)
        return [TextContent(
            type="text",
            text=f"调用工具时发生错误: {str(e)}"
        )]


async def async_main():
    """启动MCP服务器（异步版本）"""

    # 解析命令行参数
    parser = argparse.ArgumentParser(description='Frontend MCP Server')
    # parser.add_argument(
    #     '--access-token',
    #     type=str,
    #     required=False,
    #     help='GitLab Access Token (Personal Access Token，可选)'
    # )
    args = parser.parse_args()
    logger.info("正在启动 MCP Server... for acg-frontend-mcp")
    logger.info(f"命令行参数: {args}")

    # 使用stdio传输层运行服务器
    async with stdio_server() as (read_stream, write_stream):
        await app.run(
            read_stream,
            write_stream,
            app.create_initialization_options()
        )


def main():
    """同步入口函数，供 project.scripts 调用"""
    try:
        asyncio.run(async_main())
    except KeyboardInterrupt:
        logger.info("服务器已停止")
    except Exception as e:
        logger.error(f"服务器运行时发生错误: {str(e)}", exc_info=True)


if __name__ == "__main__":
    main()
