#pragma once

#include <rclcpp/rclcpp.hpp>

#include <chrono>
#include <memory>
#include <string>

#include "mtran/http_translation_client.hpp"
#include "mtran/srv/translate_english_to_chinese.hpp"

namespace mtran
{

class TranslatorNode : public rclcpp::Node
{
public:
  explicit TranslatorNode(
    const rclcpp::NodeOptions & options = rclcpp::NodeOptions(),
    std::shared_ptr<TranslationClient> client = nullptr);

private:
  using TranslateService = mtran::srv::TranslateEnglishToChinese;

  void poll_readiness();
  void keep_warm();
  void mark_not_ready();
  void create_service_if_needed();
  void handle_request(
    const TranslateService::Request::SharedPtr request,
    TranslateService::Response::SharedPtr response);

  static std::size_t utf8_codepoint_count(const std::string & text);
  static bool is_blank(const std::string & text);
  static std::string error_code(ClientError error);

  std::shared_ptr<TranslationClient> client_;
  rclcpp::Service<TranslateService>::SharedPtr service_;
  rclcpp::TimerBase::SharedPtr health_timer_;
  rclcpp::TimerBase::SharedPtr keep_warm_timer_;

  bool ready_{false};
  bool ever_ready_{false};
  bool startup_timeout_logged_{false};
  std::chrono::steady_clock::time_point startup_started_;

  int request_timeout_ms_;
  int startup_timeout_ms_;
  int health_retry_ms_;
  int keep_warm_interval_s_;
  int max_input_characters_;
};

}  // namespace mtran
