#ifdef USE_LIBRETINY
#include "ota_backend_arduino_libretiny.h"
#include "ota_backend.h"

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

#include <Update.h>

namespace esphome::ota {

static const char *const TAG = "ota.arduino_libretiny";

std::unique_ptr<ArduinoLibreTinyOTABackend> make_ota_backend() { return make_unique<ArduinoLibreTinyOTABackend>(); }

OTAResponseTypes ArduinoLibreTinyOTABackend::begin(size_t image_size, OTAType ota_type) {
  if (ota_type != OTA_TYPE_UPDATE_APP) {
    return OTA_RESPONSE_ERROR_UNSUPPORTED_OTA_TYPE;
  }
  // Handle UPDATE_SIZE_UNKNOWN (0) which is used by web server OTA
  // where the exact firmware size is unknown due to multipart encoding
  if (image_size == 0) {
    image_size = UPDATE_SIZE_UNKNOWN;
  }
  bool ret = Update.begin(image_size, U_FLASH);
  if (ret) {
    return OTA_RESPONSE_OK;
  }

  uint8_t error = Update.getError();
  if (error == UPDATE_ERROR_SIZE)
    return OTA_RESPONSE_ERROR_ESP32_NOT_ENOUGH_SPACE;

  ESP_LOGE(TAG, "Begin error: %d", error);

  return OTA_RESPONSE_ERROR_UNKNOWN;
}

void ArduinoLibreTinyOTABackend::set_update_md5(const char *md5) {
  Update.setMD5(md5);
  this->md5_set_ = true;
}

OTAResponseTypes ArduinoLibreTinyOTABackend::write(uint8_t *data, size_t len) {
  size_t written = Update.write(data, len);
  if (written == len) {
    return OTA_RESPONSE_OK;
  }

  uint8_t error = Update.getError();
  ESP_LOGE(TAG, "Write error: %d", error);

  return OTA_RESPONSE_ERROR_WRITING_FLASH;
}

OTAResponseTypes ArduinoLibreTinyOTABackend::end() {
  // Use strict validation (false) when MD5 is set, lenient validation (true) when no MD5
  // This matches the behavior of the old web_server OTA implementation
  if (Update.end(!this->md5_set_)) {
    return OTA_RESPONSE_OK;
  }

  uint8_t error = Update.getError();
  ESP_LOGE(TAG, "End error: %d", error);

  return OTA_RESPONSE_ERROR_UPDATE_END;
}

void ArduinoLibreTinyOTABackend::abort() { Update.abort(); }

}  // namespace esphome::ota
#endif  // USE_LIBRETINY
