#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
修正通知表結構腳本
"""

import pymysql
import os
from dotenv import load_dotenv

# 載入環境變數
load_dotenv('C:/Users/EGG/WORK/data/user_scrip/TOOL/env.txt')

def fix_notification_table():
    """修正通知表的欄位名稱"""
    try:
        # 連接資料庫
        connection = pymysql.connect(
            host=os.getenv('DB_HOST', 'localhost'),
            user=os.getenv('DB_USER', 'root'),
            password=os.getenv('DB_PASSWORD', ''),
            database=os.getenv('DB_NAME', 'doc_translator'),
            charset='utf8mb4'
        )

        with connection.cursor() as cursor:
            # 檢查 dt_notifications 表結構
            cursor.execute('DESCRIBE dt_notifications')
            columns = cursor.fetchall()
            
            print('Current table structure:')
            for col in columns:
                print(f'  {col[0]} {col[1]}')
            
            # 檢查是否有 metadata 欄位
            has_metadata = any(col[0] == 'metadata' for col in columns)
            has_extra_data = any(col[0] == 'extra_data' for col in columns)
            
            print(f'\nHas metadata column: {has_metadata}')
            print(f'Has extra_data column: {has_extra_data}')
            
            if has_metadata and not has_extra_data:
                print('\nRenaming metadata column to extra_data...')
                cursor.execute('ALTER TABLE dt_notifications CHANGE metadata extra_data JSON NULL COMMENT "額外數據"')
                connection.commit()
                print('✅ Column renamed successfully')
                
                # 再次檢查結構
                cursor.execute('DESCRIBE dt_notifications')
                columns = cursor.fetchall()
                print('\nUpdated table structure:')
                for col in columns:
                    print(f'  {col[0]} {col[1]}')
                    
            elif has_extra_data:
                print('✅ extra_data column already exists')
            else:
                print('❌ Neither metadata nor extra_data column found')
                
        connection.close()
        print('\n✅ Database structure check completed')
        
    except Exception as e:
        print(f'❌ Error fixing notification table: {e}')
        import traceback
        traceback.print_exc()

if __name__ == '__main__':
    fix_notification_table()