"""
Belief Revision System - Domain Extensions

Auto-discovery and registration of domain-specific smoke test packs.

Convention:
- Any module in this package named *_smoke.py will be auto-discovered
- Modules may expose:
    (A) SMOKE_LEVELS: dict mapping level names to test functions
        - Levels: "smoke" (fast), "regression" (medium), "deep" (expensive)
        - Each function: (store, domain_id, world_label) -> (tests_run, failures, messages)
    (B) run() function - treated as level="smoke"
- Optional DOMAIN_ID attribute overrides inferred domain ID

This design keeps adding domains frictionless while enabling
cost-aware test selection.
"""
from __future__ import annotations

import importlib
import pkgutil
from types import ModuleType
from typing import Callable, Dict, List, Optional

from .registry import auto_register


def _infer_domain_id(mod_name: str) -> str:
    """Infer domain ID from module name by stripping _smoke suffix."""
    if mod_name.endswith("_smoke"):
        return mod_name[:-len("_smoke")]
    return mod_name


def _register_levels(module: ModuleType) -> None:
    """Register smoke test levels from a discovered module."""
    # Get domain ID (explicit or inferred)
    domain_id = getattr(module, "DOMAIN_ID", None)
    if not isinstance(domain_id, str) or not domain_id.strip():
        domain_id = _infer_domain_id(module.__name__.split(".")[-1])

    # Check for SMOKE_LEVELS dict
    smoke_levels = getattr(module, "SMOKE_LEVELS", None)
    if isinstance(smoke_levels, dict) and smoke_levels:
        for level, fn in smoke_levels.items():
            if callable(fn):
                auto_register(domain_id, module.__name__, fn, level=str(level))
        return

    # Fall back to single run() function
    run = getattr(module, "run", None)
    if callable(run):
        auto_register(domain_id, module.__name__, run, level="smoke")


def _autodiscover() -> None:
    """Auto-discover and register *_smoke.py modules in this package."""
    for m in pkgutil.iter_modules(__path__):  # type: ignore
        if not m.name.endswith("_smoke"):
            continue
        try:
            module = importlib.import_module(f"{__name__}.{m.name}")
            _register_levels(module)
        except ImportError as e:
            # Log but don't fail - allows partial domain support
            import warnings
            warnings.warn(f"Failed to import domain smoke module {m.name}: {e}")


# Run discovery on import
_autodiscover()
