from celery import shared_task
from backend.core.models import Organization, Document, Risk, Control, DocumentRiskControl
from backend.core.utils import get_top_risk, get_controls_for_risk
from django.shortcuts import get_object_or_404, render
from .utils import send_payment_email


@shared_task
def create_document_for_organization(confirmation_email):
    
    organization = get_object_or_404(Organization, email=confirmation_email)

    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 Risks Identified")

    risk_content = "\n\n".join([
        f"Risk: {risk.risk_id} - {risk.risk_name} \n"
        f"Category: {risk.category}\n"
        f"Primary Impact: {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}")

    controls_content = "Mitigation Controls:\n\n"
    
    for risk in top_risks:
        controls_content += f"Risk: {risk.risk_id} - {risk.risk_name}\n"

        selected_controls = get_controls_for_risk(risk ,organization=organization)
        
        for control_id, weight, likelihood in selected_controls:
            control = Control.objects.filter(id=control_id).first() 
            if control:
                DocumentRiskControl.objects.create(
                    document=document,
                    risk=risk,
                    control=control,
                    weight=weight,
                    likelihood=likelihood
                )
                controls_content += f"  - Control: {control.name} (Impact Weight: {weight}/10) (Likelihood: {likelihood}/10)\n"
        
        controls_content += "\n"
    
    document.add_segment('body', controls_content)

    
    send_payment_email(confirmation_email)