from django.shortcuts import render
from django.views.generic import TemplateView
from django.db.models import Count, Q
from parks.models import Park
from rides.models import Ride
from companies.models import Company, Manufacturer

def handler404(request, exception):
    return render(request, '404.html', status=404)

def handler500(request):
    return render(request, '500.html', status=500)

class HomeView(TemplateView):
    template_name = 'home.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        
        # Get stats
        context['stats'] = {
            'total_parks': Park.objects.count(),
            'total_rides': Ride.objects.count(),
            'total_roller_coasters': Ride.objects.filter(category='RC').count(),
        }
        
        # Get popular parks (based on average rating)
        context['popular_parks'] = Park.objects.exclude(
            average_rating__isnull=True
        ).order_by('-average_rating')[:5]
        
        # Get popular rides (based on average rating)
        context['popular_rides'] = Ride.objects.exclude(
            average_rating__isnull=True
        ).order_by('-average_rating')[:5]
        
        return context

class SearchView(TemplateView):
    template_name = 'search_results.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        query = self.request.GET.get('q', '').strip()

        if query:
            # Search parks
            context['parks'] = Park.objects.filter(
                Q(name__icontains=query) |
                Q(location__icontains=query) |
                Q(description__icontains=query)
            ).select_related('owner').prefetch_related('photos')[:10]

            # Search rides
            context['rides'] = Ride.objects.filter(
                Q(name__icontains=query) |
                Q(description__icontains=query) |
                Q(manufacturer__name__icontains=query)
            ).select_related('park', 'coaster_stats').prefetch_related('photos')[:10]

            # Search companies
            context['companies'] = Company.objects.filter(
                Q(name__icontains=query) |
                Q(headquarters__icontains=query) |
                Q(description__icontains=query)
            ).prefetch_related('parks')[:10]

            # Search manufacturers
            context['manufacturers'] = Manufacturer.objects.filter(
                Q(name__icontains=query) |
                Q(headquarters__icontains=query) |
                Q(description__icontains=query)
            ).prefetch_related('rides')[:10]

        return context
