from django.db.models import Avg, Count, Max
from django.shortcuts import get_object_or_404, redirect, render

from .forms import ThreatScanForm
from .models import ThreatScan
from .scanner import scan_content


def _dashboard_context():
    scans = ThreatScan.objects.all()
    totals = scans.aggregate(total=Count("id"), avg_score=Avg("risk_score"), latest=Max("created_at"))
    high_risk_count = scans.filter(risk_level__in=[ThreatScan.RiskLevel.HIGH, ThreatScan.RiskLevel.CRITICAL]).count()
    return {
        "total_scans": totals["total"] or 0,
        "avg_score": round(totals["avg_score"] or 0),
        "latest_scan_at": totals["latest"],
        "high_risk_count": high_risk_count,
        "recent_scans": scans[:6],
    }


def home(request):
    form = ThreatScanForm()
    context = {
        "project_name": "SentinelAI Cyber Assistant",
        "meta_description": "Privacy-first AI cybersecurity assistant for phishing URL and scam message risk scoring with clear explanations.",
        "form": form,
        **_dashboard_context(),
    }
    return render(request, "core/index.html", context)


def create_scan(request):
    if request.method != "POST":
        return redirect("home")
    form = ThreatScanForm(request.POST)
    if not form.is_valid():
        context = {
            "project_name": "SentinelAI Cyber Assistant",
            "meta_description": "Scan a suspicious URL, email, or message for phishing risk.",
            "form": form,
            **_dashboard_context(),
        }
        return render(request, "core/index.html", context, status=422)

    result = scan_content(form.cleaned_data["scan_type"], form.cleaned_data["content"])
    scan = ThreatScan.objects.create(
        scan_type=form.cleaned_data["scan_type"],
        target_preview=result.target_preview,
        content_hash=result.content_hash,
        risk_score=result.risk_score,
        risk_level=result.risk_level,
        verdict=result.verdict,
        explanation=result.explanation,
        indicators=result.indicators,
        recommended_actions=result.recommended_actions,
        store_metadata=form.cleaned_data["store_metadata"],
    )
    return redirect("scan_detail", pk=scan.pk)


def scan_history(request):
    scans = ThreatScan.objects.all()
    context = {
        "project_name": "Scan History",
        "meta_description": "Review privacy-safe cybersecurity scan results and risk levels.",
        "scans": scans,
        **_dashboard_context(),
    }
    return render(request, "core/scan_history.html", context)


def scan_detail(request, pk):
    scan = get_object_or_404(ThreatScan, pk=pk)
    context = {
        "project_name": f"Scan Result #{scan.pk}",
        "meta_description": "Detailed phishing and scam risk result with explainable AI indicators.",
        "scan": scan,
    }
    return render(request, "core/scan_detail.html", context)
