/*
 * SPDX-FileCopyrightText: Copyright (c) 2021-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
 * SPDX-License-Identifier: Apache-2.0
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#ifndef NVIDIA_GXF_STD_RECEIVER_HPP
#define NVIDIA_GXF_STD_RECEIVER_HPP

#include <set>
#include <string>
#include "gxf/std/queue.hpp"
#include "gxf/std/system_group.hpp"
#include "gxf/std/transmitter.hpp"

namespace nvidia {
namespace gxf {

// Interface for receiving entities.
class Receiver : public Queue {
 public:
  struct StageSizeSnapshot {
    size_t main_stage = 0;
    size_t back_stage = 0;

    size_t total() const { return main_stage + back_stage; }
  };

  gxf_result_t initialize() override;

  // Receives the next entity from the main stage.
  virtual gxf_result_t receive_abi(gxf_uid_t* uid) = 0;

  // The total number of entities which have recently arrived but are not yet on the main stage.
  virtual size_t back_size_abi() = 0;

  // Returns a coherent front/back queue snapshot. Scheduling terms that reason about both
  // counters should use this instead of combining separate size()/back_size() calls.
  virtual StageSizeSnapshot stage_sizes_abi();

  // Peeks into back stage
  virtual gxf_result_t peek_back_abi(gxf_uid_t* uid, int32_t index) = 0;

  // Moves entities which recently arrived to the main stage.
  virtual gxf_result_t sync_abi() = 0;

  virtual gxf_result_t sync_io_abi() { return GXF_SUCCESS; }

  virtual gxf_result_t wait_abi() { return GXF_SUCCESS; }

  Expected<Entity> receive();

  size_t back_size();

  StageSizeSnapshot stage_sizes();

  Expected<void> sync();

  Expected<void> sync_io();

  Expected<void> wait();

  Expected<Entity> peekBack(int32_t index = 0);

  Expected<void> setTransmitter(Handle<Transmitter> tx);

  // Sets the system group for direct entity notification.
  // When set, bypasses GxfEntityNotifyEventType -> Runtime -> Program chain.
  void setSystemGroup(SystemGroup* system_group) { system_group_ = system_group; }

 protected:
  const char* entity_name() const noexcept { return entity_name_.c_str(); }

 private:
  std::string entity_name_;
  std::set<Handle<Transmitter>> connected_transmitters_;
  SystemGroup* system_group_{nullptr};
};

}  // namespace gxf
}  // namespace nvidia

#endif
