module order_token_bucket_throttle (
    input  wire       clk,
    input  wire       rst,
    input  wire [4:0] bucket_capacity,
    input  wire [8:0] refill_period,
    input  wire       order_req,
    output reg        accept,
    output reg        reject
);
    reg [4:0] token_count;
    reg [8:0] refill_countdown;

    reg       refill_event;
    reg [4:0] visible_tokens;
    reg [4:0] next_token_count;
    reg [8:0] next_refill_countdown;

    always @(*) begin
        accept = 1'b0;
        reject = 1'b0;

        refill_event = 1'b0;
        visible_tokens = token_count;
        next_token_count = token_count;
        next_refill_countdown = refill_countdown;

        if (rst) begin
            next_token_count = bucket_capacity;
            next_refill_countdown = refill_period;
        end else begin
            refill_event = (refill_countdown == 9'd1);

            if (refill_event) begin
                if (visible_tokens < bucket_capacity)
                    visible_tokens = visible_tokens + 5'd1;
                next_refill_countdown = refill_period;
            end else begin
                next_refill_countdown = refill_countdown - 9'd1;
            end

            next_token_count = visible_tokens;

            if (order_req) begin
                if (visible_tokens != 5'd0) begin
                    accept = 1'b1;
                    next_token_count = visible_tokens - 5'd1;
                end else begin
                    reject = 1'b1;
                end
            end
        end
    end

    always @(posedge clk) begin
        if (rst) begin
            token_count <= bucket_capacity;
            refill_countdown <= refill_period;
        end else begin
            token_count <= next_token_count;
            refill_countdown <= next_refill_countdown;
        end
    end
endmodule
