"""
状态管理（撤销/重做）
"""

import streamlit as st
import copy


def init_undo_stack():
    """初始化撤销/重做栈"""
    if 'undo_stack' not in st.session_state:
        st.session_state.undo_stack = []
    if 'redo_stack' not in st.session_state:
        st.session_state.redo_stack = []


def save_state_for_undo(structure):
    """
    保存当前状态到撤销栈
    
    Args:
        structure: 当前表格结构
    """
    # 深拷贝当前结构
    state = copy.deepcopy(structure)
    st.session_state.undo_stack.append(state)
    
    # 清空重做栈
    st.session_state.redo_stack = []
    
    # 限制栈深度（最多保存20个历史状态）
    if len(st.session_state.undo_stack) > 20:
        st.session_state.undo_stack.pop(0)


def undo_last_action():
    """
    撤销上一个操作
    
    Returns:
        是否成功撤销
    """
    if st.session_state.undo_stack:
        # 保存当前状态到重做栈
        current_state = copy.deepcopy(st.session_state.structure)
        st.session_state.redo_stack.append(current_state)
        
        # 恢复上一个状态
        st.session_state.structure = st.session_state.undo_stack.pop()
        return True
    return False


def redo_last_action():
    """
    重做上一个操作
    
    Returns:
        是否成功重做
    """
    if st.session_state.redo_stack:
        # 保存当前状态到撤销栈
        current_state = copy.deepcopy(st.session_state.structure)
        st.session_state.undo_stack.append(current_state)
        
        # 恢复重做的状态
        st.session_state.structure = st.session_state.redo_stack.pop()
        return True
    return False