import os
import time
import board
import neopixel
from rainbowio import colorwheel

from audiopwmio import PWMAudioOut as AudioOut
from audiomp3 import MP3Decoder

# Simple hardware setup
PIXEL_PIN = board.A1
NUM_PIXELS = 20
AUDIO_PIN = board.A2
AUDIO_PATH = "gamesounds"

# Smooth rainbow motion settings
PIXEL_BRIGHTNESS = 0.2  
FRAME_DELAY = 0.005

pixels = neopixel.NeoPixel(PIXEL_PIN, NUM_PIXELS, brightness=0.2, auto_write=False)
audio = AudioOut(AUDIO_PIN)


def list_sounds(path):
    files = []
    for name in os.listdir(path):
        if name.lower().endswith(".mp3"):
            files.append(name)
    files.sort()
    return files


def rainbow_swirl(step):
    # Smooth moving rainbow across the strip.
    pixels.brightness = PIXEL_BRIGHTNESS
    for i in range(NUM_PIXELS):
        hue = (step + (i * 10)) & 255
        pixels[i] = colorwheel(hue)
    pixels.show()


sound_files = list_sounds(AUDIO_PATH)
print("Sounds found:", sound_files)

if not sound_files:
    print("No .mp3 files found in gamesounds")
    step = 0
    while True:
        rainbow_swirl(step)
        step = (step + 2) & 255
        time.sleep(FRAME_DELAY)

path = AUDIO_PATH + "/" + sound_files[0]
print("Playing:", path)

step = 0
while True:
    rainbow_swirl(step)
    step = (step + 2) & 255
    time.sleep(FRAME_DELAY)

    #To play audio later, uncomment this block:
    with open(path, "rb") as mp3_file:
        decoder = MP3Decoder(mp3_file)
        audio.play(decoder)
        while audio.playing:
            rainbow_swirl(step)
            step = (step + 2) & 255
            time.sleep(FRAME_DELAY)
