"""Audio device selection — DDJ-FLX first."""
from __future__ import annotations

import sounddevice as sd

LIVE_SR = 48000
WANT_IN = ("FLX", "DDJ-FLX", "DDJ", "Pioneer")
WANT_IN_FB = ("BlackHole 2ch",)
FORBID_IN = ("BlackHole 16ch", "BlackHole 64ch", "BlackHole 256ch")
WANT_OUT = (
    "External Headphones",
    "Headphones",
    "MacBook Air Speakers",
    "MacBook Pro Speakers",
    "Built-in Output",
    "MacBook Speakers",
)
FORBID_OUT = ("BlackHole", "Aggregate", "Multi-Output", "Multi-Out")


def _list(kind: str, forbid: tuple[str, ...]) -> list[tuple[int, str]]:
    out: list[tuple[int, str]] = []
    for i, d in enumerate(sd.query_devices()):
        ch = d["max_input_channels"] if kind == "in" else d["max_output_channels"]
        if ch < 1:
            continue
        name = d["name"]
        if any(f.lower() in name.lower() for f in forbid):
            continue
        out.append((i, name))
    return out


def pick_in() -> tuple[int, str]:
    found = _list("in", FORBID_IN)
    for want in WANT_IN + WANT_IN_FB:
        for i, name in found:
            if want.lower() in name.lower():
                return i, name
    if found:
        return found[0]
    raise RuntimeError("No input device")


def pick_out() -> tuple[int, str]:
    found = _list("out", FORBID_OUT)
    for want in WANT_OUT:
        for i, name in found:
            if want.lower() in name.lower():
                return i, name
    if found:
        return found[0]
    raise RuntimeError("No output device")


def is_ddj(name: str) -> bool:
    low = name.lower()
    return any(x in low for x in ("ddj", "flx", "pioneer"))
