import json
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from .services import chat_with_artemis

@csrf_exempt # À sécuriser avec le token CSRF en prod
@require_POST
def chat_api(request):
    try:
        data = json.loads(request.body)
        user_message = data.get('message', '').strip()
        history = data.get('history', []) # Liste d'objets {sender: 'user', text: '...'}
        
        if not user_message:
            return JsonResponse({'error': 'Message vide'}, status=400)
            
        # Appel au service
        response_text = chat_with_artemis(user_message, history)
        
        return JsonResponse({'response': response_text})
        
    except json.JSONDecodeError:
        return JsonResponse({'error': 'JSON Invalide'}, status=400)
    except Exception as e:
        return JsonResponse({'error': str(e)}, status=500)