from microdot import Microdot
from models.scene import Scene
import json

controller = Microdot()
scenes = Scene()

@controller.get('')
async def list_scenes(request):
    """List all scenes."""
    return json.dumps(scenes), 200, {'Content-Type': 'application/json'}

@controller.get('/<id>')
async def get_scene(request, id):
    """Get a specific scene by ID."""
    scene = scenes.read(id)
    if scene:
        return json.dumps(scene), 200, {'Content-Type': 'application/json'}
    return json.dumps({"error": "Scene not found"}), 404

@controller.post('')
async def create_scene(request):
    """Create a new scene."""
    try:
        data = request.json
        scene_id = scenes.create()
        if scenes.update(scene_id, data):
            return json.dumps(scenes.read(scene_id)), 201, {'Content-Type': 'application/json'}
        return json.dumps({"error": "Failed to create scene"}), 400
    except Exception as e:
        return json.dumps({"error": str(e)}), 400

@controller.put('/<id>')
async def update_scene(request, id):
    """Update an existing scene."""
    try:
        data = request.json
        if scenes.update(id, data):
            return json.dumps(scenes.read(id)), 200, {'Content-Type': 'application/json'}
        return json.dumps({"error": "Scene not found"}), 404
    except Exception as e:
        return json.dumps({"error": str(e)}), 400

@controller.delete('/<id>')
async def delete_scene(request, id):
    """Delete a scene."""
    if scenes.delete(id):
        return json.dumps({"message": "Scene deleted successfully"}), 200
    return json.dumps({"error": "Scene not found"}), 404
