# -*- coding: utf-8 -*-
# filename: image.py
# @Time    : 2025-01-20
# @Author  : Claude Code
# @Email   : noreply@anthropic.com
# @Software: PyCharm
"""Image file handler for file preview tool"""
import logging
from pathlib import Path

from PIL import Image

from tf_tools_mcp.tools.file_preview_tools.file_preview_constants import (
    get_prompt_template_for_file_type,
)
from tf_tools_mcp.tools.file_preview_tools.file_preview_types import FilePreviewOptions
from tf_tools_mcp.tools.file_preview_tools.handlers.base import (
    BaseFileHandler,
    format_file_size,
)

logger = logging.getLogger(__name__)


class ImageHandler(BaseFileHandler):
    """图片处理器"""

    # 支持的图片格式
    supported_extensions = {
        ".png",
        ".jpg",
        ".jpeg",
        ".webp",
        ".gif",
        ".bmp",
        ".tiff",
        ".tif",
        ".heic",
        ".heif",
    }
    supported_mime_types = {
        "image/png",
        "image/jpeg",
        "image/webp",
        "image/gif",
        "image/bmp",
        "image/tiff",
        "image/heic",
        "image/heif",
    }

    async def extract_metadata(self, file_path: str) -> dict:
        """提取图片元数据

        Args:
            file_path: 图片文件路径

        Returns:
            图片元数据字典
        """
        with Image.open(file_path) as img:
            return {
                "width": img.width,
                "height": img.height,
                "format": img.format or "unknown",
                "mode": img.mode,
            }

    async def generate_summary(self, file_path: str) -> str:
        """生成图片内容描述（图片格式强制调用 LLM）

        Args:
            file_path: 图片文件路径

        Returns:
            AI生成的图片分析内容（不包含文件基本信息）

        Raises:
            ValueError: 如果 API 返回空响应
        """
        # 导入 ImageUnderstandingTool（放在方法内部避免循环导入）
        from tf_tools_mcp.tools.file_preview_tools.image_understanding import (
            ImageUnderstandingTool,
        )

        # 图片格式强制调用 LLM
        # 自动选择 prompt 模板
        prompt_template = get_prompt_template_for_file_type("image")  # "describe"

        # 创建工具实例并调用，max_tokens=1000 确保有足够的输出空间
        tool = ImageUnderstandingTool(model="glm-4.6v-flashx", max_tokens=1000)
        result = tool.run(images=[file_path], prompt_template=prompt_template)

        # 检查 API 是否返回了空响应
        if not result.description or len(result.description.strip()) == 0:
            logger.error(f"GLM API returned empty response for image: {file_path}")
            raise ValueError(
                f"图片理解 API 返回空响应，请检查：\n"
                f"1. ZHIPUAI_API_KEY 是否正确配置\n"
                f"2. API 账户是否有足够余额\n"
                f"3. 图片文件是否有效: {file_path}\n"
                f"4. 网络连接是否正常"
            )

        # 只返回AI生成的描述内容，限制在 1000 字以内
        return result.description[:1000]
