"""Plugin system — dynamic tool loading from external Python files.

Plugins are Python files in ~/.tsumugi/plugins/ or ./tsumugi_plugins/.
Each plugin file should define a class that inherits from BaseTool.

Example plugin (~/.tsumugi/plugins/my_tool.py):

    from tsumugi.tools.base import BaseTool, PermissionLevel, ToolSpec

    class MyTool(BaseTool):
        def spec(self):
            return ToolSpec(
                name="my_tool",
                description="Does something useful",
                parameters={"type": "object", "properties": {}, "required": []},
                permission=PermissionLevel.READ,
            )

        def execute(self, **kwargs):
            return "Hello from my plugin!"
"""

from __future__ import annotations

import importlib.util
import sys
from pathlib import Path
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from tsumugi.tools import ToolRegistry

from tsumugi.tools.base import BaseTool

# Plugin directories
_GLOBAL_PLUGIN_DIR = Path.home() / ".tsumugi" / "plugins"
_LOCAL_PLUGIN_DIR = Path("tsumugi_plugins")


def _load_tools_from_file(filepath: Path) -> list[BaseTool]:
    """Load BaseTool subclasses from a Python file."""
    tools: list[BaseTool] = []
    module_name = f"tsumugi_plugin_{filepath.stem}"

    try:
        spec = importlib.util.spec_from_file_location(module_name, filepath)
        if spec is None or spec.loader is None:
            return tools

        module = importlib.util.module_from_spec(spec)
        sys.modules[module_name] = module
        spec.loader.exec_module(module)

        for attr_name in dir(module):
            attr = getattr(module, attr_name)
            if (
                isinstance(attr, type)
                and issubclass(attr, BaseTool)
                and attr is not BaseTool
            ):
                try:
                    tools.append(attr())
                except Exception:
                    pass

    except Exception:
        pass

    return tools


def load_plugins(registry: ToolRegistry) -> list[str]:
    """Discover and load plugins, registering tools into the registry.

    Returns list of loaded plugin names.
    """
    loaded: list[str] = []

    for plugin_dir in [_GLOBAL_PLUGIN_DIR, _LOCAL_PLUGIN_DIR.resolve()]:
        if not plugin_dir.is_dir():
            continue

        for filepath in sorted(plugin_dir.glob("*.py")):
            if filepath.name.startswith("_"):
                continue

            tools = _load_tools_from_file(filepath)
            for tool in tools:
                registry.register(tool)
                loaded.append(tool.spec().name)

    return loaded
