import os

from msgbus import MBEasyContext

from helper import import_pydevd
from mbcontextmessagehandler import (
    MbContextMessageBus,
    MbContextMessageHandler,
)
from externals.messagehandlerbuilder import AlertsMessageHandlerBuilder
from systools import sys_parsefilepath

from services.model import all_events
from externals.configurator import Configurator


def main():
    # type: (...) -> None

    loader_path = os.environ["LOADERCFG"]

    import_pydevd(loader_path=loader_path, port=9184)

    data_path = sys_parsefilepath("{HVDATADIR}")
    databases_path = os.path.join(data_path, "databases")
    backup_databases_path = os.path.join(data_path, "backups_alerts", "databases")

    configurator = Configurator(
        loader_path=loader_path,
        databases_path=databases_path,
        backup_databases_path=backup_databases_path,
    )
    configs = configurator.read_loader_configs()
    logger = configurator.get_loggers()

    mb_context = MBEasyContext(name="Alerts")
    message_bus = MbContextMessageBus(mbcontext=mb_context)

    message_handler_builder = AlertsMessageHandlerBuilder(
        configs=configs,
        message_bus=message_bus,
        mb_context=mb_context,
        logger=logger,
        input_logger=logger,
        callback_logger=logger,
    )
    message_handler = MbContextMessageHandler(
        message_bus=message_bus,
        service_name="Alerts",
        service_type="Alerts",
        required_services="",
        event_handler_builder=message_handler_builder,
    )

    message_handler.subscribe_reentrant_events(all_events())

    logger.info("Alerts started...")

    return message_handler.handle_events()
