"""add simple knowledge model capability

Revision ID: 0023_simple_knowledge_route
Revises: 0022_model_routing
"""

from alembic import op
import sqlalchemy as sa


revision = "0023_simple_knowledge_route"
down_revision = "0022_model_routing"
branch_labels = None
depends_on = None


def upgrade() -> None:
    # Existing models retain the capability so deployment behavior stays on the
    # current default model until an administrator explicitly reassigns it.
    op.add_column(
        "sys_model",
        sa.Column("allow_simple_knowledge", sa.Integer(), nullable=False, server_default="1"),
    )
    # Materialize the new three-state setting so the admin UI and runtime show
    # the same value even when the legacy emergency switch had been disabled.
    op.execute(
        """
        INSERT IGNORE INTO sys_system_config (config_key, config_value, description)
        SELECT
            'chat_model_routing_mode',
            CASE
                WHEN EXISTS (
                    SELECT 1
                    FROM sys_system_config
                    WHERE config_key = 'fixed_info_model_routing_enabled'
                      AND LOWER(TRIM(config_value)) NOT IN ('1', 'true', 'yes', 'on', '启用')
                ) THEN 'off'
                ELSE 'fixed_only'
            END,
            '正式问答模型分流规则：off / fixed_only / conservative'
        """
    )


def downgrade() -> None:
    # Preserve the closest legacy behavior before removing the new setting.
    op.execute(
        """
        UPDATE sys_system_config AS legacy
        JOIN sys_system_config AS current_mode
          ON current_mode.config_key = 'chat_model_routing_mode'
        SET legacy.config_value = CASE
            WHEN current_mode.config_value = 'off' THEN 'false'
            ELSE 'true'
        END
        WHERE legacy.config_key = 'fixed_info_model_routing_enabled'
        """
    )
    op.execute(
        """
        INSERT IGNORE INTO sys_system_config (config_key, config_value, description)
        SELECT
            'fixed_info_model_routing_enabled',
            CASE WHEN config_value = 'off' THEN 'false' ELSE 'true' END,
            '固定信息模型分流'
        FROM sys_system_config
        WHERE config_key = 'chat_model_routing_mode'
        """
    )
    op.execute("DELETE FROM sys_system_config WHERE config_key = 'chat_model_routing_mode'")
    op.drop_column("sys_model", "allow_simple_knowledge")
