#include "lumacs/macro_manager.hpp"
#include "lumacs/editor_core.hpp" // For EditorCore access
#include "lumacs/logger.hpp"
#include <spdlog/spdlog.h>

namespace lumacs {

MacroManager::MacroManager(EditorCore& core) : core_(core) {
}

void MacroManager::start_kbd_macro() {
    if (recording_macro_) {
        core_.set_message("Already recording macro");
        return;
    }
    
    recording_macro_ = true;
    current_macro_.clear();
    core_.set_message("Recording macro...");
}

void MacroManager::end_kbd_macro_or_call() {
    if (recording_macro_) {
        // End recording
        recording_macro_ = false;
        last_macro_ = current_macro_;
        current_macro_.clear();
        
        if (last_macro_.empty()) {
            core_.set_message("Macro recorded (empty)");
        } else {
            core_.set_message(std::string("Macro recorded (") + std::to_string(last_macro_.size()) + " keys)");
        }
    } else {
        // Call last macro
        if (last_macro_.empty()) {
            core_.set_message("No macro recorded");
            return;
        }
        
        core_.set_message(std::string("Executing macro (") + std::to_string(last_macro_.size()) + " keys)");
        
        // This is a simplified approach - in a real implementation, you'd need
        // to replay the actual commands through the key binding system
        // For now, we just show that the macro system is set up
        for (const auto& key : last_macro_) {
            // TODO: Execute the actual key binding for this key
            // This would require MacroManager to have access to core_->keybinding_manager()
            core_.keybinding_manager().process_key(key); // Replay the key sequence
            spdlog::debug("[MACRO] Executing key: {}", key);
        }
    }
}

void MacroManager::record_key_sequence(const std::string& key_sequence) {
    if (recording_macro_) {
        current_macro_.push_back(key_sequence);
    }
}

} // namespace lumacs
