from importlib.metadata import EntryPoint, entry_points
from typing import Any, cast

from home_agent.contracts.protocols import ProviderPlugin


def load_plugins(enabled: set[str] | None = None) -> list[ProviderPlugin]:
    discovered = entry_points(group="home_agent.providers")
    plugins: list[ProviderPlugin] = []
    for ep in discovered:
        plugin = _entry_point_to_plugin(ep)
        if enabled is not None and plugin.id not in enabled:
            continue
        plugins.append(plugin)
    return plugins


def _entry_point_to_plugin(ep: EntryPoint) -> ProviderPlugin:
    plugin_cls = cast("type[Any]", ep.load())
    plugin = plugin_cls()
    return cast("ProviderPlugin", plugin)
