from django.shortcuts import render, redirect
from .models import Application, Vulnerability
from .forms import UploadFileForm, VulnerabilitySearchForm
import csv
import io
import requests

def dashboard(request):
    # Placeholder data
    total_apps = Application.objects.count()
    total_vulns = Vulnerability.objects.count()
    critical_vulns = Vulnerability.objects.filter(severity='Critical').count()
    new_vulns = Vulnerability.objects.filter(status='New').count()
    applications = Application.objects.all()

    context = {
        'total_applications': total_apps,
        'total_vulnerabilities': total_vulns,
        'critical_vulnerabilities': critical_vulns,
        'new_vulnerabilities': new_vulns,
        'applications': applications,
        "project_name": "Vulnerability Scanner",
    }
    return render(request, "core/index.html", context)

def upload_inventory(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            try:
                csv_file = request.FILES['file']
                decoded_file = io.TextIOWrapper(csv_file.file, encoding='utf-8', newline='', errors='ignore')
                reader = csv.reader(decoded_file)
                # Skip header row
                next(reader)
                for row in reader:
                    if row and len(row) == 3:
                        print(f"Processing row: {row}")
                        Application.objects.create(
                            name=row[0],
                            version=row[1],
                            vendor=row[2],
                        )
                return redirect('dashboard')
            except Exception as e:
                print(f"An error occurred: {e}")
                form.add_error(None, f"An error occurred: {e}")
    else:
        form = UploadFileForm()
    return render(request, 'core/upload_inventory.html', {'form': form})

def vulnerability_search(request):
    form = VulnerabilitySearchForm()
    results = []
    if request.method == 'POST':
        form = VulnerabilitySearchForm(request.POST)
        if form.is_valid():
            application_name = form.cleaned_data['application_name']
            # Basic search using NVD API
            url = f"https://services.nvd.nist.gov/rest/json/cves/1.0?keyword={application_name}"
            try:
                response = requests.get(url)
                data = response.json()
                if 'result' in data:
                    for cve_item in data['result']['CVE_Items']:
                        cve_id = cve_item['cve']['CVE_data_meta']['ID']
                        description = cve_item['cve']['description']['description_data'][0]['value']
                        results.append({'cve_id': cve_id, 'description': description})
            except requests.exceptions.RequestException as e:
                form.add_error(None, f"Error fetching data from NVD: {e}")

    return render(request, 'core/vulnerability_search.html', {'form': form, 'results': results})
