#pragma once

#include <string>
#include <vector>

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

#include "calibration_common_interfaces/msg/job_state.hpp"
#include "calibration_control_interfaces/action/execute_controller_evaluation.hpp"
#include "calibration_control_interfaces/srv/get_control_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
{

using StagePlan = calibration_workshop_orchestration_interfaces::msg::StagePlan;

// 运控 gateway 薄 client。
// 职责：
//   1) 调 /control/get_readiness 确认运控服务可执行；
//   2) 向 /control/execute_controller_evaluation 发送评估任务 goal；
//   3) 把 ControlJobResult 翻译成 StageResultSummary 返回给主控。
class ControlGatewayClient
{
public:
  using ReadinessSrv =
    calibration_control_interfaces::srv::GetControlReadiness;
  using ExecuteTask =
    calibration_control_interfaces::action::ExecuteControllerEvaluation;
  using GoalHandleExecuteTask = rclcpp_action::ClientGoalHandle<ExecuteTask>;

  explicit ControlGatewayClient(rclcpp::Node * node);

  // 对主控暴露的唯一入口：执行运控参数评估阶段。
  bool execute_control_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,
    ExecuteTask::Goal & goal,
    std::string & failure_reason) const;

  std::string make_request_id() const;

  // 根据 stage.metadata 解析轨迹点；未提供必需数据时直接失败。
  std::vector<calibration_control_interfaces::msg::TrajectoryPoint>
  build_trajectory_from_metadata(const StagePlan & stage, std::string & failure_reason) const;

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

}  // namespace workshop_orchestrator_v2
