#include <stdbool.h>
#include <stdio.h>
#include "esp_err.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "wendy_core.h"
#include <inttypes.h>
#include "driver/gpio.h"
#include "esp_task_wdt.h"

static TaskHandle_t worker;

static void button_edge(void *argument)
{
    BaseType_t wake = pdFALSE;
    vTaskNotifyGiveFromISR(worker, &wake);
    if (wake) {
        portYIELD_FROM_ISR();
    }
}

static void subscribe_watchdog(void)
{
    esp_err_t status = esp_task_wdt_status(NULL);
    if (status == ESP_ERR_INVALID_STATE) {
        const esp_task_wdt_config_t config = {
            .timeout_ms = 3000, .idle_core_mask = 0, .trigger_panic = true,
        };
        ESP_ERROR_CHECK(esp_task_wdt_init(&config));
        status = ESP_ERR_NOT_FOUND;
    }
    if (status == ESP_ERR_NOT_FOUND) {
        ESP_ERROR_CHECK(esp_task_wdt_add(NULL));
    } else {
        ESP_ERROR_CHECK(status);
    }
}

void app_main(void)
{
    ESP_ERROR_CHECK(wendy_core_init());
    worker = xTaskGetCurrentTaskHandle();
    const gpio_config_t button = {
        .pin_bit_mask = 1ULL << GPIO_NUM_10, .mode = GPIO_MODE_INPUT,
        .pull_up_en = GPIO_PULLUP_ENABLE, .intr_type = GPIO_INTR_NEGEDGE,
    };
    ESP_ERROR_CHECK(gpio_config(&button));
    esp_err_t installed = gpio_install_isr_service(0);
    if (installed != ESP_ERR_INVALID_STATE) {
        ESP_ERROR_CHECK(installed);
    }
    ESP_ERROR_CHECK(gpio_isr_handler_add(GPIO_NUM_10, button_edge, NULL));
    subscribe_watchdog();
    while (true) {
        uint32_t edges = ulTaskNotifyTake(pdTRUE, pdMS_TO_TICKS(100));
        if (edges) {
            printf("Falling edges: %" PRIu32 "\n", edges);
        }
        // Feed only after this bounded work cycle completes.
        ESP_ERROR_CHECK(esp_task_wdt_reset());
    }
}
