import json import random import string import uuid import os from django.shortcuts import render, redirect, get_object_or_404 from django.contrib import messages from django.utils import timezone from datetime import timedelta from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt from django.core.management import call_command from .models import GameProject, UserSession, AdminConfig, RentalOption, UserPurchase from ai.local_ai_api import LocalAIApi from .pexels import fetch_first # Helper to check authentication def get_auth_status(request): is_admin = request.session.get('is_admin', False) user_code = request.session.get('user_code') user = None if user_code: user = UserSession.objects.filter(access_code=user_code).first() return is_admin, user def index(request): is_admin, user = get_auth_status(request) if is_admin: return redirect('admin_dashboard') if user: return redirect('catalog') return render(request, 'core/index.html', {'title': 'Acesso'}) def admin_login(request): if request.method == 'POST': key = request.POST.get('private_key') if AdminConfig.objects.filter(private_key=key).exists(): request.session['is_admin'] = True request.session['user_code'] = None return redirect('admin_dashboard') messages.error(request, 'Chave Privada Inválida.') return render(request, 'core/admin_login.html', {'title': 'Admin Login'}) def generate_code(request): if request.method == 'POST': phone = request.POST.get('phone') code = ''.join(random.choices(string.digits, k=6)) while UserSession.objects.filter(access_code=code).exists(): code = ''.join(random.choices(string.digits, k=6)) UserSession.objects.create(access_code=code, phone_number=phone) request.session['user_code'] = code request.session['is_admin'] = False messages.success(request, f'Seu código de acesso é: {code}. Guarde-o bem!') return redirect('catalog') return redirect('index') def recover_code(request): if request.method == 'POST': phone = request.POST.get('phone') user = UserSession.objects.filter(phone_number=phone).first() if user: request.session['user_code'] = user.access_code messages.success(request, f'Bem-vindo de volta! Seu código {user.access_code} foi recuperado.') return redirect('catalog') messages.error(request, 'Nenhum código encontrado para este telefone.') return redirect('index') def logout(request): request.session.flush() return redirect('index') # AI Helper - Autonomously generates full games with story and code def generate_game_script(title, prompt="", genre="arcade"): system_prompt = ( "You are the Ultimate Autonomous AI Game Developer and Storyteller. Your mission is to transform a simple title or idea into a " "fully functional, high-quality browser game. You are responsible for the entire development lifecycle:\n" "1. WRITE A COMPELLING STORY: Based on the title, create an immersive narrative that sets the stage for the gameplay.\n" "2. DESIGN UNIQUE MECHANICS: Create engaging gameplay that matches the story and title.\n" "3. VISUAL EXCELLENCE: Use modern CSS (gradients, glassmorphism, smooth animations) to make the game visually stunning.\n" "4. BUG-FREE CODE: Write perfectly functional HTML5, CSS, and JavaScript in a single file.\n" "5. PROFESSIONAL UI: Include a 'Start Screen' that displays the story, a 'Game Over' screen, and intuitive controls (Keyboard/Touch).\n" "6. AUTONOMOUS CORRECTION: You MUST review your own logic and fix any potential bugs or syntax errors before providing the final code.\n" "Return ONLY the complete HTML5 code starting with ." ) full_query = f"Game Title: {title}. Description/Idea: {prompt}. Genre: {genre}." user_prompt = f"Act as an autonomous developer. Develop a complete browser game (Story + Code) for: {full_query}. Ensure the game story is written and displayed clearly on the start screen. Use Portuguese (Brazil) for all in-game text, story, and instructions." # Step 1: Initial Generation response = LocalAIApi.create_response({ "input": [ {"role": "system", "content": system_prompt}, {"role": "user", "content": user_prompt}, ], }) if not response.get("success"): return None code = LocalAIApi.extract_text(response) # Step 2: Autonomous Bug Correction correction_prompt = ( "Review the HTML/JS code below. Ensure it is fully functional, has no syntax errors, and the game loop works correctly. " "Fix any issues and return the final, polished HTML5 code. ONLY RETURN THE CODE.\n\n" f"CODE TO REVIEW:\n{code}" ) corrected_response = LocalAIApi.create_response({ "input": [ {"role": "system", "content": "You are a senior debugger and optimizer. Your goal is to ensure the code is 100% bug-free and optimized."}, {"role": "user", "content": correction_prompt}, ], }) if corrected_response.get("success"): final_code = LocalAIApi.extract_text(corrected_response) if "