import re
from functools import wraps

from django.http import JsonResponse

from .models.security_code import SecurityCode


def extract_security_code(request):
    """从请求中提取安全码（支持多种方式）"""
    # 1. 标准获取方式
    client_code = None
    if request.method == "POST":
        client_code = request.POST.get('code')
    elif request.method == "GET":
        client_code = request.GET.get('code')

    # 2. 检查请求头
    if not client_code:
        client_code = request.headers.get('X-Security-Code')

    # 3. 正则匹配备选方案
    if not client_code:
        full_path = request.get_full_path()
        # 匹配 code= 后面直到&或字符串结束的内容
        patterns = [
            r'code=([^&]+)',  # 基本匹配
            r'code=([^&\\s]*)',  # 允许空值
            r'[?&]code=([^&]+)'  # 确保code是参数名
        ]

        for pattern in patterns:
            code_match = re.search(pattern, full_path)
            if code_match:
                client_code = code_match.group(1)
                # print(f"使用模式 '{pattern}' 匹配到: {client_code}")
                break

    return client_code


def require_security_code(view_func):

    @wraps(view_func)
    def wrapper(request, *args, **kwargs):

        client_code = extract_security_code(request)

        if not client_code:
            return JsonResponse({'error': 'Security code required'},
                                status=400,
                                json_dumps_params={"ensure_ascii": False},
                                content_type="application/json; charset=utf-8")

        if client_code != SecurityCode.get_code():
            return JsonResponse({'error': 'Invalid security code'},
                                status=403,
                                json_dumps_params={"ensure_ascii": False},
                                content_type="application/json; charset=utf-8")

        return view_func(request, *args, **kwargs)

    return wrapper
