/*
 * wificap — radio bring-up, channel-plan probing, and the survey/park loop.
 *
 * SPDX-License-Identifier: MIT
 */

#include <string.h>

#include "esp_event.h"
#include "esp_log.h"
#include "esp_wifi.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "nvs_flash.h"

#include "wcap.h"

static const char *TAG = "wcap.scan";

/* Which plan entries this radio, in this regulatory domain, actually accepted. */
static bool s_available[WCAP_N_CHANNELS];
static uint8_t s_n_available;

/* ------------------------------------------------------------------ */

esp_err_t wcap_wifi_start(void)
{
    ESP_ERROR_CHECK(esp_netif_init());
    ESP_ERROR_CHECK(esp_event_loop_create_default());

    wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();

    /*
     * Not ESP_ERROR_CHECK. On a board this tight for RAM, esp_wifi_init() is
     * where an over-ambitious buffer setting lands, and aborting here puts
     * the device in a reboot loop -- which looks like a flashing screen and
     * destroys the log that would have told you it was a memory problem.
     * Failing visibly and staying up is strictly more useful.
     */
    esp_err_t ierr = esp_wifi_init(&cfg);
    if (ierr != ESP_OK) {
        ESP_LOGE(TAG, "esp_wifi_init failed: %s", esp_err_to_name(ierr));
        ESP_LOGE(TAG, "this is almost always DRAM: lower CONFIG_WCAP_RING_BYTES, "
                      "the Wi-Fi rx buffer counts, or the LVGL buffer height");
        return ierr;
    }

    /*
     * WIFI_MODE_NULL is the whole legal posture in one line. The radio comes
     * up with no station and no AP interface, so there is nothing that can
     * associate, probe or answer. Promiscuous receive works regardless.
     */
    ESP_ERROR_CHECK(esp_wifi_set_storage(WIFI_STORAGE_RAM));
    ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_NULL));

    /*
     * Order is load-bearing and the failure is not subtle: country code and
     * band mode are rejected with ESP_ERR_WIFI_NOT_STARTED (0x3002) until
     * esp_wifi_start() has run, which inside an ESP_ERROR_CHECK aborts and
     * puts the board in a reboot loop. The screen draws once per boot, so the
     * symptom is a flashing display rather than anything that looks like a
     * radio problem.
     */
    ESP_ERROR_CHECK(esp_wifi_start());

    /*
     * The default country is "01", world-safe mode, which allows 2.4 GHz only
     * and would silently cost the entire 5 GHz half of this demo. The `false`
     * is ieee80211d: country-code learning from beacons is off, because a
     * sniffer that retunes itself based on what it overhears is a sniffer
     * whose channel plan you cannot reason about.
     *
     * A rejected country code is a warning, not a fatal error -- 2.4 GHz
     * capture still works, and losing the demo entirely over it would be the
     * wrong trade.
     */
    esp_err_t err = esp_wifi_set_country_code(CONFIG_WCAP_COUNTRY, false);
    if (err != ESP_OK) {
        ESP_LOGW(TAG, "country '%s' rejected (%s); 5 GHz may be unavailable",
                 CONFIG_WCAP_COUNTRY, esp_err_to_name(err));
    }

    ESP_ERROR_CHECK(esp_wifi_set_band_mode(WIFI_BAND_MODE_AUTO));

    /* Power save would cost frames mid-handshake. This radio never sleeps. */
    ESP_ERROR_CHECK(esp_wifi_set_ps(WIFI_PS_NONE));

    ESP_LOGI(TAG, "radio up, country %s, mode NULL (receive only)",
             CONFIG_WCAP_COUNTRY);
    return ESP_OK;
}

/*
 * Ask the radio which plan channels it will take, rather than trusting a
 * table. A channel the driver rejects is not a quiet channel - it is a
 * channel that was never listened to, and the two look identical in a
 * capture. The screen draws rejected channels in a different colour for
 * exactly that reason.
 */
static void probe_plan(void)
{
    s_n_available = 0;
    for (int i = 0; i < WCAP_N_CHANNELS; i++) {
        const uint8_t ch = wcap_plan[i];
        wifi_band_t band = wcap_is_5g(ch) ? WIFI_BAND_5G : WIFI_BAND_2G;
        esp_err_t err = esp_wifi_set_band(band);
        if (err == ESP_OK) {
            err = esp_wifi_set_channel(ch, WIFI_SECOND_CHAN_NONE);
        }
        s_available[i] = (err == ESP_OK);
        if (s_available[i]) s_n_available++;
        vTaskDelay(pdMS_TO_TICKS(2));
    }
    ESP_LOGI(TAG, "channel plan: %u of %u available",
             s_n_available, (unsigned)WCAP_N_CHANNELS);
}

/* Tune, handling the band switch a dual-band part needs. */
static bool tune(uint8_t ch)
{
    wifi_band_t band = wcap_is_5g(ch) ? WIFI_BAND_5G : WIFI_BAND_2G;
    if (esp_wifi_set_band(band) != ESP_OK) return false;
    if (esp_wifi_set_channel(ch, WIFI_SECOND_CHAN_NONE) != ESP_OK) return false;
    wcap_set_channel(ch);
    return true;
}

bool wcap_tune(uint8_t ch)
{
    return tune(ch);
}

uint8_t wcap_n_available(void) { return s_n_available; }

/* ------------------------------------------------------------------ */

void wcap_scanner_task(void *arg)
{
    (void)arg;

    probe_plan();
    wcap_plan_publish(s_available, s_n_available);

    /* Start on the first available channel. */
    int idx = 0;
    for (int i = 0; i < WCAP_N_CHANNELS; i++) {
        if (s_available[i]) { idx = i; break; }
    }
    tune(wcap_plan[idx]);

    uint32_t last_fps_ms = wcap_tick_ms();
    uint32_t last_frames = 0;
    uint32_t dwell_start = wcap_tick_ms();

    for (;;) {
        wcap_status_t st;
        wcap_status_get(&st);

        const uint32_t now = wcap_tick_ms();

        /* Frames per second, once a second, for the busy bar. */
        if (now - last_fps_ms >= 1000) {
            const uint32_t d = st.frames_seen - last_frames;
            wcap_fps_publish(d);
            last_frames = st.frames_seen;
            last_fps_ms = now;
        }

        /*
         * Stand down entirely while the active probe is running.
         *
         * Without this the scheduler keeps retuning underneath the
         * supplicant, which floods the log with "STA is scanning or
         * connecting ... cannot set band" and, worse, is trying to move the
         * radio off the target's channel in the middle of an association.
         * The probe needs the radio parked on the AP it is talking to.
         */
        if (st.active) {
            wcap_dwell_publish(1000, (now - dwell_start) % 1000);
            vTaskDelay(pdMS_TO_TICKS(50));
            continue;
        }

        if (st.mode == WCAP_MODE_PARKED) {
            /*
             * Parked. This is the capture mode and it does nothing clever on
             * purpose: it sits on one channel. The dwell bar is repurposed as
             * a one-second sweep so the screen still shows a live board, but
             * the radio does not move. Hopping while waiting for a handshake
             * is the single most common way to miss one -- the four messages
             * complete in a few milliseconds, and a sweep is somewhere else
             * for ~96% of the time.
             */
            wcap_dwell_publish(1000, (now - dwell_start) % 1000);
            vTaskDelay(pdMS_TO_TICKS(20));
            continue;
        }

        /* Survey: dwell, then step to the next available channel. */
        const uint32_t elapsed = now - dwell_start;
        wcap_dwell_publish(CONFIG_WCAP_DWELL_MS, elapsed);

        if (elapsed >= CONFIG_WCAP_DWELL_MS) {
            int next = idx;
            for (int n = 0; n < WCAP_N_CHANNELS; n++) {
                next = (next + 1) % WCAP_N_CHANNELS;
                if (s_available[next]) break;
            }
            if (next <= idx) wcap_sweep_tick();
            idx = next;
            tune(wcap_plan[idx]);
            dwell_start = wcap_tick_ms();
        }

        vTaskDelay(pdMS_TO_TICKS(20));
    }
}
