"""Audio filter registry endpoint."""

from fastapi import APIRouter, Depends

from wled_controller.api.auth import AuthRequired
from wled_controller.api.dependencies import get_audio_processing_template_store
from wled_controller.api.schemas.filters import (
    FilterOptionDefSchema,
    FilterTypeListResponse,
    FilterTypeResponse,
)
from wled_controller.core.audio.filters import AudioFilterRegistry
from wled_controller.storage.audio_processing_template_store import AudioProcessingTemplateStore

router = APIRouter()


@router.get(
    "/api/v1/audio-filters",
    response_model=FilterTypeListResponse,
    tags=["Audio Filters"],
)
async def list_audio_filter_types(
    _auth: AuthRequired,
    apt_store: AudioProcessingTemplateStore = Depends(get_audio_processing_template_store),
):
    """List all available audio filter types and their options schemas."""
    all_filters = AudioFilterRegistry.get_all()

    # Pre-build template choices for the audio_filter_template filter
    template_choices = None
    if apt_store:
        try:
            templates = apt_store.get_all_templates()
            template_choices = [{"value": t.id, "label": t.name} for t in templates]
        except Exception:
            template_choices = []

    responses = []
    for filter_id, filter_cls in all_filters.items():
        schema = filter_cls.get_options_schema()
        opt_schemas = []
        for opt in schema:
            d = opt.to_dict()
            # Dynamically populate template_id choices for audio_filter_template
            if (
                filter_id == "audio_filter_template"
                and opt.key == "template_id"
                and template_choices is not None
            ):
                d["choices"] = template_choices
            opt_schemas.append(FilterOptionDefSchema(**d))
        responses.append(
            FilterTypeResponse(
                filter_id=filter_id,
                filter_name=filter_cls.filter_name,
                options_schema=opt_schemas,
            )
        )

    return FilterTypeListResponse(filters=responses, count=len(responses))
