import pygame
import time
import re

# ------------------------------
# CONFIG
# ------------------------------
OGG_FILE = "../spotify/Golden.ogg"  # your audio file
LRC_FILE = "Golden.lrc.HR"  # your word-level LRC file
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 200
LIGHT_COUNT = 4
LIGHT_WIDTH = SCREEN_WIDTH // LIGHT_COUNT
LIGHT_HEIGHT = SCREEN_HEIGHT
BG_COLOR = (0, 0, 0)
OFF_COLOR = (30, 30, 30)
ON_COLOR = (255, 255, 0)

# ------------------------------
# LOAD LRC WORDS
# ------------------------------
def load_lrc_words(lrc_file):
    """
    Returns list of tuples: (start_time_seconds, end_time_seconds, word)
    """
    words = []
    pattern = re.compile(r"\[(\d+):(\d+\.\d+)\|(\d+):(\d+\.\d+)\](.+)")
    with open(lrc_file, "r", encoding="utf-8") as f:
        for line in f:
            match = pattern.match(line.strip())
            if match:
                start_min = int(match.group(1))
                start_sec = float(match.group(2))
                end_min = int(match.group(3))
                end_sec = float(match.group(4))
                start_time = start_min * 60 + start_sec
                end_time = end_min * 60 + end_sec
                word = match.group(5).strip()
                if word:
                    words.append((start_time, end_time, word))
    return words

words = load_lrc_words(LRC_FILE)

# ------------------------------
# INITIALIZE PYGAME
# ------------------------------
pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Lyrics Light Show")
clock = pygame.time.Clock()

# Load audio
pygame.mixer.init()
pygame.mixer.music.load(OGG_FILE)
pygame.mixer.music.play()
start_time = time.time()

# ------------------------------
# RUN LIGHT SHOW
# ------------------------------
running = True
while running:
    current_time = pygame.mixer.music.get_pos() / 1000.0
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
            pygame.mixer.music.stop()

    # Determine current word
    lights = [0] * LIGHT_COUNT
    for idx, (start, end, text) in enumerate(words):
        if start <= current_time < end:
            # Simple cycling logic across 4 lights
            lights[idx % LIGHT_COUNT] = 1
            break  # only one word active at a time

    # Draw lights
    screen.fill(BG_COLOR)
    for i, state in enumerate(lights):
        color = ON_COLOR if state else OFF_COLOR
        pygame.draw.rect(screen, color, (i*LIGHT_WIDTH, 0, LIGHT_WIDTH, LIGHT_HEIGHT))

    pygame.display.flip()
    clock.tick(60)

pygame.quit()
