import inspect
from types import ModuleType

from zayt.di.container import Container
from zayt.di.decorator import ATTRIBUTE_DI_SERVICE
from zayt.util.package_scan import scan_packages


def _is_service(arg) -> bool:
    return (inspect.isfunction(arg) or inspect.isclass(arg)) and hasattr(
        arg, ATTRIBUTE_DI_SERVICE
    )


def discover_services(container: Container, *modules: str | ModuleType):
    for item in scan_packages(*modules, predicate=_is_service):
        service_info = getattr(item, ATTRIBUTE_DI_SERVICE, None)

        container.register(
            item,
            provides=service_info.provides,
            name=service_info.name,
            scoped=service_info.scoped,
        )
