import json
from django.shortcuts import render, redirect, get_object_or_404
from django.views import View
from django.contrib import messages
from .models import Scan
from .osint_services import phone_lookup, email_lookup, serp_search

class DashboardView(View):
    def get(self, request):
        recent_scans = Scan.objects.all()[:10]
        context = {
            'recent_scans': recent_scans,
            'title': "Sentinel OSINT Dashboard"
        }
        return render(request, 'core/index.html', context)

    def post(self, request):
        query = request.POST.get('query', '').strip()
        scan_type = request.POST.get('scan_type', 'phone')
        
        if not query:
            messages.error(request, "Search query is required.")
            return redirect('index')

        # Perform lookups based on type
        results = {}
        if scan_type == 'phone':
            results = phone_lookup(query)
            # Add serp search for the phone number
            results['serp_results'] = serp_search(query)
        elif scan_type == 'email':
            results = email_lookup(query)
            results['serp_results'] = serp_search(query)
        else:
            # For general names, usernames, or IPs, we primarily use SERP and future modules
            results['serp_results'] = serp_search(query)

        # Basic risk score calculation logic (mock for now)
        risk_score = 10 # Default low
        if scan_type == 'email' and results.get('abstract', {}).get('deliverability') == 'UNDELIVERABLE':
            risk_score = 80
        elif scan_type == 'phone' and results.get('veriphone', {}).get('phone_valid') == False:
            risk_score = 90

        # Save scan
        scan = Scan.objects.create(
            target_type=scan_type,
            target_value=query,
            results_json=json.dumps(results),
            risk_score=risk_score
        )

        return redirect('scan_detail', pk=scan.pk)

class ScanDetailView(View):
    def get(self, request, pk):
        scan = get_object_or_404(Scan, pk=pk)
        results = scan.get_results()
        context = {
            'scan': scan,
            'results': results,
            'title': f"Report: {scan.target_value}"
        }
        return render(request, 'core/scan_detail.html', context)