from django.contrib import admin, messages
from django.contrib.admin.views.decorators import staff_member_required
from django.core.exceptions import PermissionDenied
from django.shortcuts import redirect, render
from django.views.decorators.http import require_http_methods

from monitoring.models import WebsiteMonitor

from .demo_data import DEMO_MARKER, clear_wordpress_demo_data, seed_wordpress_demo_data
from .models import SSLCertificate, WordPressPlugin, WordPressSite, WordPressTheme


def wordpress_demo_permission(request):
    return bool(request.user and request.user.is_active and request.user.is_superuser)


@staff_member_required
@require_http_methods(["GET", "POST"])
def wordpress_demo_center(request):
    if not wordpress_demo_permission(request):
        raise PermissionDenied

    if request.method == "POST":
        action = request.POST.get("action")
        confirmation = (request.POST.get("confirmation") or "").strip()
        if confirmation != "DADOS DEMO WORDPRESS":
            messages.error(request, "Escreva exatamente DADOS DEMO WORDPRESS para confirmar.")
            return redirect("wordpress_demo_center")
        if action == "seed":
            result = seed_wordpress_demo_data(reset=False)
            messages.success(request, f"Dados fictícios preparados: {result['sites_total']} sites e {result['plugins_total']} plugins.")
        elif action == "reset":
            result = seed_wordpress_demo_data(reset=True)
            messages.success(request, f"Demonstração recriada: {result['sites_total']} sites, {result['plugins_total']} plugins e {result['themes_total']} temas.")
        elif action == "clear":
            clear_wordpress_demo_data()
            messages.warning(request, "Os dados técnicos fictícios V9.4 foram eliminados.")
        else:
            messages.error(request, "Ação inválida.")
        return redirect("wordpress_demo_center")

    context = {
        **admin.site.each_context(request),
        "title": "Dados de demonstração WordPress",
        "marker": DEMO_MARKER,
        "counts": {
            "sites": WordPressSite.objects.filter(notes__contains=DEMO_MARKER).count(),
            "plugins": WordPressPlugin.objects.filter(notes__contains=DEMO_MARKER).count(),
            "themes": WordPressTheme.objects.filter(notes__contains=DEMO_MARKER).count(),
            "ssl": SSLCertificate.objects.filter(notes__contains=DEMO_MARKER).count(),
            "monitors": WebsiteMonitor.objects.filter(name__startswith="DEMO WP —").count(),
        },
    }
    return render(request, "admin/technical/wordpress_demo_center.html", context)
