"""Bootstrap — register all plugins, adapters, and bridges with the loader.

Call ``register_all()`` at startup (e.g. from orchestrator.initialize)
to ensure every adapter is available via ``loader.get(name)``.

Auto-discovery (PSA2):
- Plugins: vastian.plugins.* — any subpackage with register()
- Bridges: vastian.bridges.content_bridge.* and vastian.bridges.giga_dev_bridge
  — any module with register(). New plugins/bridges: just add and drop in;
  no bootstrap edit needed.
Core code never imports plugins/bridges directly — it goes through loader.py.
"""

from __future__ import annotations

import importlib
import logging
import pkgutil

logger = logging.getLogger(__name__)

# Bridge package paths to scan (modules with register() are auto-discovered)
_BRIDGE_SCAN_PACKAGES = [
    "vastian.bridges.content_bridge",
    "vastian.bridges.giga_dev_bridge",
]


def register_all() -> list[str]:
    """Register every known plugin/adapter and return the list of names.

    Plugins: Auto-discovered from vastian.plugins.* (any subpackage with register()).
    Bridges: Auto-discovered from content_bridge.* and giga_dev_bridge.
    Adapters that fail to register (e.g. missing optional dependencies)
    are logged as warnings but do not crash the system.
    """
    _registered: list[str] = []

    # Auto-discover plugins from vastian.plugins
    try:
        import vastian.plugins as plugins_pkg

        for _importer, modname, _ in pkgutil.iter_modules(
            plugins_pkg.__path__, plugins_pkg.__name__ + "."
        ):
            _safe_register(modname.split(".")[-1], modname, _registered)
    except Exception as e:
        logger.warning("Plugin auto-discovery failed: %s", e)

    # Auto-discover bridges (package __init__ and submodules with register())
    for pkg_name in _BRIDGE_SCAN_PACKAGES:
        try:
            pkg = importlib.import_module(pkg_name)
            # Try package's own register first (e.g. giga_dev_bridge)
            _safe_register(pkg_name.split(".")[-1], pkg_name, _registered)
            path = getattr(pkg, "__path__", None)
            if path is not None:
                for _importer, modname, _ in pkgutil.iter_modules(path, pkg_name + "."):
                    _safe_register(modname.split(".")[-1], modname, _registered)
        except Exception as e:
            logger.warning("Bridge discovery failed for %s: %s", pkg_name, e)

    from vastian.loader import available as loader_available

    all_names = sorted(loader_available())
    logger.info("Bootstrap complete: %d adapters registered: %s", len(all_names), all_names)
    return all_names


def _safe_register(name: str, module_path: str, out: list[str]) -> None:
    """Import a module and call its register() function.

    On failure, logs a warning and continues (adapter is optional).
    """
    try:
        import importlib

        mod = importlib.import_module(module_path)
        reg_fn = getattr(mod, "register", None)
        if reg_fn is not None:
            reg_fn()
            out.append(name)
            logger.debug("Registered %s from %s", name, module_path)
        # else: package/container without register — expected when scanning
    except ImportError as e:
        logger.warning("Could not import %s (missing dependency?): %s", module_path, e)
    except Exception as e:
        logger.warning("Failed to register %s: %s", module_path, e)
