#pragma once

#include "uart.h"
#include "esphome/core/automation.h"

#include <vector>

namespace esphome::uart {

template<typename... Ts> class UARTWriteAction : public Action<Ts...>, public Parented<UARTComponent> {
 public:
  void set_data_template(std::vector<uint8_t> (*func)(Ts...)) {
    // Stateless lambdas (generated by ESPHome) implicitly convert to function pointers
    this->code_.func = func;
    this->len_ = -1;  // Sentinel value indicates template mode
  }

  // Store pointer to static data in flash (no RAM copy)
  void set_data_static(const uint8_t *data, size_t len) {
    this->code_.data = data;
    this->len_ = len;  // Length >= 0 indicates static mode
  }

  void play(const Ts &...x) override {
    if (this->len_ >= 0) {
      // Static mode: use pointer and length
      this->parent_->write_array(this->code_.data, static_cast<size_t>(this->len_));
    } else {
      // Template mode: call function
      auto val = this->code_.func(x...);
      this->parent_->write_array(val);
    }
  }

 protected:
  ssize_t len_{-1};  // -1 = template mode, >=0 = static mode with length
  union Code {
    std::vector<uint8_t> (*func)(Ts...);  // Function pointer (stateless lambdas)
    const uint8_t *data;                  // Pointer to static data in flash
  } code_;
};

}  // namespace esphome::uart
