import logging

from amsdal.contrib.app_config import AppConfig
from amsdal_server.apps.common.events.server import MiddlewareSetupEvent
from amsdal_server.apps.common.events.server import RouterSetupEvent
from amsdal_utils.events import listen_to

from amsdal_ml.mcp_server.mcp_oauth.event_listeners.server_setup import MCPMiddlewareSetupListener
from amsdal_ml.mcp_server.mcp_oauth.event_listeners.server_setup import MCPRouterSetupListener
from amsdal_ml.ml_config import ml_config

logger = logging.getLogger(__name__)


class MLPluginAppConfig(AppConfig):
    name = 'amsdal_ml'
    verbose_name = 'AMSDAL ML Plugin'

    def on_setup(self) -> None:
        listen_to(RouterSetupEvent)(MCPRouterSetupListener)
        listen_to(MiddlewareSetupEvent)(MCPMiddlewareSetupListener)

        if not ml_config.oauth_enabled:
            return None

        try:
            from amsdal_server.apps.common.events.auth import AuthenticateEvent
            from amsdal_utils.events import EventBus

            from amsdal_ml.mcp_server.mcp_oauth.event_listeners.auth_bridge_listener import (
                OAuthAuthenticateBridgeListener,
            )
        except ImportError:
            return None

        EventBus.subscribe(
            AuthenticateEvent,
            OAuthAuthenticateBridgeListener,
            before=['amsdal.contrib.auth.event_handlers.authenticate.AuthenticateUserListener'],
        )

        return None
