#include "esp_log.h"
#include "esp_system.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "nvs_flash.h"
#include <stdio.h>
#include <string.h>

#include "ad5940.h"
#include "esp32s3_port.h"
#include "webserver.h"

#define TAG "main"

void app_main(void) {
  // Initialize NVS
  esp_err_t ret = nvs_flash_init();
  if (ret == ESP_ERR_NVS_NO_FREE_PAGES ||
      ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
    ESP_ERROR_CHECK(nvs_flash_erase());
    ret = nvs_flash_init();
  }
  ESP_ERROR_CHECK(ret);

  // Initialize WiFi and Webserver
  ESP_LOGI(TAG, "Initializing WiFi...");
  wifi_init_sta();
  // start_webserver() is now called from IP_EVENT_STA_GOT_IP handler

  // Initialize AD5940 Platform (SPI + GPIOs)
  ESP_LOGI(TAG, "Initializing AD5940 Platform...");
  AD5940_MCUResourceInit(0);

  // Hard-reset the AD5940
  ESP_LOGI(TAG, "AD5940_HWReset...");
  AD5940_HWReset();
  AD5940_Delay10us(25000); // 250ms for LDOs

  // Initialize AD5940 registers
  ESP_LOGI(TAG, "AD5940_Initialize...");
  AD5940_Initialize();

  // Initial log
  web_log("System Started.\nWaiting for commands...\n");

  while (1) {
    if (check_id_requested()) {
      web_log("Executing Check ID...\n");

      // Wakeup AFE (Pulse CS)
      AD5940_CsClr();
      AD5940_Delay10us(10); // 100us pulse
      AD5940_CsSet();
      AD5940_Delay10us(100); // Wait 1ms for wake

      // Read Chip ID
      // Using direct register read if possible, or driver function
      // Assuming AD5940_ReadReg is available in ad5940.c
      uint32_t chip_id = AD5940_ReadReg(REG_AFECON_CHIPID);

      web_log("CHIP ID: 0x%04X\n", chip_id);
      ESP_LOGI(TAG, "CHIP ID: 0x%04X", chip_id);
    }

    vTaskDelay(pdMS_TO_TICKS(100));
  }
}
