"""Event listeners registration module"""

import logging
import importlib
from pathlib import Path
from src.events.library import ALL_EVENTS

logger = logging.getLogger(__name__)

# Base directory for apps
APPS_DIR = Path(__file__).parent.parent / "apps"


def discover_listener_modules() -> list[str]:
    """
    Automatically discover all listener.py modules in the src/apps directory.
    
    Returns:
        List of module paths in dot notation (e.g., ['src.apps.auth.listener'])
    """
    listener_modules = []
    
    if not APPS_DIR.exists():
        logger.warning(f"Apps directory not found: {APPS_DIR}")
        return listener_modules
    
    # Walk through all subdirectories in apps
    for listener_file in APPS_DIR.rglob("listener.py"):
        try:
            # Convert file path to module path
            # e.g., src/apps/auth/listener.py -> src.apps.auth.listener
            relative_path = listener_file.relative_to(APPS_DIR.parent.parent)
            module_path = str(relative_path.with_suffix("")).replace("/", ".").replace("\\", ".")
            
            # Verify it's a valid Python module (has __init__.py in parent)
            parent_dir = listener_file.parent
            if (parent_dir / "__init__.py").exists():
                listener_modules.append(module_path)
                logger.debug(f"Discovered listener module: {module_path}")
            else:
                logger.warning(f"Skipping {module_path} - parent directory missing __init__.py")
        except Exception as e:
            logger.error(f"Error processing listener file {listener_file}: {e}")
    
    return sorted(listener_modules)


async def register_all_listeners():
    """Register all event listeners - this function is called during app startup"""
    logger.info("Discovering and registering event listeners...")
    
    # Auto-discover listener modules
    listener_modules = discover_listener_modules()
    
    if not listener_modules:
        logger.warning("No listener modules discovered")
    else:
        logger.info(f"Discovered {len(listener_modules)} listener module(s): {', '.join(listener_modules)}")
    
    # Import all discovered listener modules
    from src.events.dispatcher import EventDispatcher
    
    # Import modules (synchronous but typically fast)
    # Decorators need to execute in the main thread to register listeners
    for module_path in listener_modules:
        try:
            importlib.import_module(module_path)
            logger.info(f"Successfully imported listener module: {module_path}")
        except ImportError as e:
            logger.error(f"Failed to import listener module {module_path}: {e}")
        except Exception as e:
            logger.error(f"Unexpected error importing listener module {module_path}: {e}")
    
    # Print listener counts for debugging
    if EventDispatcher:
        for event in ALL_EVENTS:
            event_id = event["event_id"]
            counts = EventDispatcher.get_listener_count(event_type=event_id)
            logger.debug("LISTENER COUNTS: %s %s", event_id, counts)
            if counts['sync_listeners'] > 0 or counts['async_listeners'] > 0:
                logger.info(f"{event_id}: {counts['sync_listeners']} sync, {counts['async_listeners']} async listeners")
    
    logger.info("Event listener registration completed")