import os
import platform
import random

from django import get_version as django_version
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import AuthenticationForm
from django.http import JsonResponse
from django.shortcuts import render, get_object_or_404, redirect
from django.utils import timezone

from .models import Assignment, Exercise, Hint, Submission


def home(request):
    """Render the landing screen with loader and environment details."""
    host_name = request.get_host().lower()
    agent_brand = "AppWizzy" if host_name == "appwizzy.com" else "Flatlogic"
    now = timezone.now()

    context = {
        "project_name": "New Style",
        "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", ""),
        "project_image_url": os.getenv("PROJECT_IMAGE_URL", ""),
    }
    return render(request, "core/index.html", context)


def login_view(request):
    if request.method == 'POST':
        form = AuthenticationForm(request, data=request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            user = authenticate(username=username, password=password)
            if user is not None:
                login(request, user)
                return redirect('core:student_dashboard')
    else:
        form = AuthenticationForm()
    return render(request, 'core/login.html', {'form': form})


def logout_view(request):
    logout(request)
    return redirect('core:login')


@login_required
def student_dashboard(request):
    assignments = Assignment.objects.all()
    return render(request, "core/student_dashboard.html", {"assignments": assignments})


@login_required
def assignment_detail(request, assignment_id):
    assignment = get_object_or_404(Assignment, pk=assignment_id)
    if request.method == 'POST':
        exercise_id = request.POST.get('exercise_id')
        submitted_answer = request.POST.get('answer')
        exercise = get_object_or_404(Exercise, pk=exercise_id)
        submission, created = Submission.objects.get_or_create(
            exercise=exercise,
            student=request.user,
            defaults={'submitted_answer': submitted_answer}
        )
        if not created:
            submission.submitted_answer = submitted_answer
            submission.save()

        if submission.submitted_answer.lower() == exercise.answer.lower():
            submission.is_correct = True
            submission.save()
            # You might want to add a message here
        else:
            submission.is_correct = False
            submission.save()

    return render(request, "core/assignment_detail.html", {"assignment": assignment})


@login_required
def get_hint(request, exercise_id):
    exercise = get_object_or_404(Exercise, pk=exercise_id)
    hints = exercise.hints.all()
    if hints:
        hint = random.choice(hints)
        return JsonResponse({'hint': hint.hint_text})
    return JsonResponse({'hint': 'No hints available for this exercise.'})


@login_required
def call_teacher(request):
    # In a real application, this would trigger a notification to the teacher
    return JsonResponse({'message': 'A teacher has been called to help you.'})

