import random
from django.core.management.base import BaseCommand
from core.models import GameProject

class Command(BaseCommand):
    help = 'Populates the database with a variety of online and traditional games'

    def handle(self, *args, **options):
        game_data = [
            {
                "title": "Space Invaders Pro",
                "genre": "shooter",
                "description": "Defenda a terra contra invasores espaciais nesta versão clássica.",
                "type": "script"
            },
            {
                "title": "Neon Runner",
                "genre": "runner",
                "description": "Corra por uma cidade futurista desviando de obstáculos neon.",
                "type": "script"
            },
            {
                "title": "Sudoku Online",
                "genre": "puzzle",
                "description": "Desafie sua mente com milhares de níveis de Sudoku.",
                "type": "online",
                "url": "https://www.247sudoku.com/"
            },
            {
                "title": "Classic Solitaire",
                "genre": "puzzle",
                "description": "O jogo de cartas mais popular de todos os tempos.",
                "type": "online",
                "url": "https://www.247solitaire.com/"
            },
            {
                "title": "Snake Classic",
                "genre": "arcade",
                "description": "O jogo da cobrinha original em versão moderna.",
                "type": "script"
            },
            {
                "title": "Tower Building",
                "genre": "puzzle",
                "description": "Construa a torre mais alta que puder!",
                "type": "online",
                "url": "https://www.crazygames.com/embed/tower-building"
            },
            {
                "title": "2048",
                "genre": "puzzle",
                "description": "Combine os blocos para chegar ao número 2048.",
                "type": "online",
                "url": "https://play2048.co/"
            }
        ]

        # Categories for variety
        categories = ['Ação', 'Aventura', 'Puzzle', 'Esportes', 'Estratégia', 'Arcade', 'Luta', 'Corrida']
        
        count = 0
        # Create base games
        for data in game_data:
            if not GameProject.objects.filter(title=data['title']).exists():
                GameProject.objects.create(
                    title=data['title'],
                    genre=data['genre'],
                    description=data['description'],
                    external_url=data.get('url', ''),
                    script_code=self.get_placeholder_script(data['title']) if data['type'] == 'script' else '',
                    is_active=True
                )
                count += 1

        # Generate 50 more "simulated" games to show scale
        for i in range(1, 51):
            title = f"Jogo Online {i} - {random.choice(categories)}"
            if not GameProject.objects.filter(title=title).exists():
                GameProject.objects.create(
                    title=title,
                    genre='online',
                    description=f"Um emocionante jogo de {title.split(' - ')[1]} para jogar online.",
                    external_url="https://www.crazygames.com/embed/shell-shockers" if i % 2 == 0 else "https://www.crazygames.com/embed/moto-x3m",
                    is_active=True
                )
                count += 1

        self.stdout.write(self.style.SUCCESS(f'Sucesso! {count} novos jogos adicionados ao catálogo.'))

    def get_placeholder_script(self, title):
        return f"""
<!DOCTYPE html>
<html>
<head>
    <style>
        body {{ margin: 0; background: #000; color: #fff; font-family: sans-serif; display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100vh; overflow: hidden; }}
        canvas {{ border: 2px solid #333; max-width: 100%; }}
        #ui {{ position: absolute; top: 20px; }}
    </style>
</head>
<body>
    <div id="ui">Score: <span id="score">0</span></div>
    <canvas id="gameCanvas" width="800" height="600"></canvas>
    <script>
        const canvas = document.getElementById('gameCanvas');
        const ctx = canvas.getContext('2d');
        let score = 0;
        let x = 400, y = 300;
        
        function draw() {{
            ctx.fillStyle = 'black';
            ctx.fillRect(0, 0, 800, 600);
            
            ctx.fillStyle = '#00ff00';
            ctx.beginPath();
            ctx.arc(x, y, 20, 0, Math.PI * 2);
            ctx.fill();
            
            ctx.fillStyle = 'white';
            ctx.font = '24px Arial';
            ctx.fillText('Simulação de {title}', 280, 50);
            ctx.fillText('Use as setas para mover', 280, 550);
            
            requestAnimationFrame(draw);
        }}

        window.addEventListener('keydown', (e) => {{
            if (e.key === 'ArrowUp') y -= 10;
            if (e.key === 'ArrowDown') y += 10;
            if (e.key === 'ArrowLeft') x -= 10;
            if (e.key === 'ArrowRight') x += 10;
            score++;
            document.getElementById('score').innerText = score;
        }});

        draw();
    </script>
</body>
</html>
"""
