import time, board, pwmio, digitalio
from adafruit_motor import servo
from adafruit_seesaw.seesaw import Seesaw
from audiomp3 import MP3Decoder
from audiopwmio import PWMAudioOut as AudioOut

i2c = board.I2C()
soil_sensor = Seesaw(i2c, addr=0x36)

speaker = digitalio.DigitalInOut(board.SPEAKER_ENABLE)
speaker.direction = digitalio.Direction.OUTPUT
speaker.value = True
audio = AudioOut(board.SPEAKER)

pwm = pwmio.PWMOut(board.A1, frequency=50)
servo_1 = servo.Servo(pwm, min_pulse=750, max_pulse=2250)

path = "sounds/"
filename = "ribbit2.mp3"
threshold = 600

def read_moisture(sensor):
    moisture = sensor.moisture_read()
    angle = (moisture / 1500) * 180  # Scale to 0-180
    return moisture, angle

def play_mp3(filepath):
    with open(filepath, "rb") as mp3_file:
        decoder = MP3Decoder(mp3_file)
        audio.play(decoder)
        while audio.playing:
            pass


sound_playing = False

while True:
    moisture, angle = read_moisture(soil_sensor)
    print(f"Hi! My Moisture is : {moisture} out of 2000, and my tongue is at: {int(angle)}°")
    servo_1.angle = angle
    if moisture < threshold:
        if not sound_playing:
            play_mp3(path + filename)
            sound_playing = True
    else:
        sound_playing = False
    time.sleep(1)

