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

def home(request):
    return render(request, "core/index.html", {'timestamp': int(time.time())})

def generate_joke(request):
    response = LocalAIApi.create_response({
        "input": [
            {"role": "system", "content": "You are a witty comedian who specializes in Gen-Z humor."},
            {"role": "user", "content": "Tell me a short, funny joke."},
        ],
        "text": {"format": {"type": "json_object"}},
    })

    if response.get("success"):
        payload = LocalAIApi.decode_json_from_response(response)
        ai_reply = payload or response.get("data")
        joke = ai_reply.get("joke", "I'm sorry, I couldn't think of a joke right now. Try again!")
    else:
        joke = "I'm sorry, I couldn't think of a joke right now. Try again!"

    return JsonResponse({"joke": joke})
