from microdot import Microdot
from models.preset import Preset
from models.espnow import ESPNow
from util.espnow_message import build_message, build_preset_dict
import json

controller = Microdot()
presets = Preset()

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

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

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

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

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


@controller.post('/send')
async def send_presets(request):
    """
    Send one or more presets over ESPNow.

    Body JSON:
        {"preset_ids": ["1", "2", ...]}  or  {"ids": ["1", "2", ...]}

    The controller:
      - looks up each preset in the Preset model
      - converts them to API-compliant format
      - splits into <= 240-byte ESPNow messages
      - sends each message to all configured ESPNow peers.
    """
    try:
        data = request.json or {}
    except Exception:
        return json.dumps({"error": "Invalid JSON"}), 400, {'Content-Type': 'application/json'}

    preset_ids = data.get('preset_ids') or data.get('ids')
    if not isinstance(preset_ids, list) or not preset_ids:
        return json.dumps({"error": "preset_ids must be a non-empty list"}), 400, {'Content-Type': 'application/json'}

    # Build API-compliant preset map keyed by preset name
    presets_by_name = {}
    for pid in preset_ids:
        preset_data = presets.read(str(pid))
        if not preset_data:
            continue
        name_key = preset_data.get('name') or str(pid)
        presets_by_name[name_key] = build_preset_dict(preset_data)

    if not presets_by_name:
        return json.dumps({"error": "No matching presets found"}), 404, {'Content-Type': 'application/json'}

    # Use shared ESPNow singleton
    esp = ESPNow()

    async def send_chunk(chunk_presets):
        msg = build_message(presets=chunk_presets)
        await esp.send(msg)

    MAX_BYTES = 240
    entries = list(presets_by_name.items())
    total_presets = len(entries)
    messages_sent = 0

    batch = {}
    last_msg = None
    for name, preset_obj in entries:
        test_batch = dict(batch)
        test_batch[name] = preset_obj
        test_msg = build_message(presets=test_batch)
        size = len(test_msg)

        if size <= MAX_BYTES or not batch:
            batch = test_batch
            last_msg = test_msg
        else:
            await send_chunk(batch)
            messages_sent += 1
            batch = {name: preset_obj}
            last_msg = build_message(presets=batch)

    if batch:
        await send_chunk(batch)
        messages_sent += 1

    return json.dumps({
        "message": "Presets sent via ESPNow",
        "presets_sent": total_presets,
        "messages_sent": messages_sent
    }), 200, {'Content-Type': 'application/json'}

