from django.shortcuts import render
from ai.local_ai_api import LocalAIApi

def index(request):
    if request.method == 'POST':
        user_message = request.POST.get('message')
        
        # Get conversation history from session
        conversation = request.session.get('conversation', [])
        conversation.append({'role': 'user', 'content': user_message})

        response = LocalAIApi.create_response({
            "input": [
                {'role': 'system', 'content': 'You are a friendly AI that helps users find music based on their mood. Ask up to 6 questions to understand their mood and then suggest a playlist.'},
                *conversation
            ],
        })

        if response.get("success"):
            ai_message = LocalAIApi.extract_text(response)
            conversation.append({'role': 'assistant', 'content': ai_message})
            request.session['conversation'] = conversation
            return render(request, 'core/index.html', {'user_message': user_message, 'ai_message': ai_message})
        else:
            # Handle error
            return render(request, 'core/index.html', {'user_message': user_message, 'ai_message': 'Sorry, I had an error.'})

    else:
        # Start of a new conversation
        request.session['conversation'] = []
        return render(request, 'core/index.html', {'ai_message': 'Hi! How are you feeling today?'})
