"""Main program for ESP32 audio receiver"""
import socket
from config import *
from wifi_manager import connect_wifi
from audio_output import AudioOutput

def main():
    # Connect to WiFi
    connect_wifi(WIFI_SSID, WIFI_PASSWORD)
    
    # Initialize audio output
    audio = AudioOutput(
        bclk_pin=BCLK_PIN,
        ws_pin=WS_PIN,
        data_pin=DATA_PIN,
        sample_rate=SAMPLE_RATE,
        bits=BITS_PER_SAMPLE
    )
    
    # Setup UDP socket
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.bind(('0.0.0.0', UDP_PORT))
    print(f'Listening on port {UDP_PORT}')
    
    try:
        while True:
            try:
                # Receive audio data
                data, addr = sock.recvfrom(BUFFER_SIZE)
                # Play audio through MAX98357A
                audio.write(data)
            except Exception as e:
                print('Error:', e)
    
    finally:
        audio.deinit()
        sock.close()

if __name__ == '__main__':
    main()
