import os
import platform

from django import get_version as django_version
from django.shortcuts import render, redirect
from django.utils import timezone


from .forms import CsvUploadForm
from .models import SkipTraceJob

def index(request):
    """Render the landing screen with loader and environment details."""
    if request.method == 'POST':
        form = CsvUploadForm(request.POST, request.FILES)
        if form.is_valid():
            csv_file = request.FILES['csv_file']
            # For now, we'll just create a job and save the file name.
            # Processing will be handled in a future step.
            SkipTraceJob.objects.create(original_file_name=csv_file.name)
            # In a real app, you'd trigger a background task here.
            # For now, we just redirect to the same page.
            return redirect('index')
    else:
        form = CsvUploadForm()

    host_name = request.get_host().lower()
    agent_brand = "AppWizzy" if host_name == "appwizzy.com" else "Flatlogic"
    now = timezone.now()
    
    jobs = SkipTraceJob.objects.all().order_by('-created_at')

    context = {
        "project_name": "Skip Tracing",
        "agent_brand": agent_brand,
        "django_version": django_version(),
        "python_version": platform.python_version(),
        "current_time": now,
        "host_name": host_name,
        "project_description": os.getenv("PROJECT_DESCRIPTION", "A simple tool to skip trace contacts from a CSV file."),
        "project_image_url": os.getenv("PROJECT_IMAGE_URL", ""),
        "form": form,
        "jobs": jobs,
    }
    return render(request, "core/index.html", context)

