from rest_framework import status, generics from rest_framework.response import Response from rest_framework.views import APIView from django.utils import timezone from .models import Prediction, User, UserPrediction from .serializers import PredictionSerializer, PredictionRequestSerializer from rest_framework.permissions import IsAuthenticated import requests from django.views.decorators.csrf import csrf_exempt from django.utils.decorators import method_decorator from rest_framework.permissions import AllowAny from .services.tawhiri import TawhiriClient def get_prediction_from_tawhiri(params): base_url = "https://fly.stratonautica.ru/api/v2" response = requests.get(base_url, params=params) if response.status_code == 200: return response.json() # получаем результат предсказания else: raise Exception(f"Tawhiri error: {response.status_code} {response.text}") class PredictionCreateView(APIView): permission_classes = [AllowAny] def post(self, request): serializer = PredictionRequestSerializer(data=request.data) if not serializer.is_valid(): return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) validated_data = serializer.validated_data try: prediction_result = TawhiriClient.get_prediction(validated_data) except requests.RequestException as e: print("❌ Tawhiri error:", str(e), e.response.text if e.response else "no response") return Response({"error": f"Tawhiri error: {str(e)}"}, status=status.HTTP_502_BAD_GATEWAY) prediction = Prediction.objects.create(result=prediction_result) UserPrediction.objects.create(user=request.user, prediction=prediction, created_at=timezone.now()) return Response({ "id": prediction.id, "created_at": prediction.created_at, "result": prediction_result }, status=status.HTTP_201_CREATED) class PredictionListView(APIView): def get(self, request): user_id = request.query_params.get('user_id') created_from = request.query_params.get('created_from') created_till = request.query_params.get('created_till') predictions = Prediction.objects.filter( id__in=UserPrediction.objects.filter(user_id=user_id).values_list('prediction_id'), created_at__gte=created_from, created_at__lte=created_till, deleted_at__isnull=True ) return Response(PredictionSerializer(predictions, many=True).data) class PredictionDeleteView(APIView): def delete(self, request, pk): try: prediction = Prediction.objects.get(pk=pk) prediction.deleted_at = timezone.now() prediction.save() return Response({"deleted": True}) except Prediction.DoesNotExist: return Response({"error": "Not found"}, status=404) #class PredictionCreateView(APIView): #permission_classes = [IsAuthenticated]