from importlib.util import find_spec

from zayt.conf.settings import Settings
from zayt.di.container import Container
from zayt.web.lifecycle.decorator import startup

from .service import make_engine_service


@startup
def init(container: Container, settings: Settings):
    if find_spec("sqlalchemy") is None:
        raise ModuleNotFoundError(
            "Missing 'sqlalchemy'. Install 'zayt' with 'sqlalchemy' extra."
        )

    for name in settings.sqlalchemy.connections:
        assert isinstance(name, str)
        name = name.strip()
        container.register(make_engine_service(name), name=name if name else None)
