from django.shortcuts import render

# Create your views here.
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from django.views import View
from django.shortcuts import render
from .models import PasswordQuery
from .forms import SearchForm
from fuzzywuzzy import process, fuzz


def search_queries(request):
    form = SearchForm()
    results = []
    no_results = False  # Flag to indicate no results

    if request.method == "GET":
        form = SearchForm(request.GET)
        if form.is_valid():
            query = form.cleaned_data['query']
            all_queries = PasswordQuery.objects.all().values_list('question', flat=True)
            best_matches = process.extract(query, all_queries, limit=5, scorer=fuzz.partial_ratio)

            if best_matches:
                best_match = best_matches[0][0]
                if best_matches[0][1] > 70:  # You can adjust the threshold
                    result = PasswordQuery.objects.get(question=best_match)
                    results.append({"question": result.question, "answer": result.answer})
                else:
                    no_results = True
            else:
                no_results = True

    return render(request, 'search.html', {'form': form, 'results': results, 'no_results': no_results})


class SearchQueryView(View):
    def get(self, request, *args, **kwargs):
        results = []

        form = SearchForm(request.GET)
        if form.is_valid():
            query = form.cleaned_data['query']
            print(f"Searching for: {query}")  # Debugging the query

            all_queries = PasswordQuery.objects.all().values_list('question', flat=True)
            best_matches = process.extract(query, all_queries, limit=5, scorer=fuzz.partial_ratio)
            print("Best matches:", best_matches)  # Debugging the matches

            if best_matches:
                if best_matches[0][1] > 70:  # Adjust the threshold if needed
                    best_match = best_matches[0][0]
                    result = PasswordQuery.objects.get(question=best_match)
                    results.append({"question": result.question, "answer": result.answer})

            if results:
                return JsonResponse(results, safe=False, status=200)
            else:
                return JsonResponse({'error': 'No matches found', 'query': query}, status=404)
        else:
            return JsonResponse({'error': 'Invalid form data', 'details': form.errors}, status=400)