#pragma once

#include <string>

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

#include "calibration_common_interfaces/msg/job_state.hpp"
#include "calibration_sensor_interfaces/action/execute_sensor_calibration_task.hpp"
#include "calibration_sensor_interfaces/srv/get_sensor_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
{

// 传感器 gateway 薄 client。
// 职责：
//   1) 调 /sensor_calibration/get_readiness 确认传感器服务可执行；
//   2) 向 /sensor_calibration/execute_task 发送标定任务 goal；
//   3) 把 SensorCalibrationJobResult 翻译成 StageResultSummary 返回给主控。
class SensorGatewayClient
{
public:
  using ReadinessSrv =
    calibration_sensor_interfaces::srv::GetSensorReadiness;
  using ExecuteTask =
    calibration_sensor_interfaces::action::ExecuteSensorCalibrationTask;
  using GoalHandleExecuteTask = rclcpp_action::ClientGoalHandle<ExecuteTask>;

  explicit SensorGatewayClient(rclcpp::Node * node);

  // 对主控暴露的唯一入口：执行传感器标定阶段。
  bool execute_sensor_stage(
    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);

  uint8_t resolve_task_type(
    const calibration_workshop_orchestration_interfaces::msg::StagePlan & stage,
    std::string & failure_reason) const;

  bool build_goal(
    const calibration_workshop_orchestration_interfaces::msg::WorkshopSession & session,
    const calibration_workshop_orchestration_interfaces::msg::StagePlan & stage,
    uint8_t selected_task_type,
    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
