from io import StringIO
from django.http import JsonResponse
from django.core.management import call_command
from django.views.decorators.http import require_GET

from apps.core.decorators import require_security_code


@require_GET
@require_security_code
def collect_static(request):
    try:
        output = StringIO()
        # 调用命令，并添加 clear 和 interactive 参数
        call_command('collectstatic',
                     interactive=False,
                     clear=True,
                     stdout=output,
                     verbosity=2)
        output_str = output.getvalue()
        output.close()  # 良好实践：使用后关闭StringIO对象

        # 从输出中提取统计信息
        if "static files copied" in output_str:
            # 更健壮的提取逻辑，处理单复数形式
            import re
            match = re.search(r'(\d+)\s+static files? copied', output_str)
            if match:
                files_copied = match.group(1)
            else:
                files_copied = "一些"
            message = f"成功收集 {files_copied} 个静态文件（已清除旧文件）"
        else:
            message = "静态文件收集完成，无新文件需要复制（目标目录已被清空）"

        return JsonResponse({
            'status': 'success',
            'message': message,
            # 'details': output_str.splitlines()
        })
    except Exception as e:
        return JsonResponse({'status': 'error', 'message': str(e)}, status=500)
