"""为 vwed_tasklog 表添加层级关系字段

Revision ID: 004_add_tasklog_hierarchy
Revises: 20250904_150033
Create Date: 2025-10-10 12:00:00

"""
from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision = '004_add_tasklog_hierarchy'
down_revision = '20250904_150033'
branch_labels = None
depends_on = None


def upgrade():
    """添加层级关系字段到 vwed_tasklog 表"""

    # 添加字段
    op.add_column('vwed_tasklog',
        sa.Column('parent_log_id', sa.String(255), nullable=True, comment='父日志ID,用于建立层级关系'))

    op.add_column('vwed_tasklog',
        sa.Column('iteration_index', sa.Integer, nullable=True, comment='迭代索引,记录是第几次循环(从0开始)'))

    op.add_column('vwed_tasklog',
        sa.Column('block_record_id', sa.String(255), nullable=True, comment='关联的块执行记录ID'))

    op.add_column('vwed_tasklog',
        sa.Column('log_type', sa.String(50), nullable=True, comment='日志类型: iteration_start(迭代开始), iteration_end(迭代结束), block_execution(块执行), branch_execution(分支执行)'))

    # 创建索引以提高查询性能
    op.create_index('idx_vwed_tasklog_parent_log_id', 'vwed_tasklog', ['parent_log_id'])
    op.create_index('idx_vwed_tasklog_iteration_index', 'vwed_tasklog', ['iteration_index'])
    op.create_index('idx_vwed_tasklog_block_record_id', 'vwed_tasklog', ['block_record_id'])
    op.create_index('idx_vwed_tasklog_log_type', 'vwed_tasklog', ['log_type'])

    print("✅ 已为 vwed_tasklog 表添加层级关系字段")


def downgrade():
    """删除层级关系字段"""

    # 删除索引
    op.drop_index('idx_vwed_tasklog_log_type', table_name='vwed_tasklog')
    op.drop_index('idx_vwed_tasklog_block_record_id', table_name='vwed_tasklog')
    op.drop_index('idx_vwed_tasklog_iteration_index', table_name='vwed_tasklog')
    op.drop_index('idx_vwed_tasklog_parent_log_id', table_name='vwed_tasklog')

    # 删除字段
    op.drop_column('vwed_tasklog', 'log_type')
    op.drop_column('vwed_tasklog', 'block_record_id')
    op.drop_column('vwed_tasklog', 'iteration_index')
    op.drop_column('vwed_tasklog', 'parent_log_id')
