import logging
from mcp import types

from . import utils
from ...consts import consts
from ...tools import tools
from ...config import config

logger = logging.getLogger(consts.LOGGER_NAME)

_OBJECT_URL_DESC = "The URL of the image. This can be a URL obtained via the GetObjectURL tool or a URL generated by other Fop tools. Length Constraints: Minimum length of 1."

_COMMON_DESC = """
The information includes the object_url of the scaled image, which users can directly use for HTTP GET requests to retrieve the image content or open in a browser to view the file.
The image must be stored in a Sufy Bucket.
Supported original image formats: psd, jpeg, png, gif, webp, tiff, bmp, avif, heic. Image width and height cannot exceed 30,000 pixels, and total pixels cannot exceed 150 million.
"""


class _ToolImpl:
    def __init__(self, cfg: config):
        self.config = cfg

    @tools.tool_meta(
        types.Tool(
            name="ImageScaleByPercent",
            description="""Image scaling tool that resizes images based on a percentage and returns information about the scaled image.
            """ + _COMMON_DESC,
            inputSchema={
                "type": "object",
                "properties": {
                    "object_url": {
                        "type": "string",
                        "description": _OBJECT_URL_DESC
                    },
                    "percent": {
                        "type": "integer",
                        "description": "Scaling percentage, range [1,999]. For example: 90 means the image width and height are reduced to 90% of the original; 200 means the width and height are enlarged to 200% of the original.",
                        "minimum": 1,
                        "maximum": 999
                    },
                },
                "required": ["object_url", "percent"],
            },
        )
    )
    async def image_scale_by_percent(
            self, **kwargs
    ) -> list[types.TextContent | types.ImageContent | types.EmbeddedResource]:
        object_url = kwargs.get("object_url", "")
        percent = kwargs.get("percent", "")
        func = f"imgmogr/thumbnail/!{percent}p"
        object_url = await utils.url_add_processing_func(self.config, object_url, func)
        return [
            types.TextContent(
                type="text",
                text=str(
                    {
                        "object_url": object_url,
                    }
                ),
            )
        ]

    @tools.tool_meta(
        types.Tool(
            name="ImageScaleBySize",
            description="""Image scaling tool that resizes images based on a specified width or height and returns information about the scaled image.
            """ + _COMMON_DESC,
            inputSchema={
                "type": "object",
                "properties": {
                    "object_url": {
                        "type": "string",
                        "description": _OBJECT_URL_DESC
                    },
                    "width": {
                        "type": "integer",
                        "description": "Specifies the width for image scaling. The image will be scaled to the specified width, and the height will be adjusted proportionally.",
                        "minimum": 1
                    },
                    "height": {
                        "type": "integer",
                        "description": "Specifies the height for image scaling. The image will be scaled to the specified height, and the width will be adjusted proportionally.",
                        "minimum": 1
                    },
                },
                "required": ["object_url"],
                "anyOf": [
                    {"required": ["width"]},
                    {"required": ["height"]}
                ]
            },
        )
    )
    async def image_scale_by_size(
            self, **kwargs
    ) -> list[types.TextContent]:
        object_url = kwargs.get("object_url", "")
        width = kwargs.get("width", "")
        height = kwargs.get("height", "")

        func = f"{width}x{height}"
        if len(func) == 1:
            return [
                types.TextContent(
                    type="text", text="At least one width or height must be set"
                )
            ]

        fop = f"imgmogr/thumbnail/{func}"
        object_url = await utils.url_add_processing_func(self.config, object_url, fop)
        return [
            types.TextContent(
                type="text",
                text=str(
                    {
                        "object_url": object_url,
                    }
                ),
            )
        ]

    @tools.tool_meta(
        types.Tool(
            name="ImageBlur",
            description="""Applies Gaussian blur to images. Important notes:
            1. Does NOT affect original GIF format images
            2. Takes effect after WebP-to-GIF conversion
            """ + _COMMON_DESC,
            inputSchema={
                "type": "object",
                "properties": {
                    "object_url": {
                        "type": "string",
                        "description": _OBJECT_URL_DESC,
                        "format": "uri"
                    },
                    "radius": {
                        "type": "integer",
                        "description": "Gaussian blur radius determining intensity (1-200)",
                        "minimum": 1,
                        "maximum": 200
                    },
                    "sigma": {
                        "type": "integer",
                        "description": "Standard deviation of normal distribution controlling smoothness (>0) ",
                        "minimum": 1
                    },
                },
                "required": ["object_url", "radius", "sigma"],
            }
        )
    )
    async def image_blur(self, **kwargs) -> list[types.TextContent]:
        object_url = kwargs.get("object_url", "")
        radius = kwargs.get("radius", "")
        sigma = kwargs.get("sigma", "")
        func = f"imgmogr/blur/{radius}x{sigma}"
        object_url = await utils.url_add_processing_func(self.config, object_url, func)
        return [
            types.TextContent(
                type="text",
                text=str({
                    "object_url": object_url,
                })
            )
        ]


def register_tools(cfg: config.Config):
    tool_impl = _ToolImpl(cfg)
    tools.auto_register_tools(
        [
            tool_impl.image_scale_by_percent,
            tool_impl.image_scale_by_size,
            tool_impl.image_blur,
        ]
    )
