#pragma once

#include <string>

#include "rclcpp/rclcpp.hpp"
#include "rclcpp_action/rclcpp_action.hpp"

#include "calibration_common_interfaces/msg/job_state.hpp"
#include "calibration_external_localization_interfaces/action/execute_external_localization_task.hpp"
#include "calibration_external_localization_interfaces/srv/get_external_localization_readiness.hpp"
#include "calibration_workshop_orchestration_interfaces/msg/stage_plan.hpp"
#include "calibration_workshop_orchestration_interfaces/msg/stage_result_summary.hpp"
#include "calibration_workshop_orchestration_interfaces/msg/workshop_session.hpp"

namespace workshop_orchestrator_v2
{

// 这个类是 orchestrator 侧的“薄 client”。
// 作用只有一个：
// 1) 调 external_localization_service 的 readiness；
// 2) 调 external_localization_service 的 execute action；
// 3) 把 external 返回的结果整理成 StageResultSummary。
//
// 注意：
// 它不是 external 的“专项实现”。
// 真正的专项逻辑应该留在 external_localization_service 包里。
class ExternalLocalizationClient
{
public:
  using ReadinessSrv =
    calibration_external_localization_interfaces::srv::GetExternalLocalizationReadiness;
  using ExecuteTask =
    calibration_external_localization_interfaces::action::ExecuteExternalLocalizationTask;
  using GoalHandleExecuteTask = rclcpp_action::ClientGoalHandle<ExecuteTask>;

  explicit ExternalLocalizationClient(rclcpp::Node * node);

  // 对 orchestrator 暴露的唯一主入口：
  // 执行“外部真值校核”这一步。
  bool execute_reference_check(
    const calibration_workshop_orchestration_interfaces::msg::WorkshopSession & session,
    const calibration_workshop_orchestration_interfaces::msg::StagePlan & stage,
    calibration_workshop_orchestration_interfaces::msg::StageResultSummary & result,
    std::string & failure_reason);

private:
  bool check_ready(std::string & failure_reason);
  bool build_goal(
    const calibration_workshop_orchestration_interfaces::msg::WorkshopSession & session,
    const calibration_workshop_orchestration_interfaces::msg::StagePlan & stage,
    ExecuteTask::Goal & goal,
    std::string & failure_reason) const;
  std::string make_request_id() const;

  rclcpp::Node * node_{nullptr};
  rclcpp::Client<ReadinessSrv>::SharedPtr readiness_client_;
  rclcpp_action::Client<ExecuteTask>::SharedPtr execute_task_client_;
};

}  // namespace workshop_orchestrator_v2
