import hashlib
import os
from django.shortcuts import render, redirect
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from .models import FileScan

def index(request):
    scans = FileScan.objects.all()[:10]
    return render(request, "core/index.html", {"recent_scans": scans})

def scan_file(request):
    if request.method == 'POST' and request.FILES.get('file'):
        uploaded_file = request.FILES['file']
        filename = uploaded_file.name
        content = uploaded_file.read()
        
        # Calculate SHA256
        sha256_hash = hashlib.sha256(content).hexdigest()
        
        # Basic Static Analysis
        risk_level = 'LOW'
        reasons = []
        
        # 1. Extension check
        ext = os.path.splitext(filename)[1].lower()
        danger_exts = ['.exe', '.dll', '.bin', '.sh', '.bat', '.msi', '.js', '.vbs', '.ps1', '.py']
        if ext in danger_exts:
            risk_level = 'MEDIUM'
            reasons.append(f"Suspicious file extension: {ext}")
            
        # 2. Content check (basic keyword search)
        suspicious_keywords = [
            b'eval(', b'exec(', b'os.system(', b'subprocess.run(', b'base64.b64decode(',
            b'chmod +x', b'rm -rf', b'powershell', b'cmd.exe'
        ]
        found_keywords = []
        for kw in suspicious_keywords:
            if kw in content:
                found_keywords.append(kw.decode())
        
        if found_keywords:
            risk_level = 'HIGH'
            reasons.append(f"Found suspicious code patterns: {', '.join(found_keywords)}")
            
        if not reasons:
            reasons.append("No immediate threats found via static analysis.")
        
        # Save to DB
        scan = FileScan.objects.create(
            filename=filename,
            file_hash=sha256_hash,
            risk_level=risk_level,
            reasons="; ".join(reasons)
        )
        
        if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
            return JsonResponse({
                'filename': scan.filename,
                'hash': scan.file_hash,
                'risk_level': scan.risk_level,
                'reasons': scan.reasons,
                'created_at': scan.created_at.strftime('%Y-%m-%d %H:%M:%S')
            })
            
        return render(request, "core/index.html", {
            "result": scan,
            "recent_scans": FileScan.objects.all()[:10]
        })
        
    return redirect('index')