"""
SetupGuardMiddleware
Redirects every request to /setup/ while setup is not yet complete,
except for the /setup/ URL itself (and static files).
"""
from pathlib import Path
from django.http import HttpResponseRedirect

SETUP_FLAG = Path(__file__).resolve().parent.parent / '.setup_complete'


class SetupGuardMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        path = request.path_info

        # Always allow static/media and the setup wizard itself
        if (path.startswith('/setup/')
            or path.startswith('/static/')
            or path.startswith('/media/')
            or path.startswith('/api/')):
            return self.get_response(request)

        # If setup not done, redirect everything else to the wizard
        if not SETUP_FLAG.exists():
            return HttpResponseRedirect('/setup/')

        return self.get_response(request)
