from __future__ import annotations

import logging
from collections.abc import Callable
from pathlib import Path

from yera.config.tool_config import ToolConfig
from yera.tools import tool_utils
from yera.tools.decorated_tool import DecoratedTool

logger = logging.getLogger(__name__)


def tool(security_rank: int, save: bool = False, cfg_path: Path | str | None = None):
    if not isinstance(security_rank, int) or security_rank < 0:
        raise ValueError("security_rank must be a non-negative integer")

    def decorator(func: Callable) -> DecoratedTool:
        tool_config: ToolConfig = tool_utils.extract_tool_config(
            func, security_rank=security_rank
        )

        wrapper = DecoratedTool(func, tool_config)

        if save:
            try:
                tool_utils.save_tool(
                    func, cfg_path=cfg_path, security_rank=security_rank
                )
            except Exception as e:
                logger.warning("Failed to save tool '%s': %s", func.__name__, e)

        return wrapper

    return decorator
