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

def get_playlist_for_mood(mood):
    """
    Returns a mock playlist of songs for a given mood.
    """
    playlists = {
        "happy": [
            {"title": "Happy", "artist": "Pharrell Williams"},
            {"title": "Don't Stop Me Now", "artist": "Queen"},
            {"title": "Uptown Funk", "artist": "Mark Ronson ft. Bruno Mars"},
        ],
        "sad": [
            {"title": "Someone Like You", "artist": "Adele"},
            {"title": "Hurt", "artist": "Johnny Cash"},
            {"title": "Fix You", "artist": "Coldplay"},
        ],
        "energetic": [
            {"title": "Eye of the Tiger", "artist": "Survivor"},
            {"title": "Thunderstruck", "artist": "AC/DC"},
            {"title": "Can't Stop", "artist": "Red Hot Chili Peppers"},
        ],
        "calm": [
            {"title": "Weightless", "artist": "Marconi Union"},
            {"title": "Clair de Lune", "artist": "Claude Debussy"},
            {"title": "Orinoco Flow", "artist": "Enya"},
        ],
    }
    return playlists.get(mood.lower(), [])

def index(request):
    playlist = None
    if request.method == 'POST':
        user_message = request.POST.get('message')
        
        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. Once you have determined the mood, respond with ONLY a JSON object with a single key "mood" and the mood as the value (e.g. {"mood": "happy"}).'},
                *conversation
            ],
        })

        ai_message = 'Sorry, I had an error.'
        if response.get("success"):
            json_response = LocalAIApi.decode_json_from_response(response)
            if json_response and 'mood' in json_response:
                mood = json_response['mood']
                playlist = get_playlist_for_mood(mood)
                ai_message = f"I've created a playlist for your {mood} mood. I hope you like it!"
            else:
                ai_message = LocalAIApi.extract_text(response)

        conversation.append({'role': 'assistant', 'content': ai_message})
        request.session['conversation'] = conversation

        if request.headers.get('x-requested-with') == 'XMLHttpRequest':
            return JsonResponse({'ai_message': ai_message, 'playlist': playlist})
        
        return render(request, 'core/index.html', {'user_message': user_message, 'ai_message': ai_message, 'playlist': playlist, 'conversation': conversation})

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