import functools
import logging
from urllib.parse import urlparse, parse_qs, urlencode, urlunparse

from mcp.shared.exceptions import McpError
from mcp.types import ErrorData

logger = logging.getLogger(__name__)

SENSITIVE_PARAMS = {"key", "token"}


def sanitize_url(url: str) -> str:
    """Remove valores sensíveis (key, token) de uma webhook URL, substituindo por '***'."""
    parsed = urlparse(url)
    params = parse_qs(parsed.query, keep_blank_values=True)
    sanitized_params = {
        k: ["***"] * len(v) if k in SENSITIVE_PARAMS else v
        for k, v in params.items()
    }
    sanitized_query = urlencode(sanitized_params, doseq=True)
    sanitized_query = sanitized_query.replace("%2A%2A%2A", "***")
    return urlunparse(parsed._replace(query=sanitized_query))

def handle_error(func):
    """Decorator que converte exceções em McpError com mensagens descritivas."""

    @functools.wraps(func)
    async def wrapper(*args, **kwargs):
        try:
            return await func(*args, **kwargs)
        except McpError:
            raise
        except ValueError as e:
            raise McpError(ErrorData(code=-1, message=str(e)))
        except Exception as e:
            logger.error("Erro interno: %s", e)
            raise McpError(ErrorData(code=-1, message="Erro interno do servidor"))

    return wrapper
