import os
import traceback
from django.core.management.base import BaseCommand
from django.conf import settings
from courses.models import Certificate
from courses.utils import generate_certificate_pdf, _build_certificate_canvas

class Command(BaseCommand):
    help = "Diagnóstico exhaustivo para la generación del Diploma PDF en terminal cPanel"

    def add_arguments(self, parser):
        parser.add_argument(
            '--code',
            type=str,
            default='LJ-2026-MET1',
            help='Código de constancia a verificar (ej. LJ-2026-MET1)'
        )

    def handle(self, *args, **options):
        code = options['code']
        self.stdout.write(self.style.WARNING(f"\n======================================================="))
        self.stdout.write(self.style.WARNING(f"🔬 INICIANDO DIAGNÓSTICO EN CPANEL PARA DIPLOMA: {code}"))
        self.stdout.write(self.style.WARNING(f"=======================================================\n"))

        self.stdout.write("🔍 [1/4] Buscando constancia en la base de datos...")
        try:
            cert = Certificate.objects.filter(certificate_code=code).first()
            if not cert:
                self.stdout.write(self.style.WARNING(f"⚠️ No se encontró el código '{code}'. Buscando el último diploma en la base de datos..."))
                cert = Certificate.objects.first()
                if not cert:
                    self.stdout.write(self.style.ERROR("❌ ERROR: No hay ningún diploma en la base de datos de producción."))
                    return
                self.stdout.write(self.style.WARNING(f"ℹ️ Usando diploma encontrado: {cert.certificate_code} (Alumno: {cert.enrollment.user.username})"))
            else:
                self.stdout.write(self.style.SUCCESS(f"✅ Diploma encontrado: ID {cert.id} | Alumno: {cert.enrollment.user.get_full_name() or cert.enrollment.user.username} | Curso: {cert.enrollment.course.title}"))
        except Exception as e:
            self.stdout.write(self.style.ERROR("❌ ERROR consultando la base de datos:"))
            traceback.print_exc()
            return

        self.stdout.write("\n🔍 [2/4] Verificando archivos de imágenes estáticas...")
        logo_path = os.path.join(str(settings.BASE_DIR), "static", "img", "logo.png")
        side_path_png = os.path.join(str(settings.BASE_DIR), "static", "img", "diploma_side.png")
        side_path_jpg = os.path.join(str(settings.BASE_DIR), "static", "img", "diploma_side.jpg")

        self.stdout.write(f"   -> BASE_DIR: {settings.BASE_DIR}")
        self.stdout.write(f"   -> Logo oficial ({logo_path}): {'✅ EXISTE' if os.path.exists(logo_path) else '❌ NO EXISTE'}")
        if os.path.exists(side_path_png):
            self.stdout.write(f"   -> Imagen lateral ({side_path_png}): ✅ EXISTE (PNG)")
        elif os.path.exists(side_path_jpg):
            self.stdout.write(f"   -> Imagen lateral ({side_path_jpg}): ✅ EXISTE (JPG)")
        else:
            self.stdout.write(f"   -> Imagen lateral: ⚠️ NO EXISTE (Se usará panel geométrico vectorial)")

        self.stdout.write("\n🚀 [3/4] Probando generación de PDF CON IMÁGENES (_build_certificate_canvas(..., use_images=True))...")
        try:
            buffer = _build_certificate_canvas(cert, use_images=True)
            size_bytes = len(buffer.getvalue())
            self.stdout.write(self.style.SUCCESS(f"✅ ¡ÉXITO! PDF generado en memoria con imágenes (Tamaño: {size_bytes} bytes)."))
        except Exception as e:
            self.stdout.write(self.style.ERROR(f"❌ FALLO en generación CON IMÁGENES (_build_certificate_canvas(use_images=True)):"))
            self.stdout.write("------------------- TRACEBACK COMPLETO -------------------")
            traceback.print_exc()
            self.stdout.write("----------------------------------------------------------")

        self.stdout.write("\n🛡️ [4/4] Probando generación de PDF FALLBACK VECTORIAL SIN IMÁGENES (_build_certificate_canvas(..., use_images=False))...")
        try:
            buffer_vec = _build_certificate_canvas(cert, use_images=False)
            size_vec = len(buffer_vec.getvalue())
            self.stdout.write(self.style.SUCCESS(f"✅ ¡ÉXITO FALLBACK! PDF vectorial generado sin errores (Tamaño: {size_vec} bytes)."))
        except Exception as e2:
            self.stdout.write(self.style.ERROR(f"❌ FALLO en generación FALLBACK VECTORIAL:"))
            self.stdout.write("------------------- TRACEBACK COMPLETO -------------------")
            traceback.print_exc()
            self.stdout.write("----------------------------------------------------------")

        self.stdout.write("\n🔧 PROBANDO FUNCIÓN PÚBLICA PRINCIPAL (generate_certificate_pdf(cert))...")
        try:
            final_buf = generate_certificate_pdf(cert)
            self.stdout.write(self.style.SUCCESS(f"🏁 CONCLUSIÓN: generate_certificate_pdf ejecutó sin lanzar excepción fatal. Bytes: {len(final_buf.getvalue())}"))
        except Exception as e_final:
            self.stdout.write(self.style.ERROR(f"💥 CONCLUSIÓN FATAL: generate_certificate_pdf lanzó una excepción no capturada:"))
            traceback.print_exc()
