#include "CommandHistory.h"
#include "../utils/Logger.h"

namespace UsdLayerManager {

void CommandHistory::Push(std::unique_ptr<ICommand> cmd) {
    if (!cmd) return;
    try {
        cmd->Execute();
    } catch (...) {
        LOG_ERROR("CommandHistory::Push — Execute() threw an exception; command discarded");
        return;
    }
    m_undoStack.push_back(std::move(cmd));
    m_redoStack.clear();
}

void CommandHistory::Undo() {
    if (m_undoStack.empty()) return;
    auto& cmd = m_undoStack.back();
    try {
        cmd->Undo();
    } catch (...) {
        LOG_ERROR("CommandHistory::Undo — Undo() threw an exception; history cleared for safety");
        Clear();
        return;
    }
    m_redoStack.push_back(std::move(cmd));
    m_undoStack.pop_back();
}

void CommandHistory::Redo() {
    if (m_redoStack.empty()) return;
    auto& cmd = m_redoStack.back();
    try {
        cmd->Execute();
    } catch (...) {
        LOG_ERROR("CommandHistory::Redo — Execute() threw an exception; history cleared for safety");
        Clear();
        return;
    }
    m_undoStack.push_back(std::move(cmd));
    m_redoStack.pop_back();
}

void CommandHistory::Clear() {
    m_undoStack.clear();
    m_redoStack.clear();
}

std::string CommandHistory::GetUndoDescription() const {
    return m_undoStack.empty() ? std::string() : m_undoStack.back()->GetDescription();
}

std::string CommandHistory::GetRedoDescription() const {
    return m_redoStack.empty() ? std::string() : m_redoStack.back()->GetDescription();
}

} // namespace UsdLayerManager
