from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
import json
import requests

@csrf_exempt
def generate_path(request):
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            if 'points' not in data or not isinstance(data['points'], list) or len(data['points']) != 2:
                return JsonResponse({'error': 'Invalid input data. "points" must be an array of two objects with x and y.'}, status=400)

            response = requests.post(
                'http://localhost:82/generatePath',
                json=data
            )

            if response.status_code == 200:
                return JsonResponse(response.json(), safe=False)
            else:
                return JsonResponse({'error': 'Failed to generate path', 'details': response.text}, status=response.status_code)

        except json.JSONDecodeError:
            return JsonResponse({'error': 'Invalid JSON format'}, status=400)
        except Exception as e:
            return JsonResponse({'error': 'An unexpected error occurred', 'details': str(e)}, status=500)

    return JsonResponse({'error': 'Only POST method is allowed'}, status=405)
