"""add workflow run metadata columns

Revision ID: e5f6g7h8i9j0
Revises: d4e5f6g7h8i9
Create Date: 2026-06-01 12:00:00.000000

"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa

revision: str = 'e5f6g7h8i9j0'
down_revision: Union[str, None] = 'd4e5f6g7h8i9'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    bind = op.get_bind()
    inspector = sa.inspect(bind)
    existing_columns = {
        column['name']
        for column in inspector.get_columns('ai_workflow_run')
    }

    if 'trigger_type' not in existing_columns:
        op.add_column(
            'ai_workflow_run',
            sa.Column('trigger_type', sa.String(length=30), nullable=True, comment='触发来源'),
        )
    if 'use_draft' not in existing_columns:
        op.add_column(
            'ai_workflow_run',
            sa.Column('use_draft', sa.Boolean(), nullable=True, comment='是否使用草稿定义执行'),
        )
    if 'workflow_version' not in existing_columns:
        op.add_column(
            'ai_workflow_run',
            sa.Column('workflow_version', sa.Integer(), nullable=True, comment='执行时发布版本号'),
        )
    if 'definition_snapshot' not in existing_columns:
        op.add_column(
            'ai_workflow_run',
            sa.Column('definition_snapshot', sa.JSON(), nullable=True, comment='运行开始时的工作流定义快照'),
        )
    op.execute("UPDATE ai_workflow_run SET trigger_type = 'api' WHERE trigger_type IS NULL")
    op.execute("UPDATE ai_workflow_run SET use_draft = false WHERE use_draft IS NULL")
    op.execute("UPDATE ai_workflow_run SET definition_snapshot = '{}' WHERE definition_snapshot IS NULL")


def downgrade() -> None:
    op.drop_column('ai_workflow_run', 'definition_snapshot')
    op.drop_column('ai_workflow_run', 'workflow_version')
    op.drop_column('ai_workflow_run', 'use_draft')
    op.drop_column('ai_workflow_run', 'trigger_type')
