#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
修復缺失的翻譯快取記錄
"""

import sys
import os
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

# 設定編碼
sys.stdout.reconfigure(encoding='utf-8')

from app import create_app
from datetime import datetime

def fix_missing_translation_cache():
    """修復缺失的翻譯快取記錄"""
    
    print("=" * 80)
    print("修復缺失的翻譯快取記錄")
    print("=" * 80)
    
    app = create_app()
    
    with app.app_context():
        from sqlalchemy import text as sql_text
        from app import db
        
        # 需要補充的翻譯記錄
        missing_translations = [
            {
                'source_text': '製程',
                'target_language': 'ja',
                'translated_text': 'プロセス',  # 製程的日文翻譯
                'source_language': 'zh'
            }
        ]
        
        print(f"準備添加 {len(missing_translations)} 筆翻譯記錄到快取...")
        
        for translation in missing_translations:
            source_text = translation['source_text']
            target_language = translation['target_language']
            translated_text = translation['translated_text']
            source_language = translation['source_language']
            
            # 檢查是否已存在
            check_result = db.session.execute(sql_text("""
                SELECT id FROM dt_translation_cache 
                WHERE source_text = :source AND target_language = :target
                LIMIT 1
            """), {
                'source': source_text,
                'target': target_language
            })
            
            if check_result.fetchone():
                print(f"⚠️  翻譯記錄已存在: '{source_text}' -> {target_language}")
                continue
            
            # 計算source_text_hash
            import hashlib
            source_text_hash = hashlib.md5(source_text.encode('utf-8')).hexdigest()
            
            # 插入新的翻譯記錄
            insert_result = db.session.execute(sql_text("""
                INSERT INTO dt_translation_cache 
                (source_text_hash, source_text, translated_text, source_language, target_language)
                VALUES (:source_hash, :source, :translated, :source_lang, :target_lang)
            """), {
                'source_hash': source_text_hash,
                'source': source_text,
                'translated': translated_text,
                'source_lang': source_language,
                'target_lang': target_language
            })
            
            print(f"✅ 已添加翻譯記錄: '{source_text}' -> '{translated_text}' ({target_language})")
        
        # 提交變更
        db.session.commit()
        print(f"\n✅ 所有翻譯記錄已提交到資料庫")
        
        # 驗證添加結果
        print(f"\n驗證翻譯記錄:")
        for translation in missing_translations:
            source_text = translation['source_text']
            target_language = translation['target_language']
            
            verify_result = db.session.execute(sql_text("""
                SELECT translated_text, created_at 
                FROM dt_translation_cache 
                WHERE source_text = :source AND target_language = :target
                ORDER BY created_at DESC 
                LIMIT 1
            """), {
                'source': source_text,
                'target': target_language
            })
            
            row = verify_result.fetchone()
            if row:
                print(f"✅ '{source_text}' -> '{row[0]}' (時間: {row[1]})")
            else:
                print(f"❌ 驗證失敗: '{source_text}'")
    
    print(f"\n" + "=" * 80)
    print("修復完成！")
    print("=" * 80)

if __name__ == "__main__":
    fix_missing_translation_cache()