import os
import platform

from django import get_version as django_version
from django.contrib.auth import login
from django.contrib.auth.models import User
from django.contrib import messages
from django.shortcuts import render, redirect
from django.utils import timezone

from .models import MachineModel, SparePart, ServiceIntervention, TechnicianProfile


def index(request):
    """Render the landing screen with dashboard stats."""
    host_name = request.get_host().lower()
    agent_brand = "AppWizzy" if host_name == "appwizzy.com" else "Flatlogic"
    now = timezone.now()

    context = {
        "project_name": "Nespresso Repair Assistant",
        "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 guided tool for Nespresso machine repairs."),
        "project_image_url": os.getenv("PROJECT_IMAGE_URL", ""),
        "intervention_count": ServiceIntervention.objects.count(),
        "spare_part_count": SparePart.objects.count(),
        "machine_model_count": MachineModel.objects.count(),
        "pending_interventions": ServiceIntervention.objects.filter(status='PENDING').count(),
    }
    return render(request, "core/index.html", context)


def article_detail(request):
    return render(request, "core/article_detail.html")

def technician_login(request):
    if request.method == 'POST':
        technician_id = request.POST.get('technician')
        pin = request.POST.get('pin')
        
        try:
            user = User.objects.get(id=technician_id, technician_profile__is_technician=True, is_active=True)
            if user.technician_profile.pin == pin:
                login(request, user)
                return redirect('index')
            else:
                messages.error(request, 'PIN incorrecto.')
        except User.DoesNotExist:
            messages.error(request, 'Técnico no encontrado.')
        
        return redirect('technician_login')

    technicians = User.objects.filter(technician_profile__is_technician=True, is_active=True)
    return render(request, 'core/technician_login.html', {'technicians': technicians})
