#include "lumacs/kill_ring_manager.hpp"
#include <iostream> // For debug output, consider replacing with logging

namespace lumacs {

KillRingManager::KillRingManager(size_t max_size) : max_size_(max_size) {
    if (max_size_ == 0) {
        max_size_ = 1; // Ensure minimum size
    }
}

void KillRingManager::push(const std::string& text) {
    if (text.empty()) {
        return;
    }

    if (!ring_.empty() && last_action_was_kill_) {
        // If the last action was a kill, append to the last entry
        ring_.front().append(text);
    } else {
        // Otherwise, create a new entry
        ring_.push_front(text);
        if (ring_.size() > max_size_) {
            ring_.pop_back(); // Remove oldest entry if max size exceeded
        }
    }
    last_action_was_kill_ = true;
}

std::string KillRingManager::current() const {
    if (ring_.empty()) {
        return "";
    }
    return ring_.front();
}

std::string KillRingManager::previous() {
    if (ring_.empty()) {
        return "";
    }
    
    // Rotate the ring: move back to front (conceptual 'previous')
    std::string back_item = ring_.back();
    ring_.pop_back();
    ring_.push_front(back_item);

    last_action_was_kill_ = false; // Reset state for push logic
    return ring_.front();
}

} // namespace lumacs
