import pymysql

db_config = {
    "host": "rm-f8ze60yirdj8786u2.mysql.rds.aliyuncs.com",
    "port": 3306,
    "user": "root",
    "password": "csqz@20255",
    "db": "csqz-client",
    "charset": "utf8mb4",
    "cursorclass": pymysql.cursors.DictCursor
}

def migrate():
    conn = pymysql.connect(**db_config)
    try:
        with conn.cursor() as cursor:
            # 1. Add ai_status and ai_content to genealogy_records
            print("Checking genealogy_records table...")
            cursor.execute("DESCRIBE genealogy_records")
            columns = [col['Field'] for col in cursor.fetchall()]
            
            if 'ai_status' not in columns:
                print("Adding ai_status column...")
                cursor.execute("ALTER TABLE genealogy_records ADD COLUMN ai_status INT DEFAULT 0 COMMENT '0:未开始, 1:处理中, 2:成功, 3:失败'")
            
            if 'ai_content' not in columns:
                print("Adding ai_content column...")
                cursor.execute("ALTER TABLE genealogy_records ADD COLUMN ai_content LONGTEXT COMMENT 'AI解析结果JSON'")

            # 2. Add source_record_id to family_member_info
            print("Checking family_member_info table...")
            cursor.execute("DESCRIBE family_member_info")
            member_columns = [col['Field'] for col in cursor.fetchall()]

            if 'source_record_id' not in member_columns:
                print("Adding source_record_id column...")
                cursor.execute("ALTER TABLE family_member_info ADD COLUMN source_record_id INT DEFAULT NULL COMMENT '关联的原始图片记录ID'")
                
        conn.commit()
        print("Migration completed successfully.")
    except Exception as e:
        print(f"Migration failed: {e}")
        conn.rollback()
    finally:
        conn.close()

if __name__ == "__main__":
    migrate()
