from django.shortcuts import render, get_object_or_404
from django.db.models import F
from django.core.paginator import Paginator
from .models import Video
from apps.properties.models import Property


def video_list(request):
    qs = Video.objects.filter(is_published=True)
    selected_category = request.GET.get('category', '')
    if selected_category:
        qs = qs.filter(category=selected_category)
    paginator = Paginator(qs, 12)
    page = paginator.get_page(request.GET.get('page'))
    return render(request, 'videos/list.html', {
        'page_obj': page,
        'selected_category': selected_category,
        'category_choices': Video.CATEGORY_CHOICES,
    })


def video_detail(request, slug):
    video = get_object_or_404(Video, slug=slug, is_published=True)
    Video.objects.filter(pk=video.pk).update(views_count=F('views_count') + 1)

    # Related videos: same category first, fallback to recent
    related = list(Video.objects.filter(is_published=True, category=video.category).exclude(pk=video.pk)[:3])
    if len(related) < 3:
        extra = Video.objects.filter(is_published=True).exclude(pk=video.pk).exclude(
            pk__in=[v.pk for v in related]
        )[:3 - len(related)]
        related += list(extra)

    # Related properties: linked property + others at same location
    related_props = []
    if video.related_property_id:
        prop = video.related_property
        related_props = [prop]
        more = list(Property.objects.filter(
            is_published=True, location=prop.location
        ).exclude(pk=prop.pk).select_related('category', 'location')[:2])
        related_props += more

    return render(request, 'videos/detail.html', {
        'video': video,
        'related': related,
        'related_props': related_props,
    })
