

from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated
from authentication.authentication import CustomTokenAuthentication
import uuid
import os
from django.conf import settings
from django.http import JsonResponse
from rest_framework import status
from .models import OpenAIDiagnose
from .openai_dia import openai_diagnoser_asyna_wraper
from django.core.exceptions import ObjectDoesNotExist
import json

class MyProtectedUploadDiagnose(APIView):
    authentication_classes = [CustomTokenAuthentication]  # 使用自定义的 Token 认证
    permission_classes = [IsAuthenticated]  # 需要用户认证才能访问
    
    def post(self, request):
        user = request.user
        uuid_str = str(uuid.uuid4())
        save_file_path = os.path.join(settings.BASE_DIR, 'upload_file', user.username, uuid_str)
        
        os.makedirs(os.path.dirname(save_file_path), exist_ok=True)

        # 获取上传的文件
        uploaded_file = request.FILES.get('file')
        if not uploaded_file:
            return JsonResponse({"error": "No file uploaded."}, status=status.HTTP_400_BAD_REQUEST)

        # 保存文件
        try:
            with open(save_file_path, 'wb+') as destination:
                for chunk in uploaded_file.chunks():
                    destination.write(chunk)
        except:
            return JsonResponse({"error": "Error saving file."}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        
        obj = OpenAIDiagnose.objects.create(uuid=uuid_str, user=user, status='P')
        obj.save()
        user.subject_usage_count = user.subject_usage_count - 1 
        user.save()
        openai_diagnoser_asyna_wraper.delay(uuid_str, user.username, "")

        return JsonResponse({"message": "File uploaded successfully.", "uuid": uuid_str}, status=status.HTTP_200_OK)


class MyProtectedDiagnoseCheck(APIView):
    authentication_classes = [CustomTokenAuthentication]  # 使用自定义的 Token 认证
    permission_classes = [IsAuthenticated]  # 需要用户认证才能访问
      
    def post(self, request):
        user = request.user
        # 处理 POST 请求，更新用户的联系信息
        try:
            data = json.loads(request.body)
            uuid_str = data.get("uuid")
        except json.JSONDecodeError:
            return JsonResponse({"error": "Invalid JSON format"}, status=400)
        try:
            # print(uuid_str)
            obj = OpenAIDiagnose.objects.get(uuid=uuid_str, user=user)  # 只获取一个对象
            if obj.status == 'D':
                return JsonResponse({"status": "done"})
            else:
                return JsonResponse({"status": "processing"})
        except ObjectDoesNotExist:
            return JsonResponse({"error_code": "2004"}, status=404)