"""add scenario_version to eval_runs

Revision ID: d5b8c2e4f617
Revises: c8e2f5a7b901
Create Date: 2026-07-29
"""
from typing import Sequence, Union

import sqlalchemy as sa
import sqlmodel  # noqa: F401
from alembic import op

# revision identifiers, used by Alembic.
revision: str = "d5b8c2e4f617"
down_revision: Union[str, Sequence[str], None] = "c8e2f5a7b901"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    with op.batch_alter_table("eval_runs") as batch_op:
        batch_op.add_column(
            sa.Column("scenario_version", sa.Integer(), nullable=False, server_default="1")
        )
    # 存量运行回填其场景当前版本；孤儿运行（场景已删）保持默认 1
    op.execute(
        "UPDATE eval_runs SET scenario_version = COALESCE("
        "(SELECT version FROM scenarios WHERE scenarios.id = eval_runs.scenario_id), 1)"
    )


def downgrade() -> None:
    with op.batch_alter_table("eval_runs") as batch_op:
        batch_op.drop_column("scenario_version")
