import logging

from django.shortcuts import render, redirect , get_object_or_404
from .forms import OrganizationForm
from .models import Organization,Document,Risk
from backend.core.utils import get_top_risk
from django.urls import reverse
from backend.accounts.utils import send_confirmation_email

# @login_required
# def index(request):
#     return HttpResponse('<h1>Django</h1><p>Página simples.</p>')

logger = logging.getLogger(__name__)

# @login_required
def index(request):
    template_name = 'index.html'
    return render(request, template_name)


def signup(request):
    if request.method == 'POST':
        form = OrganizationForm(request.POST)
        if form.is_valid():
            organization = form.save()
            top_risk_ids = get_top_risk(organization)
            top_risks = Risk.objects.filter(risk_id__in = top_risk_ids)

            organization.risks.set(top_risks)

            document = Document.objects.create(organization=organization)
            document.add_segment('h1', "Top 10 Risk Identified")

            risk_content = "\n\n".join([
                f"Risk: {risk.risk_id} : {risk.risk_name} \n"
                f"Category: {risk.category}\n"
                f"Primary Impaact: {risk.primary_impact} \n"
                f"Secondary Impact: {risk.secondary_impact}\n"
                f"Tertiary Impact: {risk.tretiary_impact} \n"
                f"Detection Difficulty: {risk.detection_difficulty} \n"
                f"Recovery Complexity: {risk.recovery_complexity} \n"
                f"Business Impact Severity: {risk.businnes_impact_severity}\n"
                for risk in top_risks
            ])
            
            document.add_segment('body',f"Identified Risks: \n\n{risk_content}")

            send_confirmation_email(form.data['email'])

            return render(request, 'thankyou.html', {
                'email': form.data['email'],
                'document_link': reverse('core:document', args=[str(document.id)])
                })
        else:
            logging.error(form.errors)
            return render(request, 'signup.html', {'form': form})
    else:
        form = OrganizationForm()

    return render(request, 'signup.html', {'form': form})


def thankyou(request):
    return render(request, 'thankyou.html')

def document(request, document_id):  
    print(f"Document ID received: {document_id}")
    doc = get_object_or_404(Document, id=document_id)

    return render(request, 'document.html', {
        'document': doc,
        'organization': doc.organization,
        'segments': doc.segments.all(),
    })
