import os
import platform

from django import get_version as django_version
from django.shortcuts import render
from django.utils import timezone
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
import json
from .models import Score


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)


@csrf_exempt
def score_create(request):
    if request.method == 'POST':
        data = json.loads(request.body)
        score = Score.objects.create(
            player_name=data.get('player_name', 'Anonymous'),
            score=data.get('score', 0)
        )
        return JsonResponse({'status': 'success', 'score_id': score.id})
    return JsonResponse({'status': 'error', 'message': 'Invalid request method'}, status=405)

def score_list(request):
    scores = Score.objects.all().order_by('-score')[:10]
    data = list(scores.values('player_name', 'score'))
    return JsonResponse(data, safe=False)
