import os
import importlib
import pkgutil
import sys
from django.conf.urls import url, include


def load_urls(relative, namespaced=True):
    relative = os.path.dirname(relative)
    base = None
    for p in sys.path:
        if relative.startswith(p):
            base = p

    if base is None:
        raise Exception('%s is not in sys.path (%s)' % (relative, sys.path))

    prefix = relative.replace(base, '').replace('/', '.')
    if prefix.startswith('.'):
        prefix = prefix[1:]
    if prefix:
        prefix = prefix + '.'

    urlpatterns = []
    for _, name, package in pkgutil.iter_modules([relative]):
        if package:
            module_name = '%s%s.urls' % (prefix, name)
            try:
                urls = importlib.import_module(module_name)
            except ImportError:
                continue

            patterns = getattr(urls, 'urlpatterns', None)
            if patterns:
                if namespaced:
                    urlpatterns.append(
                        url('%s/' % name, include(patterns))
                    )
                else:
                    urlpatterns.extend(patterns)

    return urlpatterns
