from microdot import Microdot
from models.pallet import Palette
import json

controller = Microdot()
palettes = Palette()

@controller.get('')
async def list_palettes(request):
    """List all palettes."""
    data = {}
    for pid in palettes.list():
        colors = palettes.read(pid)
        data[pid] = colors
    return json.dumps(data), 200, {'Content-Type': 'application/json'}

@controller.get('/<id>')
async def get_palette(request, id):
    """Get a specific palette by ID."""
    if str(id) in palettes:
        palette = palettes.read(id)
        return json.dumps({"colors": palette or [], "id": str(id)}), 200, {'Content-Type': 'application/json'}
    return json.dumps({"error": "Palette not found"}), 404

@controller.post('')
async def create_palette(request):
    """Create a new palette."""
    try:
        data = request.json or {}
        colors = data.get("colors", None)
        # Palette no longer needs a name; only colors are stored.
        palette_id = palettes.create("", colors)
        created_colors = palettes.read(palette_id) or []
        return json.dumps({"id": str(palette_id), "colors": created_colors}), 201, {'Content-Type': 'application/json'}
    except Exception as e:
        return json.dumps({"error": str(e)}), 400

@controller.put('/<id>')
async def update_palette(request, id):
    """Update an existing palette."""
    try:
        data = request.json or {}
        # Ignore any name field; only colors are relevant.
        if "name" in data:
            data.pop("name", None)
        if palettes.update(id, data):
            colors = palettes.read(id) or []
            return json.dumps({"id": str(id), "colors": colors}), 200, {'Content-Type': 'application/json'}
        return json.dumps({"error": "Palette not found"}), 404
    except Exception as e:
        return json.dumps({"error": str(e)}), 400

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