#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>

#define BLOCK_FRAMES 256       // ~16 ms at 16 kHz
#define CHANNELS 1             // adjust to 2 if stereo
#define SAMPLE_RATE 16000
#define BYTES_PER_SAMPLE 2     // s16le

int main(void) {
    int fd = open("/tmp/esp32_audio", O_RDONLY);
    if (fd < 0) {
        perror("open");
        return 1;
    }

    size_t block_bytes = BLOCK_FRAMES * CHANNELS * BYTES_PER_SAMPLE;
    int16_t *buffer = malloc(block_bytes);

    if (!buffer) {
        perror("malloc");
        close(fd);
        return 1;
    }

    while (1) {
        ssize_t n = read(fd, buffer, block_bytes);
        if (n <= 0) {
            usleep(1000);
            continue;
        }

        // compute peak
        int16_t peak = 0;
        for (ssize_t i = 0; i < n / 2; i++) {
            int16_t sample = buffer[i];
            if (sample < 0) sample = -sample;
            if (sample > peak) peak = sample;
        }

        // scale to 50 chars
        int bar_len = (peak * 50) / 32767;
        char bar[51];
        memset(bar, '#', bar_len);
        bar[bar_len] = '\0';

        printf("[%s]\r", bar);
        fflush(stdout);
    }

    free(buffer);
    close(fd);
    return 0;
}
