#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
修復用戶ID不匹配問題
"""

import sys
import os

# Fix encoding for Windows console
if sys.stdout.encoding != 'utf-8':
    sys.stdout.reconfigure(encoding='utf-8')
if sys.stderr.encoding != 'utf-8':
    sys.stderr.reconfigure(encoding='utf-8')

sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'app'))

from app import create_app, db
from sqlalchemy import text

def fix_user_id():
    """修復用戶ID - 將ID從1改回2以匹配JWT Token"""
    
    app = create_app()
    
    with app.app_context():
        print("=== 修復用戶ID不匹配問題 ===")
        
        try:
            # 停用外鍵檢查
            db.session.execute(text("SET FOREIGN_KEY_CHECKS = 0"))
            
            # 將用戶ID從1改為2
            result = db.session.execute(text("UPDATE dt_users SET id = 2 WHERE id = 1"))
            print(f"更新了 {result.rowcount} 筆用戶記錄")
            
            # 重新設定自增起始值
            db.session.execute(text("ALTER TABLE dt_users AUTO_INCREMENT = 3"))
            
            # 重新啟用外鍵檢查
            db.session.execute(text("SET FOREIGN_KEY_CHECKS = 1"))
            
            db.session.commit()
            
            print("✅ 用戶ID已從1改為2，匹配JWT Token")
            
            # 驗證
            user = db.session.execute(text("SELECT id, username, email FROM dt_users")).fetchone()
            if user:
                print(f"確認用戶: ID={user[0]}, 用戶名={user[1]}, Email={user[2]}")
            
        except Exception as e:
            print(f"❌ 修復失敗: {str(e)}")
            db.session.rollback()
            # 確保重新啟用外鍵檢查
            try:
                db.session.execute(text("SET FOREIGN_KEY_CHECKS = 1"))
                db.session.commit()
            except:
                pass
            raise

if __name__ == "__main__":
    fix_user_id()