#pragma once

#include <condition_variable> // 暂停/恢复、人工确认、审批等待都需要条件变量。
#include <memory>
#include <mutex>         // 保护 sessions_，避免 service 和 action 线程同时改同一条任务记录。
#include <string>        // 保存 topic 名、ID、说明文本。
#include <unordered_map> // 按 session_id 快速找到某次标定任务。

#include "rclcpp/rclcpp.hpp"               // ROS 2 普通节点基础能力。
#include "rclcpp_action/rclcpp_action.hpp" // ROS 2 action 能力，适合承载"整场任务执行"这种长操作。

#include "rcl_interfaces/msg/set_parameters_result.hpp"

#include "calibration_workshop_orchestration_interfaces/action/execute_workshop_session.hpp" // 外部要求主控开始跑某次标定任务的 action。
#include "calibration_workshop_orchestration_interfaces/msg/workshop_event.hpp"               // 发给界面/日志/上位机的进度通知消息。
#include "calibration_workshop_orchestration_interfaces/msg/workshop_event_type.hpp"          // 进度通知里的事件类型枚举。
#include "calibration_workshop_orchestration_interfaces/srv/acknowledge_manual_step.hpp"      // 人工确认。
#include "calibration_workshop_orchestration_interfaces/srv/approve_stage_result.hpp"         // 审批阶段结果。
#include "calibration_workshop_orchestration_interfaces/srv/create_workshop_session.hpp"      // 创建一条新的标定任务。
#include "calibration_workshop_orchestration_interfaces/srv/get_workshop_report.hpp"          // 查询最终报告。
#include "calibration_workshop_orchestration_interfaces/srv/get_workshop_session.hpp"         // 查询当前任务状态。
#include "calibration_workshop_orchestration_interfaces/srv/pause_workshop_session.hpp"       // 暂停。
#include "calibration_workshop_orchestration_interfaces/srv/resume_workshop_session.hpp"      // 恢复。

#include "workshop_orchestrator_v2/plan_builder.hpp"                 // 生成步骤列表。
#include "workshop_orchestrator_v2/precheck_runner.hpp"              // 开跑前检查。
#include "workshop_orchestrator_v2/report_builder.hpp"               // 生成最终报告。
#include "workshop_orchestrator_v2/types.hpp"                        // 公共类型和 SessionRecord。
#include "workshop_orchestrator_v2/external_localization_client.hpp" // 外部定位模块薄 client。
#include "workshop_orchestrator_v2/chassis_gateway_client.hpp"       // 底盘模块薄 client。
#include "workshop_orchestrator_v2/control_gateway_client.hpp"       // 运控模块薄 client。
#include "workshop_orchestrator_v2/sensor_gateway_client.hpp"        // 传感器模块薄 client。
#include "workshop_orchestrator_v2/wifi6_link_client.hpp"            // 四条 WiFi6/TCP 链路预检。

namespace workshop_orchestrator_v2
{

using StageExecutionPolicy = calibration_workshop_orchestration_interfaces::msg::StageExecutionPolicy;

class WorkshopOrchestratorV2Node : public rclcpp::Node
{
public:
  using ExecuteWorkshopSession =
    calibration_workshop_orchestration_interfaces::action::ExecuteWorkshopSession;
  using GoalHandleExecuteWorkshopSession =
    rclcpp_action::ServerGoalHandle<ExecuteWorkshopSession>;

  explicit WorkshopOrchestratorV2Node(const rclcpp::NodeOptions & options = rclcpp::NodeOptions());

private:
  // 执行上下文：主控内部在"正式开跑这条任务"时临时保存的信息。
  struct SessionExecutionContext
  {
    std::string session_id;
    int64_t started_timestamp_us{0};
    bool has_required_failure{false}; // 是否有 REQUIRED 阶段失败。
  };

  // ─── 原有 service handler ───
  // ─── 原有 service handler ───
  void handle_create_session(
    const std::shared_ptr<calibration_workshop_orchestration_interfaces::srv::CreateWorkshopSession::Request> request,
    std::shared_ptr<calibration_workshop_orchestration_interfaces::srv::CreateWorkshopSession::Response> response);
  void handle_get_session(
    const std::shared_ptr<calibration_workshop_orchestration_interfaces::srv::GetWorkshopSession::Request> request,
    std::shared_ptr<calibration_workshop_orchestration_interfaces::srv::GetWorkshopSession::Response> response);
  void handle_get_report(
    const std::shared_ptr<calibration_workshop_orchestration_interfaces::srv::GetWorkshopReport::Request> request,
    std::shared_ptr<calibration_workshop_orchestration_interfaces::srv::GetWorkshopReport::Response> response);

  // ─── 新增 service handler ───
  void handle_pause_session(
    const std::shared_ptr<calibration_workshop_orchestration_interfaces::srv::PauseWorkshopSession::Request> request,
    std::shared_ptr<calibration_workshop_orchestration_interfaces::srv::PauseWorkshopSession::Response> response);
  void handle_resume_session(
    const std::shared_ptr<calibration_workshop_orchestration_interfaces::srv::ResumeWorkshopSession::Request> request,
    std::shared_ptr<calibration_workshop_orchestration_interfaces::srv::ResumeWorkshopSession::Response> response);
  void handle_acknowledge_manual_step(
    const std::shared_ptr<calibration_workshop_orchestration_interfaces::srv::AcknowledgeManualStep::Request> request,
    std::shared_ptr<calibration_workshop_orchestration_interfaces::srv::AcknowledgeManualStep::Response> response);
  void handle_approve_stage_result(
    const std::shared_ptr<calibration_workshop_orchestration_interfaces::srv::ApproveStageResult::Request> request,
    std::shared_ptr<calibration_workshop_orchestration_interfaces::srv::ApproveStageResult::Response> response);

  // ─── Action handler ───
  rclcpp_action::GoalResponse handle_execute_goal(
    const rclcpp_action::GoalUUID & uuid,
    std::shared_ptr<const ExecuteWorkshopSession::Goal> goal);
  rclcpp_action::CancelResponse handle_execute_cancel(
    const std::shared_ptr<GoalHandleExecuteWorkshopSession> goal_handle);
  void handle_execute_accepted(const std::shared_ptr<GoalHandleExecuteWorkshopSession> goal_handle);

  // ─── 执行主流程 ───
  void execute_session(const std::shared_ptr<GoalHandleExecuteWorkshopSession> goal_handle);
  SessionExecutionContext prepare_session_for_run(const std::string & session_id);
  WorkshopPrecheckResponse run_precheck_step(const std::string & session_id);
  void run_wifi6_link_precheck(const WorkshopSession & session, WorkshopPrecheckResponse & precheck);
  void append_precheck_item(
    WorkshopPrecheckResponse & precheck,
    const std::string & item_code,
    const std::string & display_name,
    bool passed,
    const std::string & message,
    uint8_t stage_type,
    uint8_t module_type);
  void mark_session_running(const std::string & session_id);
  bool handle_cancel_if_requested(
    const std::shared_ptr<GoalHandleExecuteWorkshopSession> goal_handle,
    const SessionExecutionContext & context);
  bool run_all_stages(
    const std::shared_ptr<GoalHandleExecuteWorkshopSession> goal_handle,
    SessionExecutionContext & context,
    std::string & failure_reason);
  bool run_single_stage(
    const std::shared_ptr<GoalHandleExecuteWorkshopSession> goal_handle,
    const std::string & session_id,
    const StagePlan & stage,
    std::string & failure_reason);
  bool wait_for_manual_confirmation(
    const std::shared_ptr<GoalHandleExecuteWorkshopSession> goal_handle,
    const std::string & session_id,
    const StagePlan & stage,
    std::string & failure_reason);
  bool wait_for_stage_approval(
    const std::shared_ptr<GoalHandleExecuteWorkshopSession> goal_handle,
    const std::string & session_id,
    const StagePlan & stage,
    StageResultSummary & result,
    std::string & failure_reason);
  bool dispatch_stage_to_module(
    const std::string & session_id,
    const StagePlan & stage,
    StageResultSummary & result,
    std::string & failure_reason);
  bool run_external_localization_stage(
    const std::string & session_id,
    const StagePlan & stage,
    StageResultSummary & result,
    std::string & failure_reason);
  bool run_chassis_stage(
    const std::string & session_id,
    const StagePlan & stage,
    StageResultSummary & result,
    std::string & failure_reason);
  bool run_control_stage(
    const std::string & session_id,
    const StagePlan & stage,
    StageResultSummary & result,
    std::string & failure_reason);
  bool run_sensor_stage(
    const std::string & session_id,
    const StagePlan & stage,
    StageResultSummary & result,
    std::string & failure_reason);

  // ─── 暂停等待 ───
  void wait_if_paused(const std::string & session_id);

  // ─── 阶段结果记录 ───
  void record_stage_result(const std::string & session_id, const StageResultSummary & result);

  // ─── 状态标记 ───
  void mark_stage_failed(
    const std::string & session_id,
    const StagePlan & stage,
    const std::string & failure_reason);
  void mark_stage_started(const std::string & session_id, const StagePlan & stage);
  void mark_stage_completed(
    const std::string & session_id,
    const StagePlan & stage,
    const StageResultSummary & result);

  // ─── 收尾 ───
  void finish_session_precheck_failed(
    const std::shared_ptr<GoalHandleExecuteWorkshopSession> goal_handle,
    const SessionExecutionContext & context,
    const WorkshopPrecheckResponse & precheck);
  void finish_session_failed(
    const std::shared_ptr<GoalHandleExecuteWorkshopSession> goal_handle,
    const SessionExecutionContext & context,
    const std::string & failure_reason);
  void finish_session_succeeded(
    const std::shared_ptr<GoalHandleExecuteWorkshopSession> goal_handle,
    const SessionExecutionContext & context);
  void finish_session_canceled(
    const std::shared_ptr<GoalHandleExecuteWorkshopSession> goal_handle,
    const SessionExecutionContext & context);
  void append_report_trace_files(WorkshopReport & report) const;

  // ─── 事件发布（同时发 topic + action feedback） ───
  void publish_event(
    const SessionRecord & record,
    uint8_t event_type,
    const std::string & message,
    const std::string & stage_id = std::string(),
    uint8_t stage_job_state = JobState::JOB_STATE_UNSPECIFIED,
    uint8_t stage_type = WorkflowStageType::WORKFLOW_STAGE_UNSPECIFIED,
    uint8_t module_type = CalibrationModuleType::CALIBRATION_MODULE_UNSPECIFIED,
    bool requires_manual_ack = false,
    uint8_t approval_state = ApprovalState::APPROVAL_STATE_UNSPECIFIED);

  std::string make_session_id() const;

  // ─── 数据成员 ───
  std::mutex mutex_;
  std::unordered_map<std::string, SessionRecord> sessions_;

  // 暂停/恢复、人工动作、审批等待。
  std::condition_variable pause_cv_;
  std::condition_variable manual_action_cv_;
  std::condition_variable approval_cv_;
  bool pause_requested_{false};

  // 当前正在执行的 action goal handle，用于发 feedback。
  std::shared_ptr<GoalHandleExecuteWorkshopSession> active_goal_handle_;

  PlanBuilder plan_builder_;
  PrecheckRunner precheck_runner_;
  ReportBuilder report_builder_;
  std::unique_ptr<ExternalLocalizationClient> external_localization_client_;
  std::unique_ptr<ChassisGatewayClient> chassis_gateway_client_;
  std::unique_ptr<ControlGatewayClient> control_gateway_client_;
  std::unique_ptr<SensorGatewayClient> sensor_gateway_client_;
  std::unique_ptr<Wifi6LinkClient> wifi6_link_client_;
  bool wifi6_precheck_enabled_{true};
  bool wifi6_precheck_require_all_links_{true};
  std::string data_input_params_file_;
  std::string dataset_index_file_;
  rclcpp::node_interfaces::OnSetParametersCallbackHandle::SharedPtr parameter_callback_handle_;

  // ─── ROS 接口 ───
  rclcpp::Service<calibration_workshop_orchestration_interfaces::srv::CreateWorkshopSession>::SharedPtr create_session_service_;
  rclcpp::Service<calibration_workshop_orchestration_interfaces::srv::GetWorkshopSession>::SharedPtr get_session_service_;
  rclcpp::Service<calibration_workshop_orchestration_interfaces::srv::GetWorkshopReport>::SharedPtr get_report_service_;
  rclcpp::Service<calibration_workshop_orchestration_interfaces::srv::PauseWorkshopSession>::SharedPtr pause_session_service_;
  rclcpp::Service<calibration_workshop_orchestration_interfaces::srv::ResumeWorkshopSession>::SharedPtr resume_session_service_;
  rclcpp::Service<calibration_workshop_orchestration_interfaces::srv::AcknowledgeManualStep>::SharedPtr acknowledge_manual_step_service_;
  rclcpp::Service<calibration_workshop_orchestration_interfaces::srv::ApproveStageResult>::SharedPtr approve_stage_result_service_;
  rclcpp_action::Server<ExecuteWorkshopSession>::SharedPtr execute_session_action_server_;
  rclcpp::Publisher<calibration_workshop_orchestration_interfaces::msg::WorkshopEvent>::SharedPtr event_publisher_;
};

}  // namespace workshop_orchestrator_v2
