import sounddevice as sd, pprint
from auracast.utils.sounddevice_utils import (
    devices_by_backend,
    get_alsa_inputs,
    get_alsa_usb_inputs,
    get_network_pw_inputs,
    refresh_pw_cache,
)

print("PortAudio library:", sd._libname)
print("PortAudio version:", sd.get_portaudio_version())

print("\nHost APIs:")
apis = sd.query_hostapis()
pprint.pprint(apis)

print("\nAll Devices (with host API name):")
devs = sd.query_devices()
for i, d in enumerate(devs):
    ha_name = apis[d['hostapi']]['name'] if isinstance(d.get('hostapi'), int) and d['hostapi'] < len(apis) else '?'
    if d.get('max_input_channels', 0) > 0:
        print(f"IN  {i:>3}: {d['name']}  api={ha_name}  in={d['max_input_channels']}")
    elif d.get('max_output_channels', 0) > 0:
        print(f"OUT {i:>3}: {d['name']}  api={ha_name}  out={d['max_output_channels']}")
    else:
        print(f"DEV {i:>3}: {d['name']}  api={ha_name}  (no I/O)")

print("\nALSA input devices (PortAudio ALSA host):")
for i, d in devices_by_backend('ALSA'):
    if d.get('max_input_channels', 0) > 0:
        print(f"ALSA {i:>3}: {d['name']}  in={d['max_input_channels']}")

print("\nALSA USB-filtered inputs:")
for i, d in get_alsa_usb_inputs():
    print(f"USB  {i:>3}: {d['name']}  in={d['max_input_channels']}")

print("\nRefreshing PipeWire caches...")
try:
    refresh_pw_cache()
except Exception:
    pass

print("PipeWire Network inputs (from cache):")
for i, d in get_network_pw_inputs():
    print(f"NET  {i:>3}: {d['name']}  in={d.get('max_input_channels', 0)}")


