# -*- coding: utf-8 -*-
"""ToolRegistry source 追踪测试"""
import pytest
from abyss.tools.registry import ToolRegistry
from abyss.tools.base import Tool


class _EchoTool(Tool):
    def __init__(self, name):
        self._name = name

    @property
    def name(self) -> str:
        return self._name

    @property
    def description(self) -> str:
        return "test tool"

    @property
    def parameters(self) -> dict:
        return {"type": "object", "properties": {}}

    def execute(self, **kwargs) -> dict:
        return {"success": True}


class TestToolSourceTracking:
    """ToolRegistry source 追踪功能测试"""

    def test_register_with_source(self):
        reg = ToolRegistry()
        reg.register(_EchoTool("t1"), source="builtin")
        assert reg.get_source("t1") == "builtin"

    def test_list_by_source(self):
        reg = ToolRegistry()
        reg.register(_EchoTool("a"), source="builtin")
        reg.register(_EchoTool("b"), source="builtin")
        reg.register(_EchoTool("c"), source="mcp__server1")

        builtins = reg.list_by_source("builtin")
        assert builtins == ["a", "b"]
        assert reg.list_by_source("mcp__server1") == ["c"]

    def test_unregister_by_source(self):
        reg = ToolRegistry()
        reg.register(_EchoTool("a"), source="builtin")
        reg.register(_EchoTool("b"), source="mcp__s")
        reg.register(_EchoTool("c"), source="mcp__s")

        count = reg.unregister_by_source("mcp__s")
        assert count == 2
        assert "a" in reg
        assert "b" not in reg
        assert "c" not in reg
        assert reg.get_source("a") == "builtin"
        assert reg.get_source("b") is None

    def test_unregister_clears_source(self):
        reg = ToolRegistry()
        reg.register(_EchoTool("t1"), source="builtin")
        reg.unregister("t1")
        assert reg.get_source("t1") is None

    def test_register_builtins_sets_source(self):
        reg = ToolRegistry()
        reg.register_builtins()
        names = reg.list_names()
        assert len(names) == 7  # 7 built-in tools
        for name in names:
            assert reg.get_source(name) == "builtin"
