#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
重置資料庫 - 清空除 dt_users 外的所有表，並將用戶ID設為1
"""

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 app.models import User, TranslationJob, JobFile, TranslationCache, APIUsageStats, SystemLog
from sqlalchemy import text

def reset_database():
    """重置資料庫"""
    
    app = create_app()
    
    with app.app_context():
        print("=== 開始重置資料庫 ===")
        
        try:
            # 1. 先檢查現有用戶
            users = User.query.all()
            print(f"當前用戶數量: {len(users)}")
            for user in users:
                print(f"  ID: {user.id}, 用戶名: {user.username}, Email: {user.email}")
            
            if len(users) != 1:
                print("❌ 錯誤：應該只有一個用戶")
                return
            
            current_user = users[0]
            print(f"\n準備將用戶 ID {current_user.id} 改為 1")
            
            # 2. 停用外鍵檢查（MySQL）
            print("\n⏳ 停用外鍵檢查...")
            db.session.execute(text("SET FOREIGN_KEY_CHECKS = 0"))
            
            # 3. 清空相關表格（按依賴順序）
            print("\n🗑️ 清空相關表格...")
            
            # API使用統計
            deleted_stats = db.session.execute(text("DELETE FROM dt_api_usage_stats")).rowcount
            print(f"  已刪除 {deleted_stats} 筆 API 使用記錄")
            
            # 系統日誌
            deleted_logs = db.session.execute(text("DELETE FROM dt_system_logs")).rowcount
            print(f"  已刪除 {deleted_logs} 筆系統日誌")
            
            # 翻譯檔案
            deleted_files = db.session.execute(text("DELETE FROM dt_job_files")).rowcount
            print(f"  已刪除 {deleted_files} 筆檔案記錄")
            
            # 翻譯任務
            deleted_jobs = db.session.execute(text("DELETE FROM dt_translation_jobs")).rowcount
            print(f"  已刪除 {deleted_jobs} 筆翻譯任務")
            
            # 翻譯快取
            deleted_cache = db.session.execute(text("DELETE FROM dt_translation_cache")).rowcount
            print(f"  已刪除 {deleted_cache} 筆翻譯快取")
            
            # 4. 更新用戶ID為1
            print(f"\n🔄 更新用戶ID從 {current_user.id} 到 1...")
            if current_user.id != 1:
                db.session.execute(text("UPDATE dt_users SET id = 1 WHERE id = :old_id"), {'old_id': current_user.id})
                db.session.execute(text("ALTER TABLE dt_users AUTO_INCREMENT = 2"))
                print("  ✅ 用戶ID已更新為 1")
            else:
                print("  ✅ 用戶ID已經是 1")
            
            # 5. 重新啟用外鍵檢查
            print("\n⚡ 重新啟用外鍵檢查...")
            db.session.execute(text("SET FOREIGN_KEY_CHECKS = 1"))
            
            # 6. 提交所有變更
            db.session.commit()
            
            # 7. 驗證結果
            print("\n✅ 驗證結果:")
            users_after = User.query.all()
            for user in users_after:
                print(f"  用戶 ID: {user.id}, 用戶名: {user.username}, Email: {user.email}")
            
            jobs_count = db.session.execute(text("SELECT COUNT(*) FROM dt_translation_jobs")).scalar()
            files_count = db.session.execute(text("SELECT COUNT(*) FROM dt_job_files")).scalar()
            cache_count = db.session.execute(text("SELECT COUNT(*) FROM dt_translation_cache")).scalar()
            stats_count = db.session.execute(text("SELECT COUNT(*) FROM dt_api_usage_stats")).scalar()
            logs_count = db.session.execute(text("SELECT COUNT(*) FROM dt_system_logs")).scalar()
            
            print(f"  翻譯任務: {jobs_count}")
            print(f"  檔案記錄: {files_count}")
            print(f"  翻譯快取: {cache_count}")
            print(f"  API統計: {stats_count}")
            print(f"  系統日誌: {logs_count}")
            
            print(f"\n🎉 資料庫重置完成！")
            print(f"   - 保留用戶: ID=1, {users_after[0].username}")
            print(f"   - 清空了所有翻譯相關資料")
            print(f"   - 系統已準備好重新開始測試")
            
        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__":
    reset_database()