#include "keyboard_stdio.h"
#include "pico/stdio/driver.h"
#include "pico/sync.h"

#define KBD_BUF_SIZE 128

// Circular buffer for keyboard input
static char kbd_buf[KBD_BUF_SIZE];
static volatile int write_idx = 0;
static volatile int read_idx = 0;
static critical_section_t kbd_crit;

void keyboard_stdio_push_char(char c) {
    critical_section_enter_blocking(&kbd_crit);
    int next_write = (write_idx + 1) % KBD_BUF_SIZE;
    if (next_write != read_idx) { // Only write if not full
        kbd_buf[write_idx] = c;
        write_idx = next_write;
    }
    critical_section_exit(&kbd_crit);
}

static int keyboard_in_chars(char *buf, int len) {
    int count = 0;
    critical_section_enter_blocking(&kbd_crit);
    while (count < len && read_idx != write_idx) {
        buf[count++] = kbd_buf[read_idx];
        read_idx = (read_idx + 1) % KBD_BUF_SIZE;
    }
    critical_section_exit(&kbd_crit);
    return count > 0 ? count : PICO_ERROR_NO_DATA;
}

static stdio_driver_t kbd_driver = {
    .out_chars = NULL,
    .out_flush = NULL,
    .in_chars = keyboard_in_chars,
#if PICO_STDIO_ENABLE_CRLF_SUPPORT
    .crlf_enabled = false
#endif
};

void keyboard_stdio_init(void) {
    critical_section_init(&kbd_crit);
    stdio_set_driver_enabled(&kbd_driver, true);
}
