import os
from typing import List

try:
    from config.modules import ENABLED_MODULES as DEFAULT_ENABLED
except Exception:
    DEFAULT_ENABLED = []


def get_enabled_modules() -> List[str]:
    """Return the list of enabled modules, allowing ENV override."""
    env = os.getenv('ENABLED_MODULES')
    if env:
        return [m.strip() for m in env.split(',') if m.strip()]
    return list(DEFAULT_ENABLED)


def is_module_enabled(name: str) -> bool:
    enabled = name in get_enabled_modules()
    if not enabled:
        return False

    # If featureflags app is available, allow feature flag to override module availability
    try:
        from apps.featureflags.services.feature_service import is_feature_enabled
        # flag name convention: enable_<module>
        flag_name = f'enable_{name}'
        # If feature flag exists and returns False, consider module disabled
        try:
            return is_feature_enabled(flag_name)
        except Exception:
            return enabled
    except Exception:
        return enabled


def list_available_modules() -> List[str]:
    # For now, return enabled modules as available set. Could be extended to scan apps/ directory.
    return get_enabled_modules()


def module_app_path(name: str) -> str:
    """Return the python package path for an app module based on grouping.

    Platform modules live under `apps.platform`, business modules under `apps.business`.
    """
    platform = {'accounts', 'core', 'notifications', 'audit', 'featureflags'}
    # include tenancy as a platform-level module
    platform.add('tenancy')
    business = {'geo', 'masterdata', 'payments'}
    if name in platform:
        return f'apps.platform.{name}'
    if name in business:
        return f'apps.business.{name}'
    # fallback
    return f'apps.{name}'
