from django.shortcuts import render
from django.utils import timezone
from django.shortcuts import redirect
from review.forms import ReplyForm
from review.models import Review, CustomReply

from .nlu_utils import model_inference, analyze_inference, filter_with_last_ten_reviews


def predict_report(request, review_id):
    review = Review.objects.filter(review_id=review_id).first()
    if review is None:
        return redirect('un-replied-review')
    location_id = review.location.location_id
    text = review.comment.lower()
    res = model_inference(text=text)
    intents = analyze_inference(res)
    now = timezone.now()
    form = ReplyForm()
    date = now - timezone.timedelta(days=30)
    reviews = Review.objects.filter(reply=None, update_time__gte=date).exclude(comment=None).order_by('update_time')
    replies = {}
    for intent in intents.keys():
        r = CustomReply.objects.filter(reply_category=intent)
        filtered_replies = filter_with_last_ten_reviews(location_id, r)
        replies[intent] = filtered_replies
    context = {
        'reviews': reviews,
        'form': form,
        'intents': intents,
        'replies': replies
    }
    return render(request, 'dashboard.html', context)
