#ifndef NETWORK_SWITCH_ECN_DEDICATED_RED_H
#define NETWORK_SWITCH_ECN_DEDICATED_RED_H

#include <vector>
#include "network/switch/ecn_engine.h"
#include "network/switch/switch_buffer.h"
#include "core/rng.h"

namespace dofs {

// Classic per-port RED over DedicatedBuffer caps.
// Probabilistic ECN in [min_th, max_th]; trim at > max_th.
class DedicatedREDEngine final : public ECNEngine {
public:
        DedicatedREDEngine(Bytes min_th,
                           Bytes max_th,
                           double p_max,
                           bool back_to_sender,
                           Rng *const rng) noexcept
                : _min_th(min_th),
                  _max_th(max_th),
                  _p_max(p_max),
                  _back_to_sender(back_to_sender),
                  _rng(rng) {}

        virtual Packet &process_packet(Packet &pkt,
                                       SwitchBuffer *buf) noexcept override;

private:
        // EWMA queue estimator per port (bytes)
        void ensure_size(uint16_t port_cnt) {
                if (_avg_bytes.size() != port_cnt)
                        _avg_bytes.assign(port_cnt, 0.0);
        }

        double ewma(double cur, double avg) const noexcept {
                // w_q ~ 1/8 for responsiveness without flapping
                constexpr double W = 0.125;
                return (1.0 - W) * avg + W * cur;
        }

private:
        Bytes      _min_th;
        Bytes      _max_th;
        double     _p_max;          // in [0,1]
        bool       _back_to_sender; // whether to trim back to sender
        Rng *const _rng;            // not owned

        std::vector<double> _avg_bytes;
};

} // namespace dofs

#endif // NETWORK_SWITCH_ECN_DEDICATED_RED_H
