import os
import traceback
from django.http import HttpResponse
from django.shortcuts import redirect, render

from .models import Certificate
from .utils import generate_certificate_pdf, generate_and_sign_certificate


def verify_search_view(request):
    """
    Portal de Verificación Pública de Diplomas (/validar-certificado/).
    """
    code = request.GET.get("code")
    if code:
        clean_code = code.strip().upper()
        return redirect("certificates:verify_detail", certificate_code=clean_code)

    return render(request, "pages/verify_search.html")


def verify_detail_view(request, certificate_code):
    """
    Resultado público de la verificación del diploma.
    """
    certificate = Certificate.objects.select_related("enrollment__user", "enrollment__course").filter(
        certificate_code__iexact=certificate_code.strip()
    ).first()

    context = {
        "certificate": certificate,
        "searched_code": certificate_code.strip().upper(),
    }
    return render(request, "pages/verify_detail.html", context)


def certificate_download_view(request, certificate_code):
    """
    Descarga del diploma oficial firmado digitalmente en PDF de alta resolución.
    """
    try:
        certificate = Certificate.objects.filter(certificate_code=certificate_code).first()
        if not certificate:
            html_not_found = f"""
            <!DOCTYPE html>
            <html lang="es">
            <head>
                <meta charset="utf-8">
                <title>Constancia No Encontrada | Lo Justo LMS</title>
                <style>
                    body {{ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; padding: 40px; background: #f8fafc; color: #1e293b; margin: 0; }}
                    .card {{ max-width: 600px; margin: 60px auto; background: #ffffff; border: 1px solid #e2e8f0; border-radius: 20px; padding: 40px; box-shadow: 0 10px 30px rgba(0,0,0,0.05); text-align: center; }}
                    h1 {{ font-size: 22px; margin-top: 0; color: #0f172a; }}
                    p {{ font-size: 15px; line-height: 1.6; color: #64748b; margin-bottom: 24px; }}
                    .code {{ background: #f1f5f9; padding: 4px 12px; border-radius: 6px; font-family: monospace; font-weight: bold; color: #334155; }}
                    .btn {{ display: inline-block; background: #044d29; color: #ffffff; padding: 12px 24px; border-radius: 12px; text-decoration: none; font-weight: 600; font-size: 14px; }}
                </style>
            </head>
            <body>
                <div class="card">
                    <h1>🎓 Constancia No Encontrada</h1>
                    <p>No se localizó en la base de datos de producción ninguna constancia registrada con el código oficial <span class="code">{certificate_code}</span>.</p>
                    <a href="/" class="btn">Volver al Inicio</a>
                </div>
            </body>
            </html>
            """
            return HttpResponse(html_not_found, status=200)

        if certificate.pdf_file and os.path.exists(certificate.pdf_file.path):
            with open(certificate.pdf_file.path, "rb") as f:
                pdf_bytes = f.read()
        else:
            pdf_buffer = generate_and_sign_certificate(certificate)
            pdf_bytes = pdf_buffer.getvalue()

        filename = f"Diploma_LoJusto_{certificate.certificate_code}.pdf"
        response = HttpResponse(pdf_bytes, content_type="application/pdf")
        response["Content-Disposition"] = f'attachment; filename="{filename}"'
        response["Content-Length"] = str(len(pdf_bytes))
        return response
    except Exception as e:
        tb = traceback.format_exc()
        html = f"""
        <!DOCTYPE html>
        <html lang="es">
        <head>
            <meta charset="utf-8">
            <title>Diagnóstico Técnico | Lo Justo LMS</title>
            <style>
                body {{ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; padding: 40px; background: #fef2f2; color: #7f1d1d; margin: 0; }}
                .card {{ max-width: 950px; margin: 20px auto; background: #ffffff; border: 1px solid #fecaca; border-radius: 16px; padding: 32px; box-shadow: 0 10px 30px rgba(0,0,0,0.06); }}
                h1 {{ font-size: 22px; margin-top: 0; color: #991b1b; display: flex; align-items: center; gap: 10px; border-bottom: 2px solid #fee2e2; padding-bottom: 16px; }}
                p {{ font-size: 15px; line-height: 1.6; color: #3f3f46; }}
                .code-box {{ background: #18181b; color: #f4f4f5; font-family: 'Courier New', Courier, monospace; padding: 20px; border-radius: 10px; overflow-x: auto; font-size: 13px; line-height: 1.6; margin-top: 20px; border: 1px solid #27272a; }}
                .badge {{ background: #fee2e2; color: #991b1b; padding: 4px 10px; border-radius: 6px; font-weight: 700; font-size: 13px; }}
            </style>
        </head>
        <body>
            <div class="card">
                <h1>⚠️ Diagnóstico Técnico de Descarga en Servidor</h1>
                <p>El servidor cPanel interceptó una excepción al procesar la constancia <strong>{certificate_code}</strong>.</p>
                <p><span class="badge">Excepción principal:</span> <code style="font-size: 15px; color: #b91c1c; font-weight: bold; margin-left: 8px;">{str(e)}</code></p>
                <div class="code-box"><pre style="margin: 0;">{tb}</pre></div>
            </div>
        </body>
        </html>
        """
        return HttpResponse(html, status=200)
