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})


def search_queries(request):
    form = SearchForm()
    results = []
    no_results = False  # Flag to indicate no results
    error_message = ""  # For error messages

    if request.method == "GET":
        form = SearchForm(request.GET)
        if form.is_valid():
            query = form.cleaned_data['query']

            # Check if the query has at least 3 words
            if len(query.split()) < 3:
                error_message = "Please search with at least three words."
            else:
                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, 
        'error_message': error_message
    })

# 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] > 75:  # 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)


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

            # Check if query has at least three words
            if len(query.split()) < 3:
                return JsonResponse({
                    'error': 'Query must contain at least three words.',
                    'query': query
                }, status=400)

            # Fetch all possible queries
            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

            # Process best matches
            if best_matches and best_matches[0][1] > 75:  # 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})

            # Return results
            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)