#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
檢查並清理重複用戶記錄
"""

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
from app.models.user import User
from app.models.job import TranslationJob
from app.models.stats import APIUsageStats

def check_and_clean_users():
    """檢查並清理重複用戶記錄"""
    
    app = create_app()
    
    with app.app_context():
        from app import db
        
        print("=== 檢查用戶記錄 ===")
        
        # 查看所有用戶
        users = User.query.order_by(User.id).all()
        
        for user in users:
            print(f"用戶 ID: {user.id}")
            print(f"  用戶名: {user.username}")
            print(f"  顯示名: {user.display_name}")
            print(f"  郵箱: {user.email}")
            print(f"  是否管理員: {user.is_admin}")
            print(f"  最後登入: {user.last_login}")
            print(f"  創建時間: {user.created_at}")
            
            # 檢查關聯記錄
            job_count = user.translation_jobs.count()
            print(f"  翻譯任務數: {job_count}")
            
            try:
                api_stats_count = db.session.query(APIUsageStats).filter_by(user_id=user.id).count()
                print(f"  API統計記錄數: {api_stats_count}")
            except:
                print(f"  API統計記錄數: 查詢失敗")
            
            print()
        
        # 尋找重複用戶名
        duplicate_usernames = db.session.query(User.username).group_by(User.username).having(db.func.count(User.id) > 1).all()
        
        if duplicate_usernames:
            print("=== 發現重複用戶名 ===")
            for (username,) in duplicate_usernames:
                print(f"重複用戶名: {username}")
                dup_users = User.query.filter_by(username=username).order_by(User.id).all()
                
                for i, user in enumerate(dup_users):
                    print(f"  [{i+1}] ID: {user.id}, 創建時間: {user.created_at}, 管理員: {user.is_admin}")
                    print(f"      任務數: {user.translation_jobs.count()}")
        
        # 檢查是否有ID=1和ID=2的用戶且共享相同郵箱
        user_id_1 = User.query.get(1)
        user_id_2 = User.query.get(2)
        
        if user_id_1 and user_id_2 and user_id_1.email == user_id_2.email:
            print("=== 發現重複用戶（相同郵箱） ===")
            print(f"ID=1: {user_id_1.username} ({user_id_1.email})")
            print(f"ID=2: {user_id_2.username} ({user_id_2.email})")
            print("準備刪除 ID=1 並將記錄轉移到 ID=2...")
            
            # 檢查關聯記錄
            jobs = user_id_1.translation_jobs.all()
            if jobs:
                print(f"轉移 {len(jobs)} 個翻譯任務到 ID=2")
                for job in jobs:
                    job.user_id = 2
            
            # 轉移API統計記錄
            api_stats = db.session.query(APIUsageStats).filter_by(user_id=1).all()
            if api_stats:
                print(f"轉移 {len(api_stats)} 個API統計記錄到用戶 ID=2")
                for stat in api_stats:
                    stat.user_id = 2
            
            # 提交轉移
            db.session.commit()
            print("✅ 記錄轉移完成")
            
            # 刪除用戶記錄
            try:
                db.session.delete(user_id_1)
                db.session.commit()
                print("✅ ID=1 用戶記錄已成功刪除")
            except Exception as e:
                print(f"❌ 刪除用戶記錄失敗: {e}")
                db.session.rollback()
        elif user_id_1:
            print("=== ID=1 用戶存在但沒有找到相同郵箱的ID=2用戶 ===")
            print("暫不刪除")
        
        print("\n=== 清理完成後的用戶狀態 ===")
        users = User.query.order_by(User.id).all()
        for user in users:
            print(f"ID: {user.id}, 用戶名: {user.username}, 管理員: {user.is_admin}, 任務數: {user.translation_jobs.count()}")

if __name__ == "__main__":
    check_and_clean_users()