"""
数据库迁移脚本：为 messages 表添加 message_type 字段
用于支持不同类型的消息（text, emoji, image）
"""

from sqlalchemy import create_engine, text
from database import SQLALCHEMY_DATABASE_URL

def migrate():
    """执行数据库迁移"""
    engine = create_engine(SQLALCHEMY_DATABASE_URL)
    
    with engine.connect() as conn:
        # 检查字段是否已存在
        result = conn.execute(text("""
            SELECT COUNT(*) as count 
            FROM pragma_table_info('messages') 
            WHERE name='message_type'
        """))
        
        count = result.fetchone()[0]
        
        if count == 0:
            print("正在添加 message_type 字段...")
            # 添加 message_type 字段，默认值为 'text'
            conn.execute(text("""
                ALTER TABLE messages 
                ADD COLUMN message_type VARCHAR DEFAULT 'text'
            """))
            conn.commit()
            print("✓ message_type 字段添加成功")
        else:
            print("✓ message_type 字段已存在，无需迁移")

if __name__ == "__main__":
    print("开始数据库迁移...")
    try:
        migrate()
        print("数据库迁移完成！")
    except Exception as e:
        print(f"迁移失败: {e}")
        import traceback
        traceback.print_exc()
