#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
直接檢查ROW291的具體內容
"""

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

def check_exact_row291():
    """直接檢查ROW291的具體內容"""
    
    print("=" * 80)
    print("直接檢查ROW291的具體內容")
    print("=" * 80)
    
    app = create_app()
    
    with app.app_context():
        from sqlalchemy import text as sql_text
        from app import db
        
        # 1. 直接查看ROW291
        print(f"1. 直接查看ROW291")
        print("-" * 60)
        
        result = db.session.execute(sql_text("""
            SELECT id, source_text, translated_text, source_language, target_language, created_at
            FROM dt_translation_cache 
            WHERE id = 291
        """))
        
        row291 = result.fetchone()
        
        if not row291:
            print("❌ ROW291 不存在")
        else:
            print(f"✅ ROW291 存在:")
            print(f"  ID: {row291[0]}")
            print(f"  原文: {repr(row291[1])}")
            print(f"  翻譯: {repr(row291[2])}")
            print(f"  源語言: {row291[3]}")
            print(f"  目標語言: {row291[4]}")
            print(f"  創建時間: {row291[5]}")
            
            # 檢查是否為D2內容
            d2_content = "與 WB inline 串線（DB→WB）、時效快；支援 Sn/Au 晶片\n最小可支援9mil晶粒\n支援EAP管控"
            
            if row291[1] == d2_content:
                print(f"✅ 這確實是D2的內容！")
                
                if row291[4] == 'ko':
                    print(f"✅ 而且是韓文翻譯")
                    print(f"   韓文翻譯: {row291[2]}")
                    
                    # 測試這個翻譯是否能被映射邏輯找到
                    print(f"\n測試映射查找:")
                    search_result = db.session.execute(sql_text("""
                        SELECT translated_text 
                        FROM dt_translation_cache 
                        WHERE source_text = :text AND target_language = :lang
                        ORDER BY created_at DESC 
                        LIMIT 1
                    """), {'text': d2_content, 'lang': 'ko'})
                    
                    search_row = search_result.fetchone()
                    if search_row:
                        print(f"   ✅ 映射查找成功: {repr(search_row[0][:50])}...")
                        if search_row[0] == row291[2]:
                            print(f"   ✅ 內容完全一致")
                        else:
                            print(f"   ❌ 內容不一致")
                            print(f"      ROW291: {repr(row291[2][:50])}...")
                            print(f"      查找到: {repr(search_row[0][:50])}...")
                    else:
                        print(f"   ❌ 映射查找失敗")
                else:
                    print(f"❌ 不是韓文翻譯，而是 {row291[4]}")
            else:
                print(f"❌ 不是D2的內容")
                print(f"   實際內容: {repr(row291[1][:50])}...")
        
        # 2. 查找ROW290-295的所有記錄
        print(f"\n2. 查找ROW290-295的所有記錄")
        print("-" * 60)
        
        result = db.session.execute(sql_text("""
            SELECT id, source_text, translated_text, source_language, target_language, created_at
            FROM dt_translation_cache 
            WHERE id >= 290 AND id <= 295
            ORDER BY id
        """))
        
        nearby_records = result.fetchall()
        
        for record in nearby_records:
            print(f"\nROW {record[0]} ({record[3]} -> {record[4]}):")
            print(f"  原文: {repr(record[1][:40])}...")
            print(f"  翻譯: {repr(record[2][:40])}...")
            print(f"  時間: {record[5]}")
        
        # 3. 查找所有D2相關的翻譯記錄（包含部分匹配）
        print(f"\n3. 查找所有包含D2關鍵詞的記錄")
        print("-" * 60)
        
        result = db.session.execute(sql_text("""
            SELECT id, source_text, translated_text, source_language, target_language, created_at
            FROM dt_translation_cache 
            WHERE source_text LIKE '%WB inline%' OR source_text LIKE '%Sn/Au%'
            ORDER BY id
        """))
        
        d2_related_records = result.fetchall()
        
        print(f"找到 {len(d2_related_records)} 筆包含D2關鍵詞的記錄:")
        
        for record in d2_related_records:
            print(f"\nROW {record[0]} ({record[3]} -> {record[4]}):")
            print(f"  原文: {repr(record[1][:50])}...")
            print(f"  翻譯: {repr(record[2][:50])}...")
            print(f"  時間: {record[5]}")
            
            # 標示是否為完整的D2內容
            if "WB inline" in record[1] and "Sn/Au" in record[1] and "EAP" in record[1]:
                print(f"  🎯 這是完整的D2內容！")
    
    print(f"\n" + "=" * 80)
    print("ROW291具體內容檢查完成！")
    print("=" * 80)

if __name__ == "__main__":
    check_exact_row291()