import logging
import traceback
from importlib import import_module
from importlib.util import find_spec
from django.conf import settings
from django.contrib import admin
from django.urls import path, include, re_path
from django.conf.urls.static import static
from django.apps import apps
from .views import (
    manifest,
    offline,
    service_worker,
)
from .registry import ViewRegistry


AppsPage = ViewRegistry.get("lariv.AppsPage")
IndexRedirectView = ViewRegistry.get("lariv.IndexRedirectView")
ComingSoonPage = ViewRegistry.get("lariv.ComingSoon")
EnvironmentUpdateView = ViewRegistry.get("lariv.EnvironmentUpdateView")


logger = logging.getLogger(__name__)


def get_plugin_urls():
    paths = []
    for app_id in settings.ENABLED_APPS:
        try:
            url_prefix = getattr(apps.get_app_config(app_id), "url_prefix", None)
            if url_prefix is None:
                continue
            if find_spec(f"{app_id}.urls") is None:
                continue
            paths.append(
                path(
                    f"app/{url_prefix}/",
                    include((f"{app_id}.urls", url_prefix)),
                )
            )
            logger.info(f"Imported http paths from {app_id}")
        except Exception as e:
            logger.error("--------------------------------")
            logger.error(f"Error importing http paths from {app_id}: {e}")
            logger.error(traceback.format_exc())
            logger.error("--------------------------------")
            continue
    return paths


def get_plugin_websocket_urls():
    paths = []
    for app_id in settings.ENABLED_APPS:
        try:
            for path in import_module(app_id + ".urls").websocket_urlpatterns:
                paths.append(path)
            print(f"Imported websocket paths from {app_id}")
        except Exception:
            continue
    print("--------------------------------")
    return paths


environment_patterns = (
    [
        path("update/", EnvironmentUpdateView.as_view(), name="update"),
    ],
    "environment",
)

urlpatterns = (
    [
        re_path(
            r"^serviceworker\.js$",
            service_worker,
            name="serviceworker",
        ),
        re_path(r"^manifest\.json$", manifest, name="manifest"),
        path("offline/", offline, name="offline"),
        path(
            "",
            IndexRedirectView.as_view(),
        ),
        path("admin/", admin.site.urls),
        path("apps/", AppsPage.as_view(), name="apps"),
        path("coming-soon/", ComingSoonPage.as_view(), name="coming_soon"),
        path("environment/", include(environment_patterns)),
    ]
    + get_plugin_urls()
    + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
)

websocket_urlpatterns = get_plugin_websocket_urls()


if settings.DEBUG:
    # Include django_browser_reload URLs only in DEBUG mode
    urlpatterns += [
        path("__reload__/", include("django_browser_reload.urls")),
    ]
