from django.shortcuts import render, get_object_or_404
from django.core.paginator import Paginator
from .models import Article, Category, Author
from taggit.models import Tag
from apps.core.models import SiteSettings

def get_base_context():
    return {'site': SiteSettings.get_solo()}

def article_list(request):
    articles = Article.objects.filter(status='published').select_related('author').prefetch_related('categories', 'tags')
    
    # Grab featured article for hero section
    featured_article = articles.filter(is_featured=True).first()
    if not featured_article:
        featured_article = articles.first()
        
    # Grab editors picks for the 3 grid items
    editors_picks = articles.filter(is_editors_pick=True)[:3]
    if editors_picks.count() < 3:
        editors_picks = articles[:3]
        
    # Grab timeline events
    from .models import TimelineEvent
    timeline_events = TimelineEvent.objects.select_related('article').order_by('order')[:6]
    
    paginator = Paginator(articles, 12)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    context = get_base_context()
    context.update({
        'page_obj': page_obj,
        'featured_article': featured_article,
        'editors_picks': editors_picks,
        'timeline_events': timeline_events,
    })
    return render(request, 'articles/article_list.html', context)

def article_detail(request, slug):
    article = get_object_or_404(Article.objects.select_related('author').prefetch_related('categories', 'tags'), slug=slug, status='published')
    
    # Increment view count blindly on GET
    article.view_count += 1
    article.save(update_fields=['view_count'])
    
    related_articles = Article.objects.filter(categories__in=article.categories.all(), status='published').exclude(id=article.id).distinct()[:3]
    
    is_bookmarked = False
    if request.user.is_authenticated:
        from .models import UserBookmark
        is_bookmarked = UserBookmark.objects.filter(user=request.user, article=article).exists()
    
    context = get_base_context()
    context.update({
        'article': article,
        'related_articles': related_articles,
        'is_bookmarked': is_bookmarked,
    })
    return render(request, 'articles/article_detail.html', context)

def category_detail(request, slug):
    category = get_object_or_404(Category, slug=slug, is_active=True)
    articles = Article.objects.filter(categories=category, status='published').select_related('author').prefetch_related('categories', 'tags').distinct()
    
    tag_slug = request.GET.get('tag')
    if tag_slug:
        articles = articles.filter(tags__slug=tag_slug)
        
    paginator = Paginator(articles, 12)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    # Get all tags used in this category for filtering
    tags = Tag.objects.filter(article__categories=category, article__status='published').distinct()
    
    context = get_base_context()
    context.update({
        'category': category,
        'page_obj': page_obj,
        'tags': tags,
        'current_tag': tag_slug,
    })
    return render(request, 'articles/category_list.html', context)

def tag_detail(request, slug):
    tag = get_object_or_404(Tag, slug=slug)
    articles = Article.objects.filter(tags=tag, status='published').select_related('author').prefetch_related('categories')
    
    paginator = Paginator(articles, 12)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    context = get_base_context()
    context.update({
        'tag': tag,
        'page_obj': page_obj,
    })
    return render(request, 'articles/tag_list.html', context)

def author_detail(request, slug):
    author = get_object_or_404(Author, slug=slug)
    articles = Article.objects.filter(author=author, status='published').prefetch_related('categories')
    
    paginator = Paginator(articles, 12)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    context = get_base_context()
    context.update({
        'author': author,
        'page_obj': page_obj,
    })
    return render(request, 'articles/author_detail.html', context)

from django.http import JsonResponse
from django.contrib.auth.decorators import login_required
from .models import UserBookmark

@login_required
def toggle_bookmark(request, article_id):
    """Kept for old links; saves now live in apps.engage (shared with magazines and games)."""
    from apps.engage.models import Reaction
    from apps.engage.registry import ct
    if request.method == 'POST':
        article = get_object_or_404(Article, id=article_id, status='published')
        where = dict(user=request.user, content_type=ct(article), object_id=article.pk, kind='save')
        deleted, _ = Reaction.objects.filter(**where).delete()
        if deleted:
            return JsonResponse({'status': 'removed'})
        Reaction.objects.create(**where)
        return JsonResponse({'status': 'added'})
    return JsonResponse({'status': 'invalid method'}, status=405)

@login_required
def reading_list(request):
    from apps.engage.models import Reaction
    from django.contrib.contenttypes.models import ContentType
    ids = list(Reaction.objects.filter(user=request.user, kind='save',
                                       content_type=ContentType.objects.get_for_model(Article))
               .values_list('object_id', flat=True))
    by_id = {a.pk: a for a in Article.objects.filter(pk__in=ids, status='published')
             .select_related('author').prefetch_related('categories')}
    articles = [by_id[i] for i in ids if i in by_id]

    paginator = Paginator(articles, 12)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)

    context = get_base_context()
    context.update({
        'page_obj': page_obj,
    })
    return render(request, 'articles/reading_list.html', context)

import datetime
from django.utils import timezone
from .models import TodayExclusive

def today_exclusive_today(request):
    today = timezone.now().date()
    return today_exclusive_view(request, today.year, today.month, today.day)

def today_exclusive_view(request, year, month, day):
    try:
        requested_date = datetime.date(year, month, day)
    except ValueError:
        from django.http import Http404
        raise Http404("Invalid date")
        
    # Get the exclusive for the date, or fallback to latest, or random article
    exclusive = TodayExclusive.objects.filter(date__lte=requested_date).first()
    
    if exclusive:
        article = exclusive.article
        current_date = exclusive.date
    else:
        # Fallback if no exclusives exist yet
        article = Article.objects.filter(status='published').first()
        if not article:
            from django.http import Http404
            raise Http404("No articles available")
        current_date = requested_date

    # Always show prev/next buttons based on the requested calendar date
    prev_date = current_date - datetime.timedelta(days=1)
    next_date = current_date + datetime.timedelta(days=1)
    
    context = get_base_context()
    context.update({
        'article': article,
        'current_date': current_date,
        'prev_date': prev_date,
        'next_date': next_date,
        'is_today': current_date == timezone.now().date(),
        'hide_nav': False, # User requested the menu bar to be shown
    })
    return render(request, 'articles/today_exclusive.html', context)
