from microdot import Microdot
from models.squence import Sequence
import json

controller = Microdot()
sequences = Sequence()

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

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

@controller.post('')
async def create_sequence(request):
    """Create a new sequence."""
    try:
        data = request.json or {}
        group_name = data.get("group_name", "")
        preset_names = data.get("presets", None)
        sequence_id = sequences.create(group_name, preset_names)
        if data:
            sequences.update(sequence_id, data)
        return json.dumps(sequences.read(sequence_id)), 201, {'Content-Type': 'application/json'}
    except Exception as e:
        return json.dumps({"error": str(e)}), 400

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

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