"""add multi-model routing support

Revision ID: 0022_model_routing
Revises: 0021_periodic_report_async_jobs
"""

from alembic import op
import sqlalchemy as sa


revision = "0022_model_routing"
down_revision = "0021_periodic_report_async_jobs"
branch_labels = None
depends_on = None


def upgrade() -> None:
    op.add_column(
        "sys_model",
        sa.Column("is_default", sa.Integer(), nullable=False, server_default="0"),
    )
    op.create_index(
        "ix_sys_model_available_default",
        "sys_model",
        ["enabled", "is_default", "id"],
        unique=False,
    )
    # 兼容旧数据：原来唯一启用的模型直接成为默认主模型。
    op.execute(
        """
        UPDATE sys_model
        SET is_default = 1
        WHERE enabled = 1
          AND id = (
              SELECT selected.id
              FROM (
                  SELECT id
                  FROM sys_model
                  WHERE enabled = 1
                  ORDER BY id DESC
                  LIMIT 1
              ) AS selected
          )
        """
    )


def downgrade() -> None:
    # 回滚到旧语义前只保留默认模型为启用，避免旧代码随机选到分流模型。
    op.execute("UPDATE sys_model SET enabled = CASE WHEN is_default = 1 THEN 1 ELSE 0 END")
    op.drop_index("ix_sys_model_available_default", table_name="sys_model")
    op.drop_column("sys_model", "is_default")
