// Bench: ESP32-S3 internal temperature sensor via Arduino temperatureRead().
// Flow: first boot -> deep sleep COOL_MIN minutes (chip cools down) -> timer wake ->
// phases below, logging temperature once per second from a separate task.
#include <WiFi.h>
#include "esp_sleep.h"
#include "esp_wifi.h"
#include "xtensa/core-macros.h"

#ifndef COOL_MIN
#define COOL_MIN 15
#endif

struct Phase { const char *name; uint32_t minutes; };
// "idle" phases use delay(); "load2" spins both cores; "wifiscan" scans continuously.
static const Phase PHASES[] = {
  {"idle240", 12}, {"load2", 10}, {"idle240b", 10},
  {"wifiscan", 10}, {"wifioff", 10},
  {"idle160", 10}, {"idle80", 10},
};

static volatile const char *g_phase = "boot";
static volatile bool g_spin = false;
static volatile uint32_t g_sink0, g_sink1;

static void spinner(void *arg) {
  volatile uint32_t *sink = (volatile uint32_t *)arg;
  float x = 1.0001f, y = 0.5f;
  uint32_t last = millis();
  for (;;) {
    if (g_spin) {
      for (int i = 0; i < 10000; i++) { y = y * x + 0.25f; x = x * 0.99999f + 0.00001f; }
      *sink = (uint32_t)(y * 1000);
      // Give IDLE one tick every ~100 ms so the task watchdog stays fed (~1% idle).
      if (millis() - last >= 100) { vTaskDelay(1); last = millis(); }
    } else {
      vTaskDelay(10);
    }
  }
}

static void logger(void *) {
  TickType_t last = xTaskGetTickCount();
  for (;;) {
    float t1 = temperatureRead();
    float sum = 0; float mn = 1e9, mx = -1e9;
    for (int i = 0; i < 16; i++) { float v = temperatureRead(); sum += v; if (v < mn) mn = v; if (v > mx) mx = v; }
    Serial.printf("T,%lu,%s,%u,%.2f,%.2f,%.2f,%.2f\n", (unsigned long)millis(), (const char *)g_phase,
                  (unsigned)getCpuFrequencyMhz(), t1, sum / 16, mn, mx);
    vTaskDelayUntil(&last, pdMS_TO_TICKS(1000));
  }
}

void setup() {
  Serial.begin(115200);
  delay(200);
  if (esp_sleep_get_wakeup_cause() != ESP_SLEEP_WAKEUP_TIMER) {
    Serial.printf("SLEEP,%d\n", COOL_MIN);
    Serial.flush();
    esp_sleep_enable_timer_wakeup((uint64_t)COOL_MIN * 60ULL * 1000000ULL);
    esp_deep_sleep_start();
  }
  // Cost of the first call (driver install) and of later calls, in CPU cycles.
  uint32_t c0 = XTHAL_GET_CCOUNT(); float a = temperatureRead(); uint32_t c1 = XTHAL_GET_CCOUNT();
  float b = temperatureRead(); uint32_t c2 = XTHAL_GET_CCOUNT();
  Serial.printf("WAKE,first=%.2f,%lu cyc,second=%.2f,%lu cyc,mhz=%u\n", a, (unsigned long)(c1 - c0), b,
                (unsigned long)(c2 - c1), (unsigned)getCpuFrequencyMhz());
  xTaskCreatePinnedToCore(spinner, "spin0", 4096, (void *)&g_sink0, 1, NULL, 0);
  xTaskCreatePinnedToCore(spinner, "spin1", 4096, (void *)&g_sink1, 1, NULL, 1);
  xTaskCreatePinnedToCore(logger, "log", 4096, NULL, 5, NULL, 1);
}

void loop() {
  for (const Phase &p : PHASES) {
    g_phase = p.name;
    Serial.printf("PHASE,%lu,%s\n", (unsigned long)millis(), p.name);
#ifdef PHASE_SEC
    uint32_t end = millis() + PHASE_SEC * 1000UL;  // quick functional test
#else
    uint32_t end = millis() + p.minutes * 60000UL;
#endif
    if (!strcmp(p.name, "idle160")) setCpuFrequencyMhz(160);
    if (!strcmp(p.name, "idle80")) setCpuFrequencyMhz(80);
    if (!strcmp(p.name, "load2")) g_spin = true;
    if (!strcmp(p.name, "wifiscan")) { WiFi.mode(WIFI_STA); }
    if (!strcmp(p.name, "wifioff")) { WiFi.mode(WIFI_OFF); }
    while ((int32_t)(millis() - end) < 0) {
      if (!strcmp(p.name, "wifiscan")) {
        int n = WiFi.scanNetworks();
        Serial.printf("SCAN,%lu,%d\n", (unsigned long)millis(), n);
      } else {
        delay(200);
      }
    }
    g_spin = false;
  }
  Serial.println("DONE");
  for (;;) delay(1000);
}
