from django.shortcuts import render, get_object_or_404
from django.template import loader
from django.urls import reverse
from django.http import HttpResponse
from django.utils.html import strip_tags
from django.core.paginator import Paginator
from django.db.models import Q
import json

from core.views import gen_page_base
from blog.models import Blog, Cat_Blog, Blog_search_Form
from blog.seo_helpers import SEOMetadata


def blog_index(request, bcat):
    """Vue pour la liste des articles du blog"""
    template = loader.get_template('listing.html')
    page = gen_page_base()
    
    # Recherche
    b_search = request.GET.get('b_search')
    if b_search:
        page.blog_search = Blog_search_Form(initial={'b_search': b_search})
        q = Q(b_titre__icontains=b_search) | Q(b_mots_clefs__icontains=b_search) | Q(b_description__icontains=b_search)
    else:
        page.blog_search = Blog_search_Form()
    
    # Filtrage des articles
    category = None
    if bcat == "index":
        if b_search:
            blog_art = Blog.objects.filter(b_publier=True).filter(q).order_by('-b_publdate')[:5]
        else:
            blog_art = Blog.objects.filter(b_publier=True).order_by('-b_publdate')[:5]
        page.blog_cat = Cat_Blog.objects.all()[:15]
    elif bcat == "all":
        blog_art = Blog.objects.filter(b_publier=True).order_by('-b_publdate')
        page.blog_cat = Cat_Blog.objects.all()[:15]
    else:
        category = get_object_or_404(Cat_Blog, cb_titre_slgify=bcat)
        if b_search:
            blog_art = Blog.objects.filter(b_publier=True, b_cat__cb_titre_slgify=bcat).filter(q).order_by('-b_publdate')
        else:
            blog_art = Blog.objects.filter(b_publier=True, b_cat__cb_titre_slgify=bcat).order_by('-b_publdate')
        page.blog_cat = Cat_Blog.objects.filter(cb_titre_slgify=bcat)[:15]
        page.retour = "blog_index"
    
    # Pagination
    paginator = Paginator(blog_art, 15)
    page_number = request.GET.get('page')
    page.blog_art = paginator.get_page(page_number)
    page.blog_art.nbpage = range(page.blog_art.paginator.num_pages)
    
    # Top 10 articles
    page.blog_top10 = Blog.objects.filter(b_publier=True).order_by('-b_reading')[:10]
    
    # SEO Metadata
    seo_helper = SEOMetadata(request)
    seo = seo_helper.get_listing_metadata(category)
    page.seo = seo
    page.seo_json = json.dumps(seo.get('schema', {})) if 'schema' in seo else '{}'
    
    # Configuration page traditionnelle
    page.p_adresse = reverse('blog_index')
    page.p_titre = category.cb_titre if category else "Les articles du Blog"
    page.p_contenu = ""
    page.p_right = f"Retrouvez tous les articles de la catégorie {category.cb_titre}" if category else "Retrouvez tous les articles de mon blog"
    page.p_description = strip_tags(page.p_right)
    page.p_mots_clefs = ""
    
    for cat in page.blog_cat.all():
        page.p_mots_clefs += cat.cb_titre + ', '
    
    # Fil d'Ariane (Breadcrumbs)
    breadcrumbs = [
        {'name': 'Accueil', 'url': reverse('core_index')},
        {'name': 'Blog', 'url': reverse('blog_index')},
    ]
    if category:
        breadcrumbs.append({
            'name': category.cb_titre,
            'url': reverse('blog_tag', args=[category.cb_titre_slgify])
        })
    page.breadcrumbs = breadcrumbs
    
    html = template.render({
        'page': page,
        'user': request.user,
    }, request)
    
    return HttpResponse(html)


def blog_play(request, bart):
    """Vue pour afficher un article de blog"""
    template = loader.get_template('read.html')
    page = gen_page_base()
    
    # Récupération de l'article avec optimisation des requêtes
    article = get_object_or_404(
        Blog.objects.prefetch_related('b_cat'),
        b_titre_slugify=bart,
        b_publier=True
    )
    
    # Incrémenter les lectures
    article.b_reading += 1
    article.save(update_fields=['b_reading'])
    
    # SEO Metadata
    seo_helper = SEOMetadata(request, article)
    seo = seo_helper.get_blog_metadata(article)
    page.seo = seo
    page.seo_json = json.dumps(seo.get('schema', {}))
    
    # Configuration page traditionnelle
    page.p_adresse = reverse('blog_play', args=[bart])
    page.p_titre = article.b_titre
    page.p_contenu = article.b_description
    page.p_description = strip_tags(article.b_description)
    page.p_right = article.b_right if article.b_right else "&nbsp;"
    page.blog_art = [article]
    page.c_card_mp = "True"
    
    # Mots clés
    page.p_mots_clefs = ""
    for cat in article.b_cat.all():
        page.p_mots_clefs += cat.cb_titre + ', '
    
    # Fil d'Ariane (Breadcrumbs)
    breadcrumbs = [
        {'name': 'Accueil', 'url': reverse('core_index')},
        {'name': 'Blog', 'url': reverse('blog_index')},
        {'name': article.b_titre, 'url': reverse('blog_play', args=[bart])}
    ]
    
    # Ajouter les catégories au breadcrumb si présent
    first_category = article.b_cat.first()
    if first_category:
        breadcrumbs.insert(2, {
            'name': first_category.cb_titre,
            'url': reverse('blog_tag', args=[first_category.cb_titre_slgify])
        })
    
    page.breadcrumbs = breadcrumbs
    
    html = template.render({
        'page': page,
        'user': request.user,
    }, request)
    
    return HttpResponse(html)


def blog_update(request):
    """
    ATTENTION: Cette fonction est obsolète et dangereuse!
    À supprimer en production ou protéger avec authentification admin.
    """
    # Cette fonction ne devrait PAS être accessible en production
    if not request.user.is_staff:
        return HttpResponse("Accès refusé", status=403)
    
    arts = Blog.objects.all()
    for art in arts:
        # Nettoyage des caractères mal encodés
        art.b_contenu = art.b_contenu.replace('é"', 'é').replace('à"', 'à').replace('ê"', 'ê').replace('è"', 'è').replace('ô"', 'ô').replace('«"', '«').replace('»"', '»')
        art.save()
    
    return HttpResponse("Mise à jour terminée")
