"""202602061730

Revision ID: bab823f7cc82
Revises: ef0787b85c35
Create Date: 2026-02-06 17:24:48.600823

"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql

# revision identifiers, used by Alembic.
revision: str = 'bab823f7cc82'
down_revision: Union[str, None] = 'ef0787b85c35'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    # 1. 先添加 memory_config 表的列
    op.add_column('memory_config', sa.Column('is_default', sa.Boolean(), nullable=True, comment='是否为工作空间默认配置'))
    
    # 2. 再添加 end_users 表的列和外键
    op.add_column('end_users', sa.Column('memory_config_id', sa.UUID(), nullable=True, comment='关联的记忆配置ID'))
    op.create_index(op.f('ix_end_users_memory_config_id'), 'end_users', ['memory_config_id'], unique=False)
    op.create_foreign_key(None, 'end_users', 'memory_config', ['memory_config_id'], ['config_id'])
    
    # 3. 最后安全删除备份表（如果存在）
    conn = op.get_bind()
    inspector = sa.inspect(conn)
    if 'model_api_keys_backup_20260123' in inspector.get_table_names():
        op.drop_table('model_api_keys_backup_20260123')
    # ### end Alembic commands ###


def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    # 1. 先恢复备份表
    op.create_table('model_api_keys_backup_20260123',
    sa.Column('id', sa.UUID(), autoincrement=False, nullable=True),
    sa.Column('model_name', sa.VARCHAR(), autoincrement=False, nullable=True),
    sa.Column('provider', sa.VARCHAR(), autoincrement=False, nullable=True),
    sa.Column('api_key', sa.VARCHAR(), autoincrement=False, nullable=True),
    sa.Column('api_base', sa.VARCHAR(), autoincrement=False, nullable=True),
    sa.Column('config', postgresql.JSON(astext_type=sa.Text()), autoincrement=False, nullable=True),
    sa.Column('usage_count', sa.VARCHAR(), autoincrement=False, nullable=True),
    sa.Column('last_used_at', postgresql.TIMESTAMP(precision=6), autoincrement=False, nullable=True),
    sa.Column('is_active', sa.BOOLEAN(), autoincrement=False, nullable=True),
    sa.Column('priority', sa.VARCHAR(), autoincrement=False, nullable=True),
    sa.Column('created_at', postgresql.TIMESTAMP(precision=6), autoincrement=False, nullable=True),
    sa.Column('updated_at', postgresql.TIMESTAMP(precision=6), autoincrement=False, nullable=True),
    sa.Column('model_config_id', sa.UUID(), autoincrement=False, nullable=True)
    )
    
    # 2. 删除 end_users 的外键和列
    op.drop_constraint(None, 'end_users', type_='foreignkey')
    op.drop_index(op.f('ix_end_users_memory_config_id'), table_name='end_users')
    op.drop_column('end_users', 'memory_config_id')
    
    # 3. 删除 memory_config 的列
    op.drop_column('memory_config', 'is_default')
    # ### end Alembic commands ###
