from django.contrib import admin
from django.urls import path, re_path, include
from django.conf import settings
from django.conf.urls.static import static
from django.views.static import serve as static_serve
from django.http import FileResponse, Http404
import os
from urllib.parse import unquote


def serve_media(request, path):
    """Serve media files — works under Daphne/ASGI where static() does not."""
    # URL-decode the path (handles %20 for spaces, etc.)
    decoded_path = unquote(path)
    file_path = os.path.join(settings.MEDIA_ROOT, decoded_path)

    if os.path.isfile(file_path):
        return FileResponse(open(file_path, 'rb'))

    # Fallback: try the raw (non-decoded) path
    raw_path = os.path.join(settings.MEDIA_ROOT, path)
    if os.path.isfile(raw_path):
        return FileResponse(open(raw_path, 'rb'))

    print(f"[MEDIA 404] Requested: {path}")
    print(f"[MEDIA 404] Decoded:   {decoded_path}")
    print(f"[MEDIA 404] Full path: {file_path}")
    print(f"[MEDIA 404] Exists:    {os.path.exists(file_path)}")
    print(f"[MEDIA 404] Dir listing: {os.listdir(os.path.dirname(file_path)) if os.path.isdir(os.path.dirname(file_path)) else 'DIR NOT FOUND'}")
    raise Http404(f"Media file not found: {decoded_path}")


urlpatterns = [
    path('admin/', admin.site.urls),
    # Serve media files explicitly — needed because Daphne (ASGI) does not
    # honour the static() helper the way Django's runserver does.
    # Must be BEFORE the catch-all chat.urls include.
    re_path(r'^media/(?P<path>.*)$', serve_media),
    path('', include('chat.urls')),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

handler404 = 'chat.views.handler404'
handler500 = 'chat.views.handler500'
