#!/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

def check_table_structure():
    """檢查翻譯快取資料表結構"""
    
    print("=" * 80)
    print("檢查翻譯快取資料表結構")
    print("=" * 80)
    
    app = create_app()
    
    with app.app_context():
        from sqlalchemy import text as sql_text
        from app import db
        
        # 查詢資料表結構
        result = db.session.execute(sql_text("DESCRIBE dt_translation_cache"))
        
        print("dt_translation_cache 資料表結構:")
        print("-" * 60)
        
        rows = result.fetchall()
        for row in rows:
            row_data = [str(item) if item is not None else '' for item in row]
            print(f"  {row_data[0]:<20} | {row_data[1]:<15} | {row_data[2]:<5} | {row_data[3]:<5} | {row_data[4]:<10} | {row_data[5] if len(row_data) > 5 else ''}")
        
        print("\n" + "-" * 60)
        print("欄位說明: 欄位名稱 | 類型 | Null | Key | Default | Extra")
        
        # 查詢資料表中的資料筆數
        count_result = db.session.execute(sql_text("SELECT COUNT(*) FROM dt_translation_cache"))
        count = count_result.fetchone()[0]
        print(f"\n總記錄數: {count}")
        
        # 查詢最近的幾筆記錄
        recent_result = db.session.execute(sql_text("""
            SELECT source_text, translated_text, source_language, target_language, created_at 
            FROM dt_translation_cache 
            ORDER BY created_at DESC 
            LIMIT 5
        """))
        
        print(f"\n最近的翻譯記錄:")
        print("-" * 60)
        recent_rows = recent_result.fetchall()
        for i, (src, trans, src_lang, tgt_lang, created_at) in enumerate(recent_rows):
            print(f"  {i+1}. '{src[:20]}...' -> '{trans[:20]}...' ({src_lang}->{tgt_lang}) {created_at}")
    
    print("\n" + "=" * 80)
    print("檢查完成！")
    print("=" * 80)

if __name__ == "__main__":
    check_table_structure()