"""Audio device routes: enumerate available audio devices."""

import asyncio

from fastapi import APIRouter

from wled_controller.api.auth import AuthRequired
from wled_controller.core.audio.audio_capture import AudioCaptureManager

router = APIRouter()


@router.get("/api/v1/audio-devices", tags=["Audio"])
async def list_audio_devices(_auth: AuthRequired):
    """List available audio input/output devices for audio-reactive sources.

    Returns a deduped flat list (backward compat) plus a ``by_engine`` dict
    with per-engine device lists (no cross-engine dedup) so the frontend can
    filter by the selected audio template's engine type.
    """
    try:
        devices, by_engine = await asyncio.to_thread(
            lambda: (
                AudioCaptureManager.enumerate_devices(),
                AudioCaptureManager.enumerate_devices_by_engine(),
            )
        )
        return {
            "devices": devices,
            "count": len(devices),
            "by_engine": by_engine,
        }
    except Exception as e:
        return {"devices": [], "count": 0, "by_engine": {}, "error": str(e)}
