"""Gestor de descubrimiento y registro de plugins."""


if __package__ in {None, ""}:  # pragma: no cover - permite ejecución como script
    import sys
    from pathlib import Path

    _current_file = Path(__file__).resolve()
    for _parent in (_current_file.parent, *_current_file.parents):
        if (_parent / "pyproject.toml").exists() or (_parent / ".git").exists():
            _project_root = _parent
            break
    else:
        _project_root = _current_file.parents[2]
    _src_root = _project_root / "src"
    for _path in (_project_root, _src_root):
        _path_str = str(_path)
        if _path_str not in sys.path:
            sys.path.insert(0, _path_str)
    from agix._script_utils import bootstrap_script_environment

    bootstrap_script_environment("__main__", str(_current_file))

from importlib import metadata
from typing import Dict, Iterable

from .base import StrategyPlugin


class PluginManager:
    """Carga plugins registrados bajo el grupo ``agix.strategies``."""

    def __init__(self) -> None:
        self.plugins: Dict[str, StrategyPlugin] = {}

    def register(self, plugin: StrategyPlugin) -> None:
        """Registra un plugin disponible."""
        self.plugins[plugin.name()] = plugin

    def discover(self) -> None:
        """Descubre e instancia plugins a través de entry points."""
        eps: Iterable[metadata.EntryPoint] = metadata.entry_points(group="agix.strategies")
        for ep in eps:
            plugin_cls = ep.load()
            plugin = plugin_cls()
            self.register(plugin)

    def get(self, name: str) -> StrategyPlugin:
        """Obtiene un plugin por nombre."""
        return self.plugins[name]

    def apply_all(self, data) -> None:
        """Ejecuta ``apply`` sobre todos los plugins registrados."""
        for plugin in self.plugins.values():
            plugin.apply(data)
