import pkgutil
import importlib

from wurker.util import init_logger

# Initialize logger for debugging
logger = init_logger()

# Dictionary to hold dispatcher callbacks
callbacks = {}

# Use this module's own namespace and path, which load_plugins() has extended to include external plugins
_pkg_name = __name__
_pkg_path = __path__

# TODO
logger.log(f"HERE! {_pkg_name=}, {_pkg_path=}")

# Iterate over all modules in the dispatchers namespace path
for finder, name, ispkg in pkgutil.iter_modules(_pkg_path):
    # Only consider modules following the cb_<slug> naming convention
    if not name.startswith("cb_"):
        continue

    module_name = f"{_pkg_name}.{name}"
    try:
        # Dynamically import the dispatcher module from the merged __path__
        module = importlib.import_module(module_name)
        logger.log(f"Loaded dispatcher module: {module_name}", prefix="dispatchers.__init__", level="debug")
    except Exception as e:
        logger.log(f"Error importing dispatcher module: {module_name}: {e}",
                   prefix="dispatchers.__init__", level="error")
        raise

    # Verify that the module defines a 'callback' function
    if not hasattr(module, "callback"):
        raise Exception(f"Wurker Drone Dispatcher missing 'callback' function: {module_name!r}")

    # Register the callback under its slug (e.g., 'cb_my_dispatch')
    callbacks[name] = module.callback
