package com.cameleer.server.core.ingestion;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * Bounded write buffer that decouples HTTP ingestion from database batch inserts.
 * <p>
 * Items are offered to the buffer by controllers and drained in batches by a
 * scheduled flush task. When the buffer is full, {@link #offer} returns false,
 * signaling the caller to apply backpressure (HTTP 503).
 *
 * @param <T> the type of items buffered
 */
public class WriteBuffer<T> {

    private static final Logger log = LoggerFactory.getLogger(WriteBuffer.class);

    private final BlockingQueue<T> queue;
    private final int capacity;

    public WriteBuffer(int capacity) {
        this.capacity = capacity;
        this.queue = new ArrayBlockingQueue<>(capacity);
    }

    /**
     * Offer a single item to the buffer.
     *
     * @return true if the item was added, false if the buffer is full
     */
    public boolean offer(T item) {
        return queue.offer(item);
    }

    /**
     * Offer an item, logging a warning if the buffer is full.
     * Use this as a {@code Consumer<T>} when the caller cannot handle backpressure.
     */
    public void offerOrWarn(T item) {
        if (!queue.offer(item)) {
            log.warn("WriteBuffer full (capacity={}), item dropped", capacity);
        }
    }

    /**
     * Offer a batch of items with all-or-nothing semantics.
     * If the buffer does not have enough remaining capacity for the entire batch,
     * no items are added and false is returned.
     *
     * @return true if all items were added, false if insufficient capacity
     */
    public boolean offerBatch(List<T> items) {
        if (queue.remainingCapacity() < items.size()) {
            return false;
        }
        for (T item : items) {
            if (!queue.offer(item)) {
                log.warn("WriteBuffer offer rejected despite capacity check — possible concurrent modification");
                return false;
            }
        }
        return true;
    }

    /**
     * Drain up to {@code maxBatch} items from the buffer.
     * Called by the scheduled flush task.
     *
     * @return list of drained items (may be empty)
     */
    public List<T> drain(int maxBatch) {
        List<T> batch = new ArrayList<>(maxBatch);
        queue.drainTo(batch, maxBatch);
        return batch;
    }

    public int size() {
        return queue.size();
    }

    public int capacity() {
        return capacity;
    }

    public boolean isFull() {
        return queue.remainingCapacity() == 0;
    }

    public int remainingCapacity() {
        return queue.remainingCapacity();
    }
}
