from django.shortcuts import render
from django.http import JsonResponse
from ai.local_ai_api import LocalAIApi
import json

def story_writer(request):
    return render(request, 'story_writer/index.html')

def ai_assistant(request):
    if request.method == 'POST':
        data = json.loads(request.body)
        story = data.get('story', '')
        prompt = data.get('prompt', '')

        response = LocalAIApi.create_response(
            {
                "input": [
                    {"role": "system", "content": "You are a creative writing assistant."},
                    {"role": "user", "content": f'Here is the story so far:\n\n{story}\n\nNow, please continue the story with a {prompt}.'}
                ],
            },
        )

        if response.get("success"):
            text = LocalAIApi.extract_text(response)
            return JsonResponse({'suggestion': text})
        else:
            return JsonResponse({'error': 'Failed to get a response from the AI.'}, status=500)

    return JsonResponse({'error': 'Invalid request method.'}, status=405)