import board
import busio
import displayio
import terminalio
import i2cdisplaybus
from adafruit_display_text import label
import adafruit_displayio_ssd1306
import digitalio
import pwmio
import time

displayio.release_displays()

i2c = busio.I2C(board.SCL, board.SDA)
try:
    display_bus = i2cdisplaybus.I2CDisplayBus(i2c, device_address=0x3C)
    WIDTH = 128
    HEIGHT = 32
    display = adafruit_displayio_ssd1306.SSD1306(display_bus, width=WIDTH, height=HEIGHT)
except ValueError:
    pass

btn_pin = digitalio.DigitalInOut(board.D0)
btn_pin.direction = digitalio.Direction.INPUT
touch_pin = digitalio.DigitalInOut(board.D1)
touch_pin.direction = digitalio.Direction.INPUT


buzzer_pin = digitalio.DigitalInOut(board.D2)
buzzer_pin.direction = digitalio.Direction.OUTPUT
buzzer_pin.value = True 

OPTIONS = [20, 25, 30, 35, 40]
BREAK_DURATION = 5

main_group = displayio.Group()
display.root_group = main_group
bg_bitmap = displayio.Bitmap(WIDTH, HEIGHT, 1)
bg_palette = displayio.Palette(1)
bg_palette[0] = 0x000000 
bg_sprite = displayio.TileGrid(bg_bitmap, pixel_shader=bg_palette, x=0, y=0)
main_group.append(bg_sprite)
text_area = label.Label(terminalio.FONT, text="INIT", color=0xFFFFFF, scale=2)
text_area.anchor_point = (0.5, 0.5)
text_area.anchored_position = (WIDTH / 2, HEIGHT / 2)
main_group.append(text_area)
status_label = label.Label(terminalio.FONT, text="MODE", color=0xFFFFFF, scale=1, x=0, y=4)
main_group.append(status_label)


def play_tone(frequency, duration):
    global buzzer_pin 
    buzzer_pin.deinit()
    
    tone = pwmio.PWMOut(board.D2, duty_cycle=32768, frequency=frequency, variable_frequency=True)
    time.sleep(duration)
    tone.deinit()
    buzzer_pin = digitalio.DigitalInOut(board.D2)
    buzzer_pin.direction = digitalio.Direction.OUTPUT
    buzzer_pin.value = True 

def play_gentle_tune(tune_type):
    if tune_type == "START":
         play_tone(440, 0.1)
    elif tune_type == "WORK_DONE":
        for note in [523, 659, 784, 1046]:
            play_tone(note, 0.15)
            time.sleep(0.05)
    elif tune_type == "BREAK_DONE":
        for note in [1046, 784, 659, 523]:
            play_tone(note, 0.15)
            time.sleep(0.05)
    elif tune_type == "CLICK":
        play_tone(880, 0.05)

state = "SELECT" 
selected_index = 1 
timer_seconds = 0
last_tick = 0
flash_state = False
last_flash = 0
last_btn = False
last_touch = False

print("PAK OS: Safe Audio Mode")

while True:
    now = time.monotonic()
    current_btn = btn_pin.value
    current_touch = touch_pin.value
    btn_pressed = current_btn and not last_btn
    touch_pressed = current_touch and not last_touch
    
    if state == "SELECT":
        status_label.text = "SET TIME"
        target_mins = OPTIONS[selected_index]
        text_area.text = f"{target_mins} min"
        
        if touch_pressed:
            selected_index = (selected_index + 1) % len(OPTIONS)
            play_gentle_tune("CLICK")
            
        if btn_pressed:
            state = "WORK"
            timer_seconds = target_mins * 60
            last_tick = now
            play_gentle_tune("START")

    elif state == "WORK":
        status_label.text = "FOCUS"
        if now - last_tick >= 1.0:
            timer_seconds -= 1
            last_tick = now
            text_area.text = f"{int(timer_seconds/60):02d}:{timer_seconds%60:02d}"
            
            if timer_seconds <= 0:
                state = "ALARM_WORK"
                play_gentle_tune("WORK_DONE")

    elif state == "ALARM_WORK":
        status_label.text = "DONE!"
        text_area.text = "00:00"
        if now - last_flash > 0.5:
            flash_state = not flash_state
            if flash_state:
                text_area.color = 0x000000
                bg_palette[0] = 0xFFFFFF
            else:
                text_area.color = 0xFFFFFF
                bg_palette[0] = 0x000000
            last_flash = now
            
        if btn_pressed or touch_pressed:
            text_area.color = 0xFFFFFF
            bg_palette[0] = 0x000000
            state = "BREAK"
            timer_seconds = BREAK_DURATION * 60
            last_tick = now
            print("Starting Break")

    elif state == "BREAK":
        status_label.text = "RELAX"
        if now - last_tick >= 1.0:
            timer_seconds -= 1
            last_tick = now
            text_area.text = f"{int(timer_seconds/60):02d}:{timer_seconds%60:02d}"
            
            if timer_seconds <= 0:
                state = "ALARM_BREAK"
                play_gentle_tune("BREAK_DONE")

    elif state == "ALARM_BREAK":
        status_label.text = "BACK2WORK"
        text_area.text = "00:00"
        if now - last_flash > 0.5:
            flash_state = not flash_state
            if flash_state:
                text_area.color = 0x000000
                bg_palette[0] = 0xFFFFFF
            else:
                text_area.color = 0xFFFFFF
                bg_palette[0] = 0x000000
            last_flash = now
            
        if btn_pressed or touch_pressed:
            text_area.color = 0xFFFFFF
            bg_palette[0] = 0x000000
            state = "SELECT"

    last_btn = current_btn
    last_touch = current_touch
    time.sleep(0.05)