#pragma once

#include <cstdint>
#include <string>
#include <vector>

#include "calibration_common_interfaces/msg/file_reference.hpp"
#include "calibration_workshop_orchestration_interfaces/msg/stage_result_summary.hpp"
#include "external_localization_service/external_localization_algorithm_template.hpp"

namespace external_localization_service
{

// 这个类属于 external_localization_service 侧。
// 它是 external_localization_service 的专项执行器门面，职责包括：
// 1. 对外部定位 action goal 做最小请求校验；
// 2. 组装统一的算法输入结构 ExternalLocalizationInput；
// 3. 调用 ExternalLocalizationAlgorithmTemplate，按任务类型分发到具体算法模板文件；
// 4. 把外部定位任务结果回填到 StageResultSummary，方便编排器统一消费。
//
// 这样分层后：
// - node 层只负责 ROS 通信；
// - executor 层负责输入组装与结果转换；
// - algorithm template 层负责按任务类型分发；
// - 各 *_algorithm.cpp 负责真实算法实现。
class ExternalReferenceExecutor
{
public:
  using ExecuteTask =
    calibration_external_localization_interfaces::action::ExecuteExternalLocalizationTask;

  struct DataInputConfig
  {
    int64_t data_window_start_timestamp_us{0};
    int64_t data_window_end_timestamp_us{0};
    std::vector<calibration_common_interfaces::msg::FileReference> external_observation_files;
    std::vector<calibration_common_interfaces::msg::FileReference> marker_observation_files;
    std::vector<calibration_common_interfaces::msg::FileReference> time_sync_diagnostic_files;
  };

  bool validate_goal(const ExecuteTask::Goal & goal, std::string & reject_reason) const;
  bool build_result(
    const ExecuteTask::Goal & goal,
    const calibration_external_localization_interfaces::msg::ExternalLocalizationReadinessResponse & readiness,
    const std::vector<calibration_external_localization_interfaces::msg::ExternalLocalizationTelemetry> & telemetry_history,
    const DataInputConfig & data_input_config,
    ExecuteTask::Result & external_result,
    std::string & failure_reason) const;

  void fill_stage_result_from_external_result(
    const ExecuteTask::Result & external_result,
    calibration_workshop_orchestration_interfaces::msg::StageResultSummary & stage_result,
    std::string & failure_reason) const;

private:
  ExternalLocalizationAlgorithmTemplate algorithm_;
};

}  // namespace external_localization_service
