import rp2
import time
import math
import os
import json
import _thread
from machine import I2C, Pin, ADC, PWM, freq

# 1. Fixer l'horloge système à 125 MHz
freq(125000000)

# --- CONSTANTES GLOBALES ---
PWM_MAX = 1000
AUDIO_CARRIER = 200.0
DEFAULT_TRANSITION_S = 0.5
MAX_F1_HZ = 40.0

# --- CONFIGURATION MATÉRIELLE ---
i2c = I2C(0, sda=Pin(4), scl=Pin(5), freq=400000)
import sh1106
display = sh1106.SH1106_I2C(128, 64, i2c, addr=0x3C, rotate=180)

SW = Pin(2, Pin.IN, Pin.PULL_UP)

# Initialisation du potentiomètre sur GP26 (ADC0)
pot_adc = ADC(Pin(26))

class RotaryEncoder:
    def __init__(self, clk_pin, dt_pin):
        self.clk = Pin(clk_pin, Pin.IN, Pin.PULL_UP)
        self.dt = Pin(dt_pin, Pin.IN, Pin.PULL_UP)
        self.delta = 0
        self.last_clk = self.clk.value()
        self.clk.irq(trigger=Pin.IRQ_RISING | Pin.IRQ_FALLING, handler=self._irq_handler)

    def _irq_handler(self, pin):
        c = self.clk.value()
        d = self.dt.value()
        if c != self.last_clk:
            if c == 1:
                if d == 0:
                    self.delta += 1
                else:
                    self.delta -= 1
            self.last_clk = c

    def read(self):
        d = self.delta
        self.delta = 0
        return d

encoder = RotaryEncoder(14, 15)

def check_encoder():
    return encoder.read()

import neopixel
np = neopixel.NeoPixel(Pin(16), 1)

def set_neopixel(r, g, b):
    np[0] = (r, g, b)
    np.write()

set_neopixel(0, 0, 0)

PIN_L1 = Pin(8)
PIN_L2 = Pin(9)

# --- SORTIES AUDIO (GP10, GP13 & GP7 Bruit PWM sur Slice 3 indépendante) ---
audio_l = PWM(Pin(10))
audio_r = PWM(Pin(13))
noise_pwm = PWM(Pin(7))  # GP7 accessible sur le bord du Zero (Slice 3)

audio_l.duty_u16(0)
audio_r.duty_u16(0)
noise_pwm.freq(62500)
noise_pwm.duty_u16(0)

last_audio_state = None
last_f1_audio = -1.0

def update_binaural_audio(f1, active):
    global last_audio_state, last_f1_audio
    if active != last_audio_state or (active and abs(f1 - last_f1_audio) > 0.05):
        last_audio_state = active
        last_f1_audio = f1
        if active and f1 >= 0.2:
            f_left = AUDIO_CARRIER - (f1 / 2.0)
            f_right = AUDIO_CARRIER + (f1 / 2.0)
            audio_l.freq(int(f_left))
            audio_r.freq(int(f_right))
            audio_l.duty_u16(32768)
            audio_r.duty_u16(32768)
        else:
            audio_l.duty_u16(0)
            audio_r.duty_u16(0)

# --- PIO PWM ANTI-GLITCH (ZÉRO IMPULSION À 0% ET FLUIDITÉ TOTALE) ---
@rp2.asm_pio(sideset_init=rp2.PIO.OUT_LOW)
def pwm_pio():
    pull(noblock)           .side(0)
    mov(x, osr)
    mov(y, isr)
    label("pwmloop")
    jmp(not_x, "skip_pulse")
    jmp(x_not_y, "skip")
    nop()                   .side(1)
    label("skip")
    label("skip_pulse")
    jmp(y_dec, "pwmloop")

sm_l1 = rp2.StateMachine(0, pwm_pio, freq=20000000, sideset_base=PIN_L1)
sm_l1.put(PWM_MAX)
sm_l1.exec("pull()")
sm_l1.exec("mov(isr, osr)")
sm_l1.put(0)
sm_l1.active(1)

sm_l2 = rp2.StateMachine(1, pwm_pio, freq=20000000, sideset_base=PIN_L2)
sm_l2.put(PWM_MAX)
sm_l2.exec("pull()")
sm_l2.exec("mov(isr, osr)")
sm_l2.put(0)
sm_l2.active(1)

# --- MOTEUR DE BRUIT HAUTE AMPLITUDE & ZÉRO JITTER ---
rng_state = 123456789
pink_acc = 0
brown_val = 32768

def next_random():
    global rng_state
    rng_state = (rng_state * 1103515245 + 12345) & 0x7FFFFFFF
    return rng_state

def update_noise_pwm(active, noise_type):
    global pink_acc, brown_val
    if not active:
        noise_pwm.duty_u16(0)
        return

    r = next_random() & 0xFFFF

    if noise_type == 0:  # Blanc pur
        val = r
    elif noise_type == 1:  # Rose
        pink_acc = ((pink_acc * 7 + r) >> 3) & 0xFFFF
        val = (r >> 1) + (pink_acc >> 1)
    else:  # Brun
        delta = (next_random() & 0x3FF) - 512
        brown_val = brown_val + delta
        brown_val = 32768 + int((brown_val - 32768) * 0.985)
        val = max(0, min(65535, brown_val))

    noise_pwm.duty_u16(val)

# --- PARTAGE D'ÉTAT MULTI-CŒUR ---
audio_lock = _thread.allocate_lock()
shared_audio = {
    "f1": 2.0,
    "i1": 50.0,
    "f2": 1.0,
    "i2": 50.0,
    "duty": 20.0,
    "noise_en": True,
    "noise_type": 1,
    "audio_en": True
}

# --- TÂCHE EXÉCUTÉE EN CONTINU SUR LE CORE 1 (TEMPS RÉEL PUR) ---
def core1_audio_loop():
    global sm_l1, sm_l2
    local_pwm_max = 1000
    phase_l2 = 0.0
    t_ref = time.ticks_us()
    l1_period_start_us = time.ticks_us()
    
    noise_interval_us = 125  # 8 kHz fixe
    next_noise_us = time.ticks_us()
    
    last_l1_val = -1
    last_l2_val = -1
    
    while True:
        try:
            now_us = time.ticks_us()
            
            if time.ticks_diff(now_us, next_noise_us) >= noise_interval_us:
                next_noise_us = time.ticks_add(next_noise_us, noise_interval_us)
                with audio_lock:
                    noise_active = shared_audio["noise_en"]
                    n_type = shared_audio["noise_type"]
                update_noise_pwm(noise_active, n_type)

            dt_us = time.ticks_diff(now_us, t_ref)
            t_ref = now_us
            dt_s = dt_us / 1_000_000.0
            if dt_s > 0.1:
                dt_s = 0.005

            with audio_lock:
                f1 = shared_audio["f1"]
                i1 = shared_audio["i1"]
                f2 = shared_audio["f2"]
                i2 = shared_audio["i2"]
                duty_pct = shared_audio["duty"]
                audio_active = shared_audio["audio_en"]

            update_binaural_audio(f1, audio_active)

            # Stroboscope L1 (GP8)
            if i1 <= 0.05:
                target_l1 = 0
                l1_period_start_us = now_us
            elif f1 >= 0.2:
                period_us = int(1_000_000.0 / f1)
                duty_ratio = max(0.1, min(0.5, duty_pct / 100.0))
                on_us = int(period_us * duty_ratio)
                
                elapsed_in_period = time.ticks_diff(now_us, l1_period_start_us)
                if elapsed_in_period >= period_us:
                    l1_period_start_us = now_us
                    elapsed_in_period = 0
                
                target_l1 = int((i1 / 100.0) * local_pwm_max) if elapsed_in_period < on_us else 0
            elif f1 > 0.05:
                target_l1 = int((i1 / 100.0) * local_pwm_max)
                l1_period_start_us = now_us
            else:
                target_l1 = 0
                l1_period_start_us = now_us

            if target_l1 != last_l1_val:
                if sm_l1.tx_fifo() < 4:
                    sm_l1.put(target_l1)
                    last_l1_val = target_l1

            # Stroboscope L2 (GP9)
            if i2 <= 0.05:
                duty_l2 = 0
            elif f2 >= 0.05:
                phase_l2 = (phase_l2 + f2 * dt_s) % 1.0
                sine_val = (1.0 + math.sin(2.0 * math.pi * phase_l2)) / 2.0
                duty_l2 = int(sine_val * (i2 / 100.0) * local_pwm_max)
            else:
                duty_l2 = int((i2 / 100.0) * local_pwm_max)
            
            if duty_l2 != last_l2_val:
                if sm_l2.tx_fifo() < 4:
                    sm_l2.put(duty_l2)
                    last_l2_val = duty_l2
            
            # NeoPixel (GP16)
            g_val = int((i2 / 100.0) * 255)
            set_neopixel(0, g_val, 0)

        except Exception:
            pass

# --- CONFIGURATION ---
CONFIG_FILE = "conf_luxia.json"

def load_config():
    default_config = {
        "file": "commands.txt",
        "manual_vals": [2.0, 50.0, 1.0, 50.0, 20.0],
        "noise_enabled": True,
        "audio_enabled": True,
        "noise_type": 1
    }
    try:
        if CONFIG_FILE in os.listdir():
            with open(CONFIG_FILE, "r") as f:
                data = json.load(f)
                if "file" not in data: data["file"] = default_config["file"]
                if "manual_vals" not in data or len(data["manual_vals"]) < 5: data["manual_vals"] = default_config["manual_vals"]
                if "noise_enabled" not in data: data["noise_enabled"] = True
                if "audio_enabled" not in data: data["audio_enabled"] = True
                if "noise_type" not in data: data["noise_type"] = 1
                return data
    except Exception:
        pass
    return default_config

def save_config(filename, manual_vals, noise_enabled, audio_enabled, noise_type):
    data = {
        "file": filename,
        "manual_vals": manual_vals,
        "noise_enabled": noise_enabled,
        "audio_enabled": audio_enabled,
        "noise_type": noise_type
    }
    try:
        with open(CONFIG_FILE, "w") as f:
            json.dump(data, f)
        return True
    except Exception:
        return False

config = load_config()
current_file = config["file"]
manual_vals = config["manual_vals"]
noise_enabled = config["noise_enabled"]
saved_audio_enabled = config.get("audio_enabled", True)
saved_noise_type = config.get("noise_type", 1)

def read_button_with_long_press():
    if SW.value() == 0:
        t_start = time.ticks_ms()
        while SW.value() == 0:
            if time.ticks_diff(time.ticks_ms(), t_start) > 1000:
                while SW.value() == 0:
                    pass
                return 2
            time.sleep_ms(10)
        return 1
    return 0

def get_txt_files():
    files = [f for f in os.listdir() if f.endswith(".txt") and f != CONFIG_FILE]
    return files if files else ["commands.txt"]

def load_commands(filename):
    cmds = []
    has_loop = False
    current_label = ""
    global_transition = DEFAULT_TRANSITION_S
    
    try:
        with open(filename, "r") as f:
            for line in f:
                if "#" in line: line = line.split("#")[0]
                stripped = line.strip()
                if not stripped: continue
                
                if stripped.upper().startswith("TRANS:"):
                    try: global_transition = float(stripped.split(":")[1].strip())
                    except ValueError: pass
                    continue
                    
                if stripped.startswith(">"):
                    current_label = stripped[1:].strip()
                    continue
                if stripped.upper() == "LOOP":
                    has_loop = True
                    continue
                
                parts = [x.strip() for x in stripped.split(",") if x.strip()]
                if len(parts) >= 5:
                    try:
                        dur = max(0.1, float(parts[0]))
                        f1 = max(0.0, min(MAX_F1_HZ, float(parts[1])))
                        i1 = max(0.0, min(100.0, float(parts[2])))
                        f2 = max(0.0, float(parts[3]))
                        i2 = max(0.0, min(100.0, float(parts[4])))
                        
                        duty_val = None
                        trans_val = global_transition
                        step_audio = True
                        step_noise_type = None
                        step_noise_en = None
                        
                        for p in parts[5:]:
                            p_upper = p.upper()
                            if p_upper in ("OFF", "MUTED", "MUTE"): step_audio = False
                            elif p_upper in ("ON", "SOUND"): step_audio = True
                            elif p_upper in ("BLANC", "WHITE"): 
                                step_noise_type = 0
                                step_noise_en = True
                            elif p_upper in ("ROSE", "PINK"): 
                                step_noise_type = 1
                                step_noise_en = True
                            elif p_upper in ("BRUN", "BROWN"): 
                                step_noise_type = 2
                                step_noise_en = True
                            elif p_upper in ("NOISE_OFF", "BRUIT_OFF"):
                                step_noise_en = False
                            elif p_upper in ("NOISE_ON", "BRUIT_ON"):
                                step_noise_en = True
                            else:
                                try:
                                    val = float(p)
                                    if duty_val is None and p == parts[5]: duty_val = max(10.0, min(50.0, val))
                                    else: trans_val = max(0.0, val)
                                except ValueError: pass
                        
                        cmds.append({
                            "dur": dur, "f1": f1, "i1": i1, "f2": f2, "i2": i2,
                            "duty": duty_val, "trans": trans_val, "audio": step_audio,
                            "noise_type": step_noise_type, "noise_en": step_noise_en, "label": current_label
                        })
                    except ValueError: pass
    except Exception: pass
    return cmds, has_loop

# --- MODE PROGRAMME ---
def run_program_mode(filename):
    global noise_enabled, saved_noise_type
    commands, has_loop = load_commands(filename)
    if not commands:
        display.fill(0)
        display.text("Fichier vide/invalide", 0, 20, 1)
        display.show()
        time.sleep(2)
        return

    cur_f1, cur_i1 = 0.0, 0.0
    cur_f2, cur_i2 = 0.1, 0.0
    last_display_ms = time.ticks_ms()

    try:
        while True:
            for cmd in commands:
                start_f1, start_i1 = cur_f1, cur_i1
                start_f2, start_i2 = cur_f2, cur_i2
                target_f1, target_i1 = cmd["f1"], cmd["i1"]
                target_f2, target_i2 = cmd["f2"], cmd["i2"]
                step_duty = cmd["duty"] if cmd["duty"] is not None else manual_vals[4]
                step_trans = cmd["trans"]
                step_audio = cmd["audio"]
                step_noise_type = cmd["noise_type"] if cmd["noise_type"] is not None else saved_noise_type
                step_noise_en = cmd["noise_en"] if cmd["noise_en"] is not None else noise_enabled
                
                step_label = cmd["label"]
                dur_s = cmd["dur"]
                dur_us = int(dur_s * 1_000_000)
                trans_us = int(min(step_trans, dur_s) * 1_000_000)
                step_start_us = time.ticks_us()

                while True:
                    now_us = time.ticks_us()
                    elapsed_us = time.ticks_diff(now_us, step_start_us)
                    if elapsed_us >= dur_us: break

                    if read_button_with_long_press() > 0: raise KeyboardInterrupt

                    elapsed_sec = elapsed_us / 1_000_000.0
                    rem_s = max(0.0, dur_s - elapsed_sec)
                    alpha = (elapsed_us / trans_us) if (elapsed_us < trans_us and trans_us > 0) else 1.0

                    cur_f1 = start_f1 + (target_f1 - start_f1) * alpha
                    cur_i1 = start_i1 + (target_i1 - start_i1) * alpha
                    cur_f2 = start_f2 + (target_f2 - start_f2) * alpha
                    cur_i2 = start_i2 + (target_i2 - start_i2) * alpha

                    with audio_lock:
                        shared_audio["f1"] = cur_f1
                        shared_audio["i1"] = cur_i1
                        shared_audio["f2"] = cur_f2
                        shared_audio["i2"] = cur_i2
                        shared_audio["duty"] = step_duty
                        shared_audio["noise_en"] = step_noise_en
                        shared_audio["noise_type"] = step_noise_type
                        shared_audio["audio_en"] = step_audio

                    now_ms = time.ticks_ms()
                    if time.ticks_diff(now_ms, last_display_ms) >= 40:
                        last_display_ms = now_ms
                        f1_str = f"{cur_f1:4.1f}Hz" if step_audio else f"{cur_f1:4.1f}Hz(M)"
                        f2_str = f"{cur_f2:3.1f}Hz" if step_audio else f"{cur_f2:3.1f}Hz(M)"

                        display.fill(0)
                        display.text(f"Fic: {filename[:10]}", 0, 0, 1)
                        if step_label: display.text(f"{step_label[:16]}", 0, 10, 1)
                        display.text(f"L1: {f1_str} {cur_i1:3.0f}%", 0, 20, 1)
                        display.text(f"Dt: {step_duty:2.0f}%", 0, 30, 1)
                        display.text(f"L2: {f2_str} {cur_i2:3.0f}%", 0, 40, 1)
                        display.text(f"Rest: {rem_s:4.1f}s", 0, 50, 1)
                        display.show()

                    time.sleep_ms(10)

            if not has_loop: break

    except KeyboardInterrupt: pass
    
    with audio_lock:
        shared_audio["f1"] = 0.0
        shared_audio["i1"] = 0.0
        shared_audio["f2"] = 0.1
        shared_audio["i2"] = 0.0
        shared_audio["noise_en"] = False

    display.fill(0)
    display.text("Programme arrete", 0, 24, 1)
    display.show()
    time.sleep(1)

# --- MODE MANUEL ---
def manual_mode():
    global manual_vals, current_file, noise_enabled, saved_audio_enabled, saved_noise_type
    
    menu_level = 0
    sub_idx = 0
    audio_enabled = saved_audio_enabled
    local_noise_en = noise_enabled
    n_type = saved_noise_type
    noise_names = ["Blanc", "Rose", "Brun"]
    last_display_ms = time.ticks_ms()

    actual_f1 = manual_vals[0]
    actual_i1 = manual_vals[1]
    actual_f2 = manual_vals[2]
    actual_i2 = manual_vals[3]
    duty_val = manual_vals[4]

    target_i1 = actual_i1
    target_duty = duty_val
    target_f2 = actual_f2
    target_i2 = actual_i2

    while True:
        btn = read_button_with_long_press()
        if btn == 2:
            break
        elif btn == 1:
            if menu_level == 0:
                if sub_idx == 0: menu_level = 1; sub_idx = 0
                elif sub_idx == 1: menu_level = 2; sub_idx = 0
                elif sub_idx == 2: audio_enabled = not audio_enabled
                elif sub_idx == 3: local_noise_en = not local_noise_en
                elif sub_idx == 4: n_type = (n_type + 1) % 3
                elif sub_idx == 5: break
            elif menu_level == 1:
                if sub_idx == 2: menu_level = 0; sub_idx = 0
                else: sub_idx += 1
            elif menu_level == 2:
                if sub_idx == 2: menu_level = 0; sub_idx = 1
                else: sub_idx += 1

        # Lecture ADC avec zone morte de sécurité (dead zone de 2% contre le jitter)
        raw_pot = pot_adc.read_u16()
        fraction = raw_pot / 65535.0
        if fraction < 0.02:
            target_f1 = 0.0
        else:
            target_f1 = ((fraction - 0.02) / 0.98) * MAX_F1_HZ

        actual_f1 += (target_f1 - actual_f1) * 0.2

        delta = check_encoder()
        if delta != 0:
            if menu_level == 0:
                sub_idx = (sub_idx + delta) % 6
            elif menu_level == 1:
                if sub_idx == 0: target_i1 = max(0.0, min(100.0, target_i1 + delta * 5.0))
                elif sub_idx == 1: target_duty = max(10.0, min(50.0, target_duty + delta * 1.0))
                elif sub_idx == 2: sub_idx = (sub_idx + delta) % 3
            elif menu_level == 2:
                if sub_idx == 0: target_f2 = max(0.0, min(10.0, target_f2 + delta * 0.2))
                elif sub_idx == 1: target_i2 = max(0.0, min(100.0, target_i2 + delta * 5.0))
                elif sub_idx == 2: sub_idx = (sub_idx + delta) % 3

        actual_i1 += (target_i1 - actual_i1) * 0.5
        duty_val += (target_duty - duty_val) * 0.5
        actual_f2 += (target_f2 - actual_f2) * 0.5
        actual_i2 += (target_i2 - actual_i2) * 0.5

        manual_vals[0] = actual_f1
        manual_vals[1] = actual_i1
        manual_vals[2] = actual_f2
        manual_vals[3] = actual_i2
        manual_vals[4] = duty_val
        saved_audio_enabled = audio_enabled
        noise_enabled = local_noise_en
        saved_noise_type = n_type

        with audio_lock:
            shared_audio["f1"] = actual_f1
            shared_audio["i1"] = actual_i1
            shared_audio["f2"] = actual_f2
            shared_audio["i2"] = actual_i2
            shared_audio["duty"] = duty_val
            shared_audio["noise_en"] = local_noise_en
            shared_audio["noise_type"] = n_type
            shared_audio["audio_en"] = audio_enabled

        now_ms = time.ticks_ms()
        if time.ticks_diff(now_ms, last_display_ms) >= 40:
            last_display_ms = now_ms
            display.fill(0)

            if menu_level == 0:
                display.text("-- MODE MANUEL --", 0, 0, 1)
                f1_s = f"{actual_f1:4.1f}Hz" if audio_enabled else f"{actual_f1:3.1f}Hz(M)"
                f2_s = f"{actual_f2:3.1f}Hz" if audio_enabled else f"{actual_f2:3.1f}Hz(M)"
                son_s = "ON" if audio_enabled else "OFF"
                noise_s = "ON" if local_noise_en else "OFF"
                items = [
                    f"L1: {f1_s}",
                    f"L2: {f2_s}",
                    f"Son: {son_s}",
                    f"Bruit:{noise_s}",
                    f"Type:{noise_names[n_type]}",
                    "Quitter/Sauver"
                ]
                for i, itm in enumerate(items):
                    p = ">" if i == sub_idx else " "
                    display.text(f"{p} {itm}", 0, 9 + (i * 9), 1)

            elif menu_level == 1:
                display.text("-- REGLAGES L1 --", 0, 0, 1)
                lines = [f"Int : {actual_i1:3.0f}%", f"Duty: {duty_val:2.0f}%", "<- Retour"]
                for i, l in enumerate(lines):
                    p = ">" if i == sub_idx else " "
                    display.text(f"{p} {l}", 0, 16 + (i * 14), 1)

            elif menu_level == 2:
                display.text("-- REGLAGES L2 --", 0, 0, 1)
                lines = [f"Freq: {actual_f2:3.1f}Hz", f"Int : {actual_i2:3.0f}%", "<- Retour"]
                for i, l in enumerate(lines):
                    p = ">" if i == sub_idx else " "
                    display.text(f"{p} {l}", 0, 16 + (i * 14), 1)

            display.show()

        time.sleep_ms(20)

    save_config(current_file, manual_vals, noise_enabled, saved_audio_enabled, saved_noise_type)
    with audio_lock:
        shared_audio["f1"] = 0.0
        shared_audio["i1"] = 0.0
        shared_audio["f2"] = 0.1
        shared_audio["i2"] = 0.0
        shared_audio["noise_en"] = False
        noise_pwm.duty_u16(0)

    display.fill(0)
    display.text("Parametres", 24, 20, 1)
    display.text("sauvegardes !", 16, 32, 1)
    display.show()
    time.sleep(1.0)

# --- MENU PRINCIPAL (Core 0) ---
def main():
    global current_file, manual_vals, noise_enabled, saved_audio_enabled, saved_noise_type
    menu_idx = 1  # Positionné par défaut sur "Run Programme"

    while True:
        with audio_lock:
            shared_audio["f1"] = 0.0
            shared_audio["i1"] = 0.0
            shared_audio["f2"] = 0.1
            shared_audio["i2"] = 0.0
            shared_audio["noise_en"] = False
            noise_pwm.duty_u16(0)

        display.fill(0)
        display.text("-- LUXIA V1.0--", 0, 0, 1)
        
        menu_items = [
            f"{current_file[:13]}", 
            "Run Programme", 
            "Mode Manuel"
        ]
        
        for i, item in enumerate(menu_items):
            prefix = "> " if i == menu_idx else "  "
            display.text(prefix + item, 0, 15 + (i * 14), 1)
        display.show()

        while True:
            delta = check_encoder()
            if delta != 0:
                menu_idx = (menu_idx + delta) % len(menu_items)
                break

            btn = read_button_with_long_press()
            if btn == 1:
                if menu_idx == 0:
                    files = get_txt_files()
                    f_idx = 0
                    scroll_offset = 0
                    max_visible = 4
                    
                    while True:
                        display.fill(0)
                        display.text("-- CHOIX FICHIER --", 0, 0, 1)
                        
                        for i in range(max_visible):
                            file_index = scroll_offset + i
                            if file_index < len(files):
                                f = files[file_index]
                                p = "> " if file_index == f_idx else "  "
                                display.text(p + f, 0, 18 + (i * 12), 1)
                                
                        display.show()

                        d = check_encoder()
                        if d != 0:
                            f_idx = (f_idx + d) % len(files)
                            if f_idx < scroll_offset:
                                scroll_offset = f_idx
                            elif f_idx >= scroll_offset + max_visible:
                                scroll_offset = f_idx - max_visible + 1

                        b = read_button_with_long_press()
                        if b == 1:
                            current_file = files[f_idx]
                            break
                        elif b == 2:
                            break
                    
                    save_config(current_file, manual_vals, noise_enabled, saved_audio_enabled, saved_noise_type)

                elif menu_idx == 1:
                    run_program_mode(current_file)
                elif menu_idx == 2:
                    manual_mode()
                break
            time.sleep_ms(20)

# --- LANCEMENT SÉCURISÉ ---
if __name__ == "__main__":
    _thread.start_new_thread(core1_audio_loop, ())
    main()