#!/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, db
from sqlalchemy import text

def check_db_structure():
    """檢查資料庫結構"""
    
    app = create_app()
    
    with app.app_context():
        print("=== 檢查資料庫結構 ===")
        
        # 列出所有表
        result = db.session.execute(text("SHOW TABLES"))
        tables = result.fetchall()
        
        print(f"資料庫中的表:")
        for table in tables:
            table_name = table[0]
            print(f"  - {table_name}")
            
            # 檢查表結構
            desc_result = db.session.execute(text(f"DESC {table_name}"))
            columns = desc_result.fetchall()
            
            for col in columns:
                print(f"    {col[0]} ({col[1]})")
        
        # 檢查特定任務的相關資料
        print(f"\n=== 檢查特定任務資料 ===")
        job_uuid = "9c6548ac-2f59-45f4-aade-0a9b3895bbfd"
        
        # 查詢任務資料
        job_result = db.session.execute(text("""
            SELECT id, job_uuid, status, progress, total_tokens, total_cost, target_languages
            FROM dt_translation_jobs 
            WHERE job_uuid = :uuid
        """), {'uuid': job_uuid})
        
        job_row = job_result.fetchone()
        if job_row:
            print(f"任務ID: {job_row[0]}")
            print(f"UUID: {job_row[1]}")
            print(f"狀態: {job_row[2]}")
            print(f"進度: {job_row[3]}")
            print(f"Tokens: {job_row[4]}")
            print(f"成本: {job_row[5]}")
            print(f"目標語言: {job_row[6]}")
            
            job_id = job_row[0]
            
            # 查詢相關檔案
            files_result = db.session.execute(text("""
                SELECT file_type, filename, language_code, file_size, created_at
                FROM dt_job_files 
                WHERE job_id = :job_id
            """), {'job_id': job_id})
            
            files = files_result.fetchall()
            print(f"\n相關檔案 ({len(files)}):")
            for file_row in files:
                print(f"  {file_row[0]}: {file_row[1]} ({file_row[2]}) - {file_row[3]} bytes")
            
            # 查詢翻譯cache（如果存在的話）
            if 'dt_translation_cache' in [t[0] for t in tables]:
                cache_result = db.session.execute(text("""
                    SELECT COUNT(*) FROM dt_translation_cache 
                    WHERE source_text IN (
                        SELECT SUBSTRING(source_text, 1, 50) 
                        FROM dt_translation_cache 
                        LIMIT 5
                    )
                """))
                cache_count = cache_result.scalar()
                print(f"\n翻譯快取記錄數: {cache_count}")
                
                # 取幾個範例
                sample_result = db.session.execute(text("""
                    SELECT source_text, target_language, translated_text 
                    FROM dt_translation_cache 
                    LIMIT 5
                """))
                
                samples = sample_result.fetchall()
                print(f"快取範例:")
                for sample in samples:
                    print(f"  {sample[0][:50]}... -> [{sample[1]}] {sample[2][:50]}...")
        else:
            print(f"找不到任務: {job_uuid}")

if __name__ == "__main__":
    check_db_structure()