"""
PFAGD Project Scaffolding
Creates new PFAGD projects from templates
"""

import os
import shutil
from pathlib import Path
from typing import Dict, Any


PROJECT_TEMPLATES = {
    'basic': {
        'name': 'Basic Game Template',
        'description': 'Simple game with main menu and basic scene',
        'files': {
            'main.py': '''"""
Basic PFAGD Game Template
A simple game with menu and gameplay scenes
"""

from pfagd.engine import Game, Scene
from pfagd.ui import Button, Label
from pfagd.assets import AssetManager

class MainMenu(Scene):
    def __init__(self):
        super().__init__("MainMenu")
    
    def on_enter(self):
        # Create title label
        title = Label("My PFAGD Game", pos=(300, 400))
        self.add_widget(title)
        
        # Create start button
        start_button = Button("Start Game", on_press=self.start_game, pos=(350, 300))
        self.add_widget(start_button)
        
        # Create quit button
        quit_button = Button("Quit", on_press=self.quit_game, pos=(350, 250))
        self.add_widget(quit_button)
    
    def start_game(self):
        self.manager.switch_to("GameScene")
    
    def quit_game(self):
        import sys
        sys.exit(0)

class GameScene(Scene):
    def __init__(self):
        super().__init__("GameScene")
        self.player = None
    
    def on_enter(self):
        # Add player sprite
        self.player = self.add_sprite("player.png", pos=(100, 100))
        
        # Add back button
        back_button = Button("Back to Menu", on_press=self.back_to_menu, pos=(10, 10))
        self.add_widget(back_button)
        
        # Add jump button
        jump_button = Button("Jump", on_press=self.player_jump, pos=(650, 10))
        self.add_widget(jump_button)
    
    def update(self, dt):
        # Update player
        if self.player:
            self.player.update(dt)
            
            # Simple gravity
            self.player.velocity[1] += 500 * dt  # Gravity
            
            # Ground collision
            if self.player.pos[1] > 400:
                self.player.pos[1] = 400
                self.player.velocity[1] = 0
    
    def back_to_menu(self):
        self.manager.switch_to("MainMenu")
    
    def player_jump(self):
        if self.player and self.player.pos[1] >= 400:  # On ground
            self.player.jump()

if __name__ == "__main__":
    # Create asset manager
    assets = AssetManager("assets")
    
    # Create game with scenes
    game = Game(
        title="{project_name}",
        start_scene=MainMenu(),
        assets=assets,
        resolution=(800, 600)
    )
    
    # Add game scene
    game.add_scene(GameScene())
    
    # Run the game
    game.run()
''',
            'assets/player.png': None,  # Will create placeholder
            'assets/README.md': '''# Assets Directory

Place your game assets here:
- Images: PNG, JPG, BMP, GIF
- Audio: WAV, MP3, OGG
- Data: JSON, TXT files

PFAGD will automatically optimize these assets for mobile deployment.
''',
            'requirements.txt': '''pfagd>=0.1.0
# Add any additional dependencies here
''',
            'buildozer.spec': '''# Buildozer configuration for Android builds
# Generated by PFAGD

[app]
title = {project_name}
package.name = {package_name}
package.domain = com.example.{package_name}

source.dir = .
source.include_exts = py,png,jpg,kv,atlas,json,txt

version = 0.1
version.regex = __version__ = ['"]([^'"]*?)['"]
version.filename = %(source.dir)s/main.py

[buildozer]
log_level = 2

[android]
permissions = INTERNET,WRITE_EXTERNAL_STORAGE

[garden]
requirements = 

[kivy]
requirements = kivy,kivymd,pillow
''',
            'README.md': '''# {project_name}

A game built with PFAGD (Python for Android Game Development).

## Running the Game

### Desktop
```bash
pfagd run main.py
```

### Android (Build APK)
```bash
pfagd build-android main.py
```

## Development

### Hot Reload (Development Mode)
```bash
pfagd run main.py --hot-reload --debug
```

### Import Assets
```bash
pfagd import-assets assets/
```

## Project Structure

- `main.py` - Main game file
- `assets/` - Game assets (images, audio, data)
- `requirements.txt` - Python dependencies
- `buildozer.spec` - Android build configuration

## Adding Features

### Monetization
```bash
pfagd add-monetization admob
pfagd add-monetization iap
```

### New Scenes
Edit `main.py` and add new Scene classes.

### Assets
Place new assets in the `assets/` directory and run:
```bash
pfagd import-assets assets/
```

Happy game development! 🎮
'''
        }
    },
    
    'platformer': {
        'name': '2D Platformer Template', 
        'description': 'Basic 2D platformer with physics and collision',
        'files': {
            'main.py': '''# 2D Platformer template - Coming soon!
print("2D Platformer template not yet implemented")
''',
            'README.md': '# 2D Platformer Template\n\nComing soon!'
        }
    }
}


def create_project(project_name: str, template: str = 'basic') -> int:
    """Create a new PFAGD project"""
    
    if template not in PROJECT_TEMPLATES:
        print(f"Error: Template '{template}' not found")
        print(f"Available templates: {', '.join(PROJECT_TEMPLATES.keys())}")
        return 1
    
    project_dir = Path(project_name)
    
    if project_dir.exists():
        print(f"Error: Directory '{project_name}' already exists")
        return 1
    
    # Create project directory
    project_dir.mkdir(parents=True)
    
    template_info = PROJECT_TEMPLATES[template]
    print(f"Creating project '{project_name}' using '{template_info['name']}' template...")
    
    # Create files from template
    for file_path, content in template_info['files'].items():
        full_path = project_dir / file_path
        
        # Create parent directories
        full_path.parent.mkdir(parents=True, exist_ok=True)
        
        if content is None:
            # Create placeholder files
            if file_path.endswith('.png'):
                _create_placeholder_image(full_path)
            continue
        
        # Format content with project variables
        formatted_content = content.format(
            project_name=project_name,
            package_name=project_name.lower().replace(' ', '_').replace('-', '_')
        )
        
        # Write file
        with open(full_path, 'w', encoding='utf-8') as f:
            f.write(formatted_content)
    
    print(f"✓ Project '{project_name}' created successfully!")
    print(f"📁 Location: {project_dir.absolute()}")
    print()
    print("Next steps:")
    print(f"  cd {project_name}")
    print("  pfagd run main.py")
    print()
    print("For Android development:")
    print("  pfagd build-android main.py")
    
    return 0


def _create_placeholder_image(file_path: Path):
    """Create a simple placeholder image"""
    try:
        from PIL import Image, ImageDraw, ImageFont
        
        # Create a simple colored rectangle as placeholder
        img = Image.new('RGB', (64, 64), color=(100, 150, 200))
        draw = ImageDraw.Draw(img)
        
        # Draw a simple shape
        draw.rectangle([10, 10, 54, 54], outline=(255, 255, 255), width=2)
        draw.text((20, 25), "P", fill=(255, 255, 255))
        
        img.save(file_path)
        
    except ImportError:
        # If PIL not available, create an empty file
        file_path.touch()
        print(f"Warning: Created empty placeholder for {file_path} (PIL not available)")


def list_templates():
    """List available project templates"""
    print("Available PFAGD project templates:")
    print()
    
    for template_id, info in PROJECT_TEMPLATES.items():
        print(f"  {template_id}")
        print(f"    {info['name']}")
        print(f"    {info['description']}")
        print()


if __name__ == '__main__':
    # Test scaffolding
    import sys
    if len(sys.argv) > 1:
        create_project(sys.argv[1])
    else:
        list_templates()