#include "wifi_component.h"
#include "esphome/core/defines.h"

#ifdef USE_WIFI
#ifdef USE_ESP8266

#include <user_interface.h>

#include <cassert>
#include <utility>
#include <algorithm>
#ifdef USE_WIFI_WPA2_EAP
#include <wpa2_enterprise.h>
#endif

extern "C" {
#include "lwip/err.h"
#include "lwip/dns.h"
#include "lwip/dhcp.h"
#include "lwip/init.h"  // LWIP_VERSION_
#include "lwip/apps/sntp.h"
#include "lwip/netif.h"  // struct netif
#include <AddrList.h>
#if USE_ARDUINO_VERSION_CODE >= VERSION_CODE(3, 0, 0)
#include "LwipDhcpServer.h"
#if USE_ARDUINO_VERSION_CODE < VERSION_CODE(3, 1, 0)
#include <ESP8266WiFi.h>
#include "ESP8266WiFiAP.h"
#define wifi_softap_set_dhcps_lease(lease) dhcpSoftAP.set_dhcps_lease(lease)
#define wifi_softap_set_dhcps_lease_time(time) dhcpSoftAP.set_dhcps_lease_time(time)
#define wifi_softap_set_dhcps_offer_option(offer, mode) dhcpSoftAP.set_dhcps_offer_option(offer, mode)
#endif
#endif
}

#include "esphome/core/application.h"
#include "esphome/core/hal.h"
#include "esphome/core/helpers.h"
#include "esphome/core/log.h"
#include "esphome/core/progmem.h"
#include "esphome/core/util.h"

namespace esphome::wifi {

static const char *const TAG = "wifi_esp8266";

enum class ESP8266WiFiSTAState : uint8_t {
  IDLE,             // Not connecting
  CONNECTING,       // Connection in progress
  ASSOCIATED,       // Associated to AP, waiting for IP
  CONNECTED,        // Successfully connected with IP
  ERROR_NOT_FOUND,  // AP not found (probe failed)
  ERROR_FAILED,     // Connection failed (auth, timeout, etc.)
};

bool WiFiComponent::wifi_mode_(optional<bool> sta, optional<bool> ap) {
  uint8_t current_mode = wifi_get_opmode();
  bool current_sta = current_mode & 0b01;
  bool current_ap = current_mode & 0b10;
  bool target_sta = sta.value_or(current_sta);
  bool target_ap = ap.value_or(current_ap);
  if (current_sta == target_sta && current_ap == target_ap)
    return true;

  if (target_sta && !current_sta) {
    ESP_LOGV(TAG, "Enabling STA");
  } else if (!target_sta && current_sta) {
    ESP_LOGV(TAG, "Disabling STA");
    // Stop DHCP client when disabling STA
    // See https://github.com/esp8266/Arduino/pull/5703
    wifi_station_dhcpc_stop();
  }
  if (target_ap && !current_ap) {
    ESP_LOGV(TAG, "Enabling AP");
  } else if (!target_ap && current_ap) {
    ESP_LOGV(TAG, "Disabling AP");
  }

  ETS_UART_INTR_DISABLE();
  uint8_t mode = 0;
  if (target_sta)
    mode |= 0b01;
  if (target_ap)
    mode |= 0b10;
  bool ret = wifi_set_opmode_current(mode);
  ETS_UART_INTR_ENABLE();

  if (!ret) {
    ESP_LOGW(TAG, "Set mode failed");
    return false;
  }

  this->ap_started_ = target_ap;

  return ret;
}
bool WiFiComponent::wifi_apply_power_save_() {
  // ESP8266 sleep types have confusing names — LIGHT_SLEEP_T is the MORE aggressive mode.
  // SDK enum: NONE_SLEEP_T=0, LIGHT_SLEEP_T=1, MODEM_SLEEP_T=2
  //   https://github.com/esp8266/Arduino/blob/3.1.2/tools/sdk/include/user_interface.h#L447-L451
  // Arduino ESP32 compat confirms: WIFI_PS_MIN_MODEM=MODEM_SLEEP, WIFI_PS_MAX_MODEM=LIGHT_SLEEP
  //   https://github.com/esp8266/Arduino/blob/3.1.2/libraries/ESP8266WiFi/src/ESP8266WiFiType.h#L53-L55
  sleep_type_t power_save;
  switch (this->power_save_) {
    case WIFI_POWER_SAVE_LIGHT:
      // MODEM_SLEEP_T: only the WiFi modem sleeps between DTIM beacons, CPU stays active.
      // Matches ESP32's WIFI_PS_MIN_MODEM.
      power_save = MODEM_SLEEP_T;
      break;
    case WIFI_POWER_SAVE_HIGH:
      // LIGHT_SLEEP_T: both WiFi modem AND CPU suspend between DTIM beacons.
      // Most aggressive — prevents TCP processing during sleep. Matches ESP32's WIFI_PS_MAX_MODEM.
      // See https://github.com/esphome/esphome/issues/14999
      power_save = LIGHT_SLEEP_T;
      break;
    case WIFI_POWER_SAVE_NONE:
    default:
      power_save = NONE_SLEEP_T;
      break;
  }
  wifi_fpm_auto_sleep_set_in_null_mode(1);
  bool success = wifi_set_sleep_type(power_save);
#ifdef USE_WIFI_POWER_SAVE_LISTENERS
  if (success) {
    for (auto *listener : this->power_save_listeners_) {
      listener->on_wifi_power_save(this->power_save_);
    }
  }
#endif
  return success;
}

#if LWIP_VERSION_MAJOR != 1
/*
  lwip v2 needs to be notified of IP changes, see also
  https://github.com/d-a-v/Arduino/blob/0e7d21e17144cfc5f53c016191daca8723e89ee8/libraries/ESP8266WiFi/src/ESP8266WiFiSTA.cpp#L251
 */
#undef netif_set_addr  // need to call lwIP-v1.4 netif_set_addr()
extern "C" {
struct netif *eagle_lwip_getif(int netif_index);
void netif_set_addr(struct netif *netif, const ip4_addr_t *ip, const ip4_addr_t *netmask, const ip4_addr_t *gw);
};
#endif

bool WiFiComponent::wifi_sta_ip_config_(const optional<ManualIP> &manual_ip) {
  // enable STA
  if (!this->wifi_mode_(true, {}))
    return false;

  enum dhcp_status dhcp_status = wifi_station_dhcpc_status();
  if (!manual_ip.has_value()) {
    // lwIP starts the SNTP client if it gets an SNTP server from DHCP. We don't need the time, and more importantly,
    // the built-in SNTP client has a memory leak in certain situations. Disable this feature.
    // https://github.com/esphome/issues/issues/2299
    sntp_servermode_dhcp(false);

    // Use DHCP client
    if (dhcp_status != DHCP_STARTED) {
      bool ret = wifi_station_dhcpc_start();
      if (!ret) {
        ESP_LOGV(TAG, "Starting DHCP client failed");
      }
      return ret;
    }
    return true;
  }

  bool ret = true;

#if LWIP_VERSION_MAJOR != 1
  // get current->previous IP address
  // (check below)
  ip_info previp{};
  wifi_get_ip_info(STATION_IF, &previp);
#endif

  struct ip_info info {};
  info.ip = manual_ip->static_ip;
  info.gw = manual_ip->gateway;
  info.netmask = manual_ip->subnet;

  if (dhcp_status == DHCP_STARTED) {
    bool dhcp_stop_ret = wifi_station_dhcpc_stop();
    if (!dhcp_stop_ret) {
      ESP_LOGV(TAG, "Stopping DHCP client failed");
      ret = false;
    }
  }
  bool wifi_set_info_ret = wifi_set_ip_info(STATION_IF, &info);
  if (!wifi_set_info_ret) {
    ESP_LOGV(TAG, "Set manual IP info failed");
    ret = false;
  }

  ip_addr_t dns;
  if (manual_ip->dns1.is_set()) {
    dns = manual_ip->dns1;
    dns_setserver(0, &dns);
  }
  if (manual_ip->dns2.is_set()) {
    dns = manual_ip->dns2;
    dns_setserver(1, &dns);
  }

#if LWIP_VERSION_MAJOR != 1
  // trigger address change by calling lwIP-v1.4 api
  // only when ip is already set by other mean (generally dhcp)
  if (previp.ip.addr != 0 && previp.ip.addr != info.ip.addr) {
    netif_set_addr(eagle_lwip_getif(STATION_IF), reinterpret_cast<const ip4_addr_t *>(&info.ip),
                   reinterpret_cast<const ip4_addr_t *>(&info.netmask), reinterpret_cast<const ip4_addr_t *>(&info.gw));
  }
#endif
  return ret;
}

network::IPAddresses WiFiComponent::wifi_sta_ip_addresses() {
  if (!this->has_sta())
    return {};
  network::IPAddresses addresses;
  uint8_t index = 0;
  // addrList enumerates all lwIP netifs, including the SoftAP / fallback hotspot. Filter out
  // the AP address so the STA address is reported as the device IP (see issue #17181).
  struct ip_info ap_ip {};
  wifi_get_ip_info(SOFTAP_IF, &ap_ip);
  network::IPAddress ap_address(&ap_ip.ip);
  bool filter_ap = ap_address.is_set();
  for (auto &addr : addrList) {
    network::IPAddress ip(addr.ipFromNetifNum());
    if (filter_ap && ip == ap_address)
      continue;
    assert(index < addresses.size());
    addresses[index++] = ip;
  }
  return addresses;
}
bool WiFiComponent::wifi_apply_hostname_() {
  const auto &hostname = App.get_name();
  bool ret = wifi_station_set_hostname(const_cast<char *>(hostname.c_str()));
  if (!ret) {
    ESP_LOGV(TAG, "Set hostname failed");
  }

  // Update hostname on all lwIP interfaces so DHCP packets include it.
  // lwIP includes the hostname in DHCP DISCOVER/REQUEST automatically
  // via LWIP_NETIF_HOSTNAME — no dhcp_renew() needed. The hostname is
  // fixed at compile time and never changes at runtime.
  for (netif *intf = netif_list; intf; intf = intf->next) {
#if LWIP_VERSION_MAJOR == 1
    intf->hostname = (char *) wifi_station_get_hostname();
#else
    intf->hostname = wifi_station_get_hostname();
#endif
  }

  return ret;
}

bool WiFiComponent::wifi_sta_connect_(const WiFiAP &ap) {
  // enable STA
  if (!this->wifi_mode_(true, {}))
    return false;

  this->wifi_disconnect_();

  struct station_config conf {};
  memset(&conf, 0, sizeof(conf));
  if (ap.ssid_.size() > sizeof(conf.ssid)) {
    ESP_LOGE(TAG, "SSID too long");
    return false;
  }
  if (ap.password_.size() > sizeof(conf.password)) {
    ESP_LOGE(TAG, "Password too long");
    return false;
  }
  memcpy(reinterpret_cast<char *>(conf.ssid), ap.ssid_.c_str(), ap.ssid_.size());
  memcpy(reinterpret_cast<char *>(conf.password), ap.password_.c_str(), ap.password_.size());

  if (ap.has_bssid()) {
    conf.bssid_set = 1;
    memcpy(conf.bssid, ap.get_bssid().data(), 6);
  } else {
    conf.bssid_set = 0;
  }

#if USE_ARDUINO_VERSION_CODE >= VERSION_CODE(2, 4, 0)
  if (ap.password_.empty()) {
    conf.threshold.authmode = AUTH_OPEN;
  } else {
    // Set threshold based on configured minimum auth mode
    // Note: ESP8266 doesn't support WPA3
    switch (this->min_auth_mode_) {
      case WIFI_MIN_AUTH_MODE_WPA:
        conf.threshold.authmode = AUTH_WPA_PSK;
        break;
      case WIFI_MIN_AUTH_MODE_WPA2:
      case WIFI_MIN_AUTH_MODE_WPA3:  // Fall back to WPA2 for ESP8266
        conf.threshold.authmode = AUTH_WPA2_PSK;
        break;
    }
  }
  conf.threshold.rssi = -127;
#endif

  ETS_UART_INTR_DISABLE();
  bool ret = wifi_station_set_config_current(&conf);
  ETS_UART_INTR_ENABLE();

  if (!ret) {
    ESP_LOGV(TAG, "Set Station config failed");
    return false;
  }

#ifdef USE_WIFI_MANUAL_IP
  if (!this->wifi_sta_ip_config_(ap.get_manual_ip())) {
    return false;
  }
#else
  if (!this->wifi_sta_ip_config_({})) {
    return false;
  }
#endif

  // setup enterprise authentication if required
#ifdef USE_WIFI_WPA2_EAP
  const auto &eap_opt = ap.get_eap();
  if (eap_opt.has_value()) {
    // note: all certificates and keys have to be null terminated. Lengths are appended by +1 to include \0.
    const EAPAuth &eap = *eap_opt;
    ret = wifi_station_set_enterprise_identity((uint8_t *) eap.identity.c_str(), eap.identity.length());
    if (ret) {
      ESP_LOGV(TAG, "esp_wifi_sta_wpa2_ent_set_identity failed: %d", ret);
    }
    int ca_cert_len = strlen(eap.ca_cert);
    int client_cert_len = strlen(eap.client_cert);
    int client_key_len = strlen(eap.client_key);
    if (ca_cert_len) {
      ret = wifi_station_set_enterprise_ca_cert((uint8_t *) eap.ca_cert, ca_cert_len + 1);
      if (ret) {
        ESP_LOGV(TAG, "esp_wifi_sta_wpa2_ent_set_ca_cert failed: %d", ret);
      }
    }
    // workout what type of EAP this is
    // validation is not required as the config tool has already validated it
    if (client_cert_len && client_key_len) {
      // if we have certs, this must be EAP-TLS
      ret = wifi_station_set_enterprise_cert_key((uint8_t *) eap.client_cert, client_cert_len + 1,
                                                 (uint8_t *) eap.client_key, client_key_len + 1,
                                                 (uint8_t *) eap.password.c_str(), eap.password.length());
      if (ret) {
        ESP_LOGV(TAG, "esp_wifi_sta_wpa2_ent_set_cert_key failed: %d", ret);
      }
    } else {
      // in the absence of certs, assume this is username/password based
      ret = wifi_station_set_enterprise_username((uint8_t *) eap.username.c_str(), eap.username.length());
      if (ret) {
        ESP_LOGV(TAG, "esp_wifi_sta_wpa2_ent_set_username failed: %d", ret);
      }
      ret = wifi_station_set_enterprise_password((uint8_t *) eap.password.c_str(), eap.password.length());
      if (ret) {
        ESP_LOGV(TAG, "esp_wifi_sta_wpa2_ent_set_password failed: %d", ret);
      }
    }
    ret = wifi_station_set_wpa2_enterprise_auth(true);
    if (ret) {
      ESP_LOGV(TAG, "esp_wifi_sta_wpa2_ent_enable failed: %d", ret);
    }
  }
#endif  // USE_WIFI_WPA2_EAP

  this->wifi_apply_hostname_();

  // Reset flags, do this _before_ wifi_station_connect as the callback method
  // may be called from wifi_station_connect
  this->sta_state_ = static_cast<uint8_t>(ESP8266WiFiSTAState::CONNECTING);

  ETS_UART_INTR_DISABLE();
  ret = wifi_station_connect();
  ETS_UART_INTR_ENABLE();
  if (!ret) {
    ESP_LOGV(TAG, "wifi_station_connect failed");
    return false;
  }

#if USE_NETWORK_IPV6
  bool connected = false;
  while (!connected) {
    uint8_t ipv6_addr_count = 0;
    for (auto addr : addrList) {
      char ip_buf[network::IP_ADDRESS_BUFFER_SIZE];
      ESP_LOGV(TAG, "Address %s", network::IPAddress(addr.ipFromNetifNum()).str_to(ip_buf));
      if (addr.isV6()) {
        ipv6_addr_count++;
      }
    }
    delay(500);  // NOLINT
    connected = (ipv6_addr_count >= USE_NETWORK_MIN_IPV6_ADDR_COUNT);
  }
#endif /* USE_NETWORK_IPV6 */

  if (ap.has_channel()) {
    ret = wifi_set_channel(ap.get_channel());
    if (!ret) {
      ESP_LOGV(TAG, "wifi_set_channel failed");
      return false;
    }
  }

  return true;
}

class WiFiMockClass : public ESP8266WiFiGenericClass {
 public:
  static void _event_callback(void *event) { ESP8266WiFiGenericClass::_eventCallback(event); }  // NOLINT
};

// Auth mode strings indexed by AUTH_* constants (0-4), with UNKNOWN at last index
// Static asserts verify the SDK constants are contiguous as expected
static_assert(AUTH_OPEN == 0 && AUTH_WEP == 1 && AUTH_WPA_PSK == 2 && AUTH_WPA2_PSK == 3 && AUTH_WPA_WPA2_PSK == 4,
              "AUTH_* constants are not contiguous");
PROGMEM_STRING_TABLE(AuthModeStrings, "OPEN", "WEP", "WPA PSK", "WPA2 PSK", "WPA/WPA2 PSK", "UNKNOWN");

const LogString *get_auth_mode_str(uint8_t mode) {
  return AuthModeStrings::get_log_str(mode, AuthModeStrings::LAST_INDEX);
}

// WiFi op mode strings indexed by WIFI_* constants (0-3), with UNKNOWN at last index
static_assert(WIFI_OFF == 0 && WIFI_STA == 1 && WIFI_AP == 2 && WIFI_AP_STA == 3,
              "WIFI_* op mode constants are not contiguous");
PROGMEM_STRING_TABLE(OpModeStrings, "OFF", "STA", "AP", "AP+STA", "UNKNOWN");

const LogString *get_op_mode_str(uint8_t mode) { return OpModeStrings::get_log_str(mode, OpModeStrings::LAST_INDEX); }

// Use if-chain instead of switch to avoid jump tables in RODATA (wastes RAM on ESP8266).
// A single switch would generate a sparse lookup table with ~175 default entries, wasting 700 bytes of RAM.
// Even split switches still generate smaller jump tables in RODATA.
const LogString *get_disconnect_reason_str(uint8_t reason) {
  if (reason == REASON_AUTH_EXPIRE)
    return LOG_STR("Auth Expired");
  if (reason == REASON_AUTH_LEAVE)
    return LOG_STR("Auth Leave");
  if (reason == REASON_ASSOC_EXPIRE)
    return LOG_STR("Association Expired");
  if (reason == REASON_ASSOC_TOOMANY)
    return LOG_STR("Too Many Associations");
  if (reason == REASON_NOT_AUTHED)
    return LOG_STR("Not Authenticated");
  if (reason == REASON_NOT_ASSOCED)
    return LOG_STR("Not Associated");
  if (reason == REASON_ASSOC_LEAVE)
    return LOG_STR("Association Leave");
  if (reason == REASON_ASSOC_NOT_AUTHED)
    return LOG_STR("Association not Authenticated");
  if (reason == REASON_DISASSOC_PWRCAP_BAD)
    return LOG_STR("Disassociate Power Cap Bad");
  if (reason == REASON_DISASSOC_SUPCHAN_BAD)
    return LOG_STR("Disassociate Supported Channel Bad");
  if (reason == REASON_IE_INVALID)
    return LOG_STR("IE Invalid");
  if (reason == REASON_MIC_FAILURE)
    return LOG_STR("Mic Failure");
  if (reason == REASON_4WAY_HANDSHAKE_TIMEOUT)
    return LOG_STR("4-Way Handshake Timeout");
  if (reason == REASON_GROUP_KEY_UPDATE_TIMEOUT)
    return LOG_STR("Group Key Update Timeout");
  if (reason == REASON_IE_IN_4WAY_DIFFERS)
    return LOG_STR("IE In 4-Way Handshake Differs");
  if (reason == REASON_GROUP_CIPHER_INVALID)
    return LOG_STR("Group Cipher Invalid");
  if (reason == REASON_PAIRWISE_CIPHER_INVALID)
    return LOG_STR("Pairwise Cipher Invalid");
  if (reason == REASON_AKMP_INVALID)
    return LOG_STR("AKMP Invalid");
  if (reason == REASON_UNSUPP_RSN_IE_VERSION)
    return LOG_STR("Unsupported RSN IE version");
  if (reason == REASON_INVALID_RSN_IE_CAP)
    return LOG_STR("Invalid RSN IE Cap");
  if (reason == REASON_802_1X_AUTH_FAILED)
    return LOG_STR("802.1x Authentication Failed");
  if (reason == REASON_CIPHER_SUITE_REJECTED)
    return LOG_STR("Cipher Suite Rejected");
  if (reason == REASON_BEACON_TIMEOUT)
    return LOG_STR("Beacon Timeout");
  if (reason == REASON_NO_AP_FOUND)
    return LOG_STR("AP Not Found");
  if (reason == REASON_AUTH_FAIL)
    return LOG_STR("Authentication Failed");
  if (reason == REASON_ASSOC_FAIL)
    return LOG_STR("Association Failed");
  if (reason == REASON_HANDSHAKE_TIMEOUT)
    return LOG_STR("Handshake Failed");
  return LOG_STR("Unspecified");
}

void WiFiComponent::wifi_event_callback(System_Event_t *event) {
  switch (event->event) {
    case EVENT_STAMODE_CONNECTED: {
      auto it = event->event_info.connected;
#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
      char bssid_buf[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
      format_mac_addr_upper(it.bssid, bssid_buf);
      ESP_LOGV(TAG, "Connected ssid='%.*s' bssid=%s channel=%u", it.ssid_len, (const char *) it.ssid, bssid_buf,
               it.channel);
#endif
      global_wifi_component->sta_state_ = static_cast<uint8_t>(ESP8266WiFiSTAState::ASSOCIATED);
#ifdef USE_WIFI_CONNECT_STATE_LISTENERS
      // Defer listener notification until state machine reaches STA_CONNECTED
      // This ensures wifi.connected condition returns true in listener automations
      global_wifi_component->pending_.connect_state = true;
#endif
      break;
    }
    case EVENT_STAMODE_DISCONNECTED: {
      auto it = event->event_info.disconnected;
      if (it.reason == REASON_NO_AP_FOUND) {
        ESP_LOGW(TAG, "Disconnected ssid='%.*s' reason='Probe Request Unsuccessful'", it.ssid_len,
                 (const char *) it.ssid);
        global_wifi_component->sta_state_ = static_cast<uint8_t>(ESP8266WiFiSTAState::ERROR_NOT_FOUND);
      } else {
        char bssid_s[18];
        format_mac_addr_upper(it.bssid, bssid_s);
        ESP_LOGW(TAG, "Disconnected ssid='%.*s' bssid=" LOG_SECRET("%s") " reason='%s'", it.ssid_len,
                 (const char *) it.ssid, bssid_s, LOG_STR_ARG(get_disconnect_reason_str(it.reason)));
        global_wifi_component->sta_state_ = static_cast<uint8_t>(ESP8266WiFiSTAState::ERROR_FAILED);
      }
      global_wifi_component->error_from_callback_ = true;
#ifdef USE_WIFI_CONNECT_STATE_LISTENERS
      global_wifi_component->pending_.disconnect = true;
#endif
      break;
    }
    case EVENT_STAMODE_AUTHMODE_CHANGE: {
      auto it = event->event_info.auth_change;
      ESP_LOGV(TAG, "Changed Authmode old=%s new=%s", LOG_STR_ARG(get_auth_mode_str(it.old_mode)),
               LOG_STR_ARG(get_auth_mode_str(it.new_mode)));
      // Mitigate CVE-2020-12638
      // https://lbsfilm.at/blog/wpa2-authenticationmode-downgrade-in-espressif-microprocessors
      if (it.old_mode != AUTH_OPEN && it.new_mode == AUTH_OPEN) {
        ESP_LOGW(TAG, "Potential Authmode downgrade detected, disconnecting");
        wifi_station_disconnect();
        global_wifi_component->error_from_callback_ = true;
      }
      break;
    }
    case EVENT_STAMODE_GOT_IP: {
      auto it = event->event_info.got_ip;
      char ip_buf[network::IP_ADDRESS_BUFFER_SIZE], gw_buf[network::IP_ADDRESS_BUFFER_SIZE],
          mask_buf[network::IP_ADDRESS_BUFFER_SIZE];
      ESP_LOGV(TAG, "static_ip=%s gateway=%s netmask=%s", network::IPAddress(&it.ip).str_to(ip_buf),
               network::IPAddress(&it.gw).str_to(gw_buf), network::IPAddress(&it.mask).str_to(mask_buf));
      global_wifi_component->sta_state_ = static_cast<uint8_t>(ESP8266WiFiSTAState::CONNECTED);
#ifdef USE_WIFI_IP_STATE_LISTENERS
      // Defer listener callbacks to main loop - system context has limited stack
      global_wifi_component->pending_.got_ip = true;
#endif
      break;
    }
    case EVENT_STAMODE_DHCP_TIMEOUT: {
      ESP_LOGW(TAG, "DHCP request timeout");
      break;
    }
    case EVENT_SOFTAPMODE_STACONNECTED: {
#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
      auto it = event->event_info.sta_connected;
      char mac_buf[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
      format_mac_addr_upper(it.mac, mac_buf);
      ESP_LOGV(TAG, "AP client connected MAC=%s aid=%u", mac_buf, it.aid);
#endif
      break;
    }
    case EVENT_SOFTAPMODE_STADISCONNECTED: {
#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
      auto it = event->event_info.sta_disconnected;
      char mac_buf[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
      format_mac_addr_upper(it.mac, mac_buf);
      ESP_LOGV(TAG, "AP client disconnected MAC=%s aid=%u", mac_buf, it.aid);
#endif
      break;
    }
    case EVENT_SOFTAPMODE_PROBEREQRECVED: {
#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERY_VERBOSE
      auto it = event->event_info.ap_probereqrecved;
      char mac_buf[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
      format_mac_addr_upper(it.mac, mac_buf);
      ESP_LOGVV(TAG, "AP receive Probe Request MAC=%s RSSI=%d", mac_buf, it.rssi);
#endif
      break;
    }
#if USE_ARDUINO_VERSION_CODE >= VERSION_CODE(2, 4, 0)
    case EVENT_OPMODE_CHANGED: {
      auto it = event->event_info.opmode_changed;
      ESP_LOGV(TAG, "Changed Mode old=%s new=%s", LOG_STR_ARG(get_op_mode_str(it.old_opmode)),
               LOG_STR_ARG(get_op_mode_str(it.new_opmode)));
      break;
    }
    case EVENT_SOFTAPMODE_DISTRIBUTE_STA_IP: {
#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
      auto it = event->event_info.distribute_sta_ip;
      char mac_buf[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
      char ip_buf[network::IP_ADDRESS_BUFFER_SIZE];
      format_mac_addr_upper(it.mac, mac_buf);
      ESP_LOGV(TAG, "AP Distribute Station IP MAC=%s IP=%s aid=%u", mac_buf, network::IPAddress(&it.ip).str_to(ip_buf),
               it.aid);
#endif
      break;
    }
#endif
    default:
      break;
  }

  WiFiMockClass::_event_callback(event);
}

bool WiFiComponent::wifi_apply_output_power_(float output_power) {
  uint8_t val = static_cast<uint8_t>(output_power * 4);
  system_phy_set_max_tpw(val);
  return true;
}
bool WiFiComponent::wifi_sta_pre_setup_() {
  if (!this->wifi_mode_(true, {}))
    return false;

  bool ret1, ret2;
  ETS_UART_INTR_DISABLE();
  ret1 = wifi_station_set_auto_connect(0);
  ret2 = wifi_station_set_reconnect_policy(false);
  ETS_UART_INTR_ENABLE();

  if (!ret1 || !ret2) {
    ESP_LOGV(TAG, "Disabling Auto-Connect failed");
  }

#ifdef USE_WIFI_PHY_MODE
  if (!this->wifi_apply_phy_mode_()) {
    ESP_LOGV(TAG, "Setting PHY Mode failed");
  }
#endif

  delay(10);
  return true;
}

#ifdef USE_WIFI_PHY_MODE
bool WiFiComponent::wifi_apply_phy_mode_() {
  if (this->phy_mode_ == WIFI_8266_PHY_MODE_AUTO)
    return true;
  // Values of WiFi8266PhyMode are aligned with the SDK's phy_mode_t enum.
  return wifi_set_phy_mode(static_cast<phy_mode_t>(this->phy_mode_));
}
#endif

void WiFiComponent::wifi_pre_setup_() {
  wifi_set_event_handler_cb(&WiFiComponent::wifi_event_callback);

  // Make sure WiFi is in clean state before anything starts
  this->wifi_mode_(false, false);
}

WiFiSTAConnectStatus WiFiComponent::wifi_sta_connect_status_() const {
  // Use cached state from wifi_event_callback() instead of calling
  // wifi_station_get_connect_status() which queries the SDK every time.
  // Use if statements with early returns instead of switch to avoid GCC
  // generating a CSWTCH lookup table in .rodata (flash) on ESP8266.
  auto state = static_cast<ESP8266WiFiSTAState>(this->sta_state_);
  if (state == ESP8266WiFiSTAState::CONNECTED)
    return WiFiSTAConnectStatus::CONNECTED;
  if (state == ESP8266WiFiSTAState::ERROR_NOT_FOUND)
    return WiFiSTAConnectStatus::ERROR_NETWORK_NOT_FOUND;
  if (state == ESP8266WiFiSTAState::ERROR_FAILED)
    return WiFiSTAConnectStatus::ERROR_CONNECT_FAILED;
  if (state == ESP8266WiFiSTAState::CONNECTING || state == ESP8266WiFiSTAState::ASSOCIATED)
    return WiFiSTAConnectStatus::CONNECTING;
  return WiFiSTAConnectStatus::IDLE;
}

bool WiFiComponent::wifi_scan_start_(bool passive) {
  // enable STA
  if (!this->wifi_mode_(true, {}))
    return false;

  // Reset scan_done_ before starting new scan to prevent stale flag from previous scan
  // (e.g., roaming scan completed just before unexpected disconnect)
  this->scan_done_ = false;

  struct scan_config config {};
  memset(&config, 0, sizeof(config));
  config.ssid = nullptr;
  config.bssid = nullptr;
  config.channel = 0;
  config.show_hidden = 1;
#if USE_ARDUINO_VERSION_CODE >= VERSION_CODE(2, 4, 0)
  config.scan_type = passive ? WIFI_SCAN_TYPE_PASSIVE : WIFI_SCAN_TYPE_ACTIVE;
  // Use shorter dwell times for roaming scans - we only need to detect strong
  // nearby APs, not do a thorough survey. This also reduces off-channel time
  // which can cause Beacon Timeout disconnects on some APs.
  // Roaming times match the ESP32 IDF scan defaults.
  static constexpr uint32_t SCAN_PASSIVE_DEFAULT_MS = 500;
  static constexpr uint32_t SCAN_PASSIVE_ROAMING_MS = 300;
  static constexpr uint32_t SCAN_ACTIVE_MIN_DEFAULT_MS = 400;
  static constexpr uint32_t SCAN_ACTIVE_MAX_DEFAULT_MS = 500;
  static constexpr uint32_t SCAN_ACTIVE_MIN_ROAMING_MS = 100;
  static constexpr uint32_t SCAN_ACTIVE_MAX_ROAMING_MS = 300;
  bool roaming = this->roaming_state_ == RoamingState::SCANNING;
  if (passive) {
    config.scan_time.passive = roaming ? SCAN_PASSIVE_ROAMING_MS : SCAN_PASSIVE_DEFAULT_MS;
  } else {
    config.scan_time.active.min = roaming ? SCAN_ACTIVE_MIN_ROAMING_MS : SCAN_ACTIVE_MIN_DEFAULT_MS;
    config.scan_time.active.max = roaming ? SCAN_ACTIVE_MAX_ROAMING_MS : SCAN_ACTIVE_MAX_DEFAULT_MS;
  }
#endif
  bool ret = wifi_station_scan(&config, &WiFiComponent::s_wifi_scan_done_callback);
  if (!ret) {
    ESP_LOGV(TAG, "wifi_station_scan failed");
    return false;
  }

  return ret;
}
bool WiFiComponent::wifi_disconnect_() {
  bool ret = true;
  // Only call disconnect if interface is up
  if (wifi_get_opmode() & WIFI_STA)
    ret = wifi_station_disconnect();
  station_config conf{};
  memset(&conf, 0, sizeof(conf));
  ETS_UART_INTR_DISABLE();
  wifi_station_set_config_current(&conf);
  ETS_UART_INTR_ENABLE();
  return ret;
}
void WiFiComponent::s_wifi_scan_done_callback(void *arg, STATUS status) {
  global_wifi_component->wifi_scan_done_callback_(arg, status);
}

void WiFiComponent::wifi_scan_done_callback_(void *arg, STATUS status) {
  // Compiles to nothing here; kept so every scan_result_ mutation holds the lock
  ScanResultsLock lock(this);
  this->scan_result_.clear();

  if (status != OK) {
    ESP_LOGV(TAG, "Scan failed: %d", status);
    // Don't call retry_connect() here - this callback runs in SDK system context
    // where yield() cannot be called. Instead, just set scan_done_ and let
    // check_scanning_finished() handle the empty scan_result_ from loop context.
    this->scan_done_ = true;
    return;
  }

  auto *head = reinterpret_cast<bss_info *>(arg);
  bool needs_full = this->needs_full_scan_results_();

  // First pass: count matching networks (linked list is non-destructive)
  size_t total = 0;
  size_t count = 0;
  for (bss_info *it = head; it != nullptr; it = STAILQ_NEXT(it, next)) {
    total++;
    const char *ssid_cstr = reinterpret_cast<const char *>(it->ssid);
    if (needs_full || this->matches_configured_network_(ssid_cstr, it->bssid)) {
      count++;
    }
  }

  this->scan_result_.init(count);  // Exact allocation

  // Second pass: store matching networks
  for (bss_info *it = head; it != nullptr; it = STAILQ_NEXT(it, next)) {
    const char *ssid_cstr = reinterpret_cast<const char *>(it->ssid);
    if (needs_full || this->matches_configured_network_(ssid_cstr, it->bssid)) {
      this->scan_result_.emplace_back(
          bssid_t{it->bssid[0], it->bssid[1], it->bssid[2], it->bssid[3], it->bssid[4], it->bssid[5]}, ssid_cstr,
          it->ssid_len, it->channel, it->rssi, it->authmode != AUTH_OPEN, it->is_hidden != 0);
    } else {
      this->log_discarded_scan_result_(ssid_cstr, it->bssid, it->rssi, it->channel);
    }
  }
  ESP_LOGV(TAG, "Scan complete: %zu found, %zu stored%s", total, this->scan_result_.size(),
           needs_full ? LOG_STR_LITERAL("") : LOG_STR_LITERAL(" (filtered)"));
  this->scan_done_ = true;
#ifdef USE_WIFI_SCAN_RESULTS_LISTENERS
  this->pending_.scan_complete = true;  // Defer listener callbacks to main loop
#endif
}

#ifdef USE_WIFI_AP
bool WiFiComponent::wifi_ap_ip_config_(const optional<ManualIP> &manual_ip) {
  // enable AP
  if (!this->wifi_mode_({}, true))
    return false;

  struct ip_info info {};
  if (manual_ip.has_value()) {
    info.ip = manual_ip->static_ip;
    info.gw = manual_ip->gateway;
    info.netmask = manual_ip->subnet;
  } else {
    info.ip = network::IPAddress(192, 168, 4, 1);
    info.gw = network::IPAddress(192, 168, 4, 1);
    info.netmask = network::IPAddress(255, 255, 255, 0);
  }

  if (wifi_softap_dhcps_status() == DHCP_STARTED) {
    if (!wifi_softap_dhcps_stop()) {
      ESP_LOGW(TAG, "Stopping DHCP server failed");
    }
  }

  if (!wifi_set_ip_info(SOFTAP_IF, &info)) {
    ESP_LOGE(TAG, "Set SoftAP info failed");
    return false;
  }

#if USE_ARDUINO_VERSION_CODE >= VERSION_CODE(3, 0, 0) && USE_ARDUINO_VERSION_CODE < VERSION_CODE(3, 1, 0)
  dhcpSoftAP.begin(&info);
#endif

  struct dhcps_lease lease {};
  lease.enable = true;
  network::IPAddress start_address = network::IPAddress(&info.ip);
  start_address += 99;
  lease.start_ip = start_address;
#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
  char ip_buf[network::IP_ADDRESS_BUFFER_SIZE];
#endif
  ESP_LOGV(TAG, "DHCP server IP lease start: %s", start_address.str_to(ip_buf));
  start_address += 10;
  lease.end_ip = start_address;
  ESP_LOGV(TAG, "DHCP server IP lease end: %s", start_address.str_to(ip_buf));
  if (!wifi_softap_set_dhcps_lease(&lease)) {
    ESP_LOGE(TAG, "Set SoftAP DHCP lease failed");
    return false;
  }

  // lease time 1440 minutes (=24 hours)
  if (!wifi_softap_set_dhcps_lease_time(1440)) {
    ESP_LOGE(TAG, "Set SoftAP DHCP lease time failed");
    return false;
  }

#if USE_ARDUINO_VERSION_CODE >= VERSION_CODE(3, 1, 0)
  ESP8266WiFiClass::softAPDhcpServer().setRouter(true);  // send ROUTER option with netif's gateway IP
#else
  uint8_t mode = 1;
  // bit0, 1 enables router information from ESP8266 SoftAP DHCP server.
  if (!wifi_softap_set_dhcps_offer_option(OFFER_ROUTER, &mode)) {
    ESP_LOGE(TAG, "wifi_softap_set_dhcps_offer_option failed");
    return false;
  }
#endif

  if (!wifi_softap_dhcps_start()) {
    ESP_LOGE(TAG, "Starting SoftAP DHCPS failed");
    return false;
  }

  return true;
}

bool WiFiComponent::wifi_start_ap_(const WiFiAP &ap) {
  // enable AP
  if (!this->wifi_mode_({}, true))
    return false;

  struct softap_config conf {};
  if (ap.ssid_.size() > sizeof(conf.ssid)) {
    ESP_LOGE(TAG, "AP SSID too long");
    return false;
  }
  memcpy(reinterpret_cast<char *>(conf.ssid), ap.ssid_.c_str(), ap.ssid_.size());
  conf.ssid_len = static_cast<uint8>(ap.ssid_.size());
  conf.channel = ap.has_channel() ? ap.get_channel() : 1;
  conf.ssid_hidden = ap.get_hidden();
  conf.max_connection = 5;
  conf.beacon_interval = 100;

  if (ap.password_.empty()) {
    conf.authmode = AUTH_OPEN;
    *conf.password = 0;
  } else {
    conf.authmode = AUTH_WPA2_PSK;
    if (ap.password_.size() > sizeof(conf.password)) {
      ESP_LOGE(TAG, "AP password too long");
      return false;
    }
    memcpy(reinterpret_cast<char *>(conf.password), ap.password_.c_str(), ap.password_.size());
  }

  ETS_UART_INTR_DISABLE();
  bool ret = wifi_softap_set_config_current(&conf);
  ETS_UART_INTR_ENABLE();

  if (!ret) {
    ESP_LOGV(TAG, "wifi_softap_set_config_current failed");
    return false;
  }

#ifdef USE_WIFI_MANUAL_IP
  if (!this->wifi_ap_ip_config_(ap.get_manual_ip())) {
    ESP_LOGV(TAG, "wifi_ap_ip_config_ failed");
    return false;
  }
#else
  if (!this->wifi_ap_ip_config_({})) {
    ESP_LOGV(TAG, "wifi_ap_ip_config_ failed");
    return false;
  }
#endif

  return true;
}

network::IPAddress WiFiComponent::wifi_soft_ap_ip() {
  struct ip_info ip {};
  wifi_get_ip_info(SOFTAP_IF, &ip);
  return network::IPAddress(&ip.ip);
}
#endif  // USE_WIFI_AP

bssid_t WiFiComponent::wifi_bssid() {
  bssid_t bssid{};
  struct station_config conf {};
  if (wifi_station_get_config(&conf)) {
    std::copy_n(conf.bssid, bssid.size(), bssid.begin());
  }
  return bssid;
}
std::string WiFiComponent::wifi_ssid() {
  struct station_config conf {};
  if (!wifi_station_get_config(&conf)) {
    return "";
  }
  // conf.ssid is uint8[32], not null-terminated if full
  auto *ssid_s = reinterpret_cast<const char *>(conf.ssid);
  size_t len = strnlen(ssid_s, sizeof(conf.ssid));
  return {ssid_s, len};
}
const char *WiFiComponent::wifi_ssid_to(std::span<char, SSID_BUFFER_SIZE> buffer) {
  struct station_config conf {};
  if (!wifi_station_get_config(&conf)) {
    buffer[0] = '\0';
    return buffer.data();
  }
  // conf.ssid is uint8[32], not null-terminated if full
  size_t len = strnlen(reinterpret_cast<const char *>(conf.ssid), sizeof(conf.ssid));
  memcpy(buffer.data(), conf.ssid, len);
  buffer[len] = '\0';
  return buffer.data();
}
int8_t WiFiComponent::wifi_rssi() {
  if (wifi_station_get_connect_status() != STATION_GOT_IP)
    return WIFI_RSSI_DISCONNECTED;
  sint8 rssi = wifi_station_get_rssi();
  // Values >= 31 are error codes per NONOS SDK API, not valid RSSI readings
  return rssi >= 31 ? WIFI_RSSI_DISCONNECTED : rssi;
}
int32_t WiFiComponent::get_wifi_channel() { return wifi_get_channel(); }
network::IPAddress WiFiComponent::wifi_subnet_mask_() {
  struct ip_info ip {};
  wifi_get_ip_info(STATION_IF, &ip);
  return network::IPAddress(&ip.netmask);
}
network::IPAddress WiFiComponent::wifi_gateway_ip_() {
  struct ip_info ip {};
  wifi_get_ip_info(STATION_IF, &ip);
  return network::IPAddress(&ip.gw);
}
network::IPAddress WiFiComponent::wifi_dns_ip_(int num) { return network::IPAddress(dns_getserver(num)); }
bool WiFiComponent::wifi_loop_() {
  this->process_pending_callbacks_();
  return true;
}

void WiFiComponent::process_pending_callbacks_() {
  // Process callbacks deferred from ESP8266 SDK system context (~2KB stack)
  // to main loop context (full stack). Connect state listeners are handled
  // by notify_connect_state_listeners_() in the shared state machine code.

#ifdef USE_WIFI_CONNECT_STATE_LISTENERS
  if (this->pending_.disconnect) {
    this->pending_.disconnect = false;
    // Refresh is_connected() cache here, not in the SDK callback (sys context).
    this->update_connected_state_();
    this->notify_disconnect_state_listeners_();
  }
#endif

#ifdef USE_WIFI_IP_STATE_LISTENERS
  if (this->pending_.got_ip) {
    this->pending_.got_ip = false;
    this->notify_ip_state_listeners_();
  }
#endif

#ifdef USE_WIFI_SCAN_RESULTS_LISTENERS
  if (this->pending_.scan_complete) {
    this->pending_.scan_complete = false;
    this->notify_scan_results_listeners_();
  }
#endif
}

}  // namespace esphome::wifi
#endif
#endif
