from django.shortcuts import render
from django.http import JsonResponse
from .dns_engine import check_domain
import re


def _clean_domain(raw: str) -> str:
    raw = raw.strip().lower()
    raw = re.sub(r'^https?://', '', raw)
    raw = raw.split('/')[0].split('?')[0]
    return raw.rstrip('.')


def index(request):
    return render(request, 'checker/index.html')


def report(request, domain):
    domain = _clean_domain(domain)
    if not domain or len(domain) < 3:
        return render(request, 'checker/index.html', {'error': 'Please enter a valid domain name.'})
    result = check_domain(domain)
    return render(request, 'checker/report.html', {'report': result})


def check_ajax(request):
    """AJAX endpoint — returns JSON for jQuery live checking."""
    domain = _clean_domain(request.GET.get('domain', ''))
    if not domain:
        return JsonResponse({'error': 'No domain provided'}, status=400)
    result = check_domain(domain)
    data = {
        'domain': result.domain,
        'elapsed': result.elapsed,
        'pass_count': result.pass_count,
        'warn_count': result.warn_count,
        'error_count': result.error_count,
        'results': [
            {
                'category': r.category,
                'status': r.status,
                'test_name': r.test_name,
                'information': r.information,
            }
            for r in result.results
        ],
    }
    return JsonResponse(data)
