#!/usr/bin/env python3
"""
修改 oauth_access_tokens 表的 app_id 字段为可空
"""
import pymysql
import os
from urllib.parse import urlparse

# 导入配置
import sys
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'src'))
from app.core.config import config_handler

print("=" * 60)
print("修改 oauth_access_tokens 表结构")
print("=" * 60)

# 获取数据库配置
database_url = config_handler.get("admin_app", "DATABASE_URL", "")
parsed = urlparse(database_url)

try:
    conn = pymysql.connect(
        host=parsed.hostname,
        port=parsed.port,
        user=parsed.username,
        password=parsed.password,
        database=parsed.path[1:] if parsed.path else None,
        charset='utf8mb4'
    )
    
    cursor = conn.cursor()
    
    # 修改 app_id 字段为可空
    print("\n修改 app_id 字段为可空...")
    cursor.execute("""
        ALTER TABLE oauth_access_tokens 
        MODIFY COLUMN app_id CHAR(36) NULL COMMENT '应用ID（系统内部登录时可为空）'
    """)
    
    conn.commit()
    print("✅ 修改成功！")
    
    # 验证修改
    cursor.execute("DESCRIBE oauth_access_tokens")
    columns = cursor.fetchall()
    
    print("\n表结构:")
    for col in columns:
        if col[0] == 'app_id':
            print(f"  app_id: {col[1]}, NULL={col[2]}, Key={col[3]}, Default={col[4]}")
    
    cursor.close()
    conn.close()
    
except Exception as e:
    print(f"❌ 错误: {e}")
    import traceback
    traceback.print_exc()

print("\n" + "=" * 60)
