import subprocess

from apps.core.decorators import require_security_code
from django.http import JsonResponse
from django.views.decorators.http import require_GET

restart_flag = False


@require_GET
@require_security_code
def health_check(request):
    try:
        if restart_flag:
            # 检查uWSGI主进程是否存在
            result = subprocess.run(['pgrep', '-f', 'uwsgi.*master'],
                                    stdout=subprocess.PIPE)
            return JsonResponse(
                {
                    'status':
                    'ready' if result.returncode == 0 else 'restarting'
                },
                status=200)
        return JsonResponse({'status': 'ready'})
    except Exception as e:
        return JsonResponse({'status': 'error', 'message': str(e)}, status=500)


def trigger_restart():
    global restart_flag
    restart_flag = True
