#!/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
from app.models.job import TranslationJob
from pathlib import Path

def check_recent_jobs():
    """檢查最近的任務狀態"""
    
    app = create_app()
    
    with app.app_context():
        print("=== 檢查所有任務狀態 ===")
        
        # 查找所有任務，按創建時間排序
        all_jobs = TranslationJob.query.order_by(TranslationJob.created_at.desc()).all()
        
        for i, job in enumerate(all_jobs, 1):
            print(f"\n【任務 {i}】")
            print(f"  UUID: {job.job_uuid}")
            print(f"  檔名: {job.original_filename}")
            print(f"  狀態: {job.status}")
            print(f"  進度: {job.progress}%")
            print(f"  創建時間: {job.created_at}")
            print(f"  目標語言: {job.target_languages}")
            print(f"  總tokens: {job.total_tokens}")
            print(f"  總成本: ${job.total_cost}")
            
            if job.error_message:
                print(f"  ❌ 錯誤: {job.error_message}")
            
            # 檢查翻譯檔案
            if job.status == 'COMPLETED':
                translated_files = job.get_translated_files()
                print(f"  📁 翻譯檔案數: {len(translated_files)}")
                
                for tf in translated_files:
                    file_path = Path(tf.file_path)
                    exists = "✅" if file_path.exists() else "❌"
                    size = file_path.stat().st_size if file_path.exists() else 0
                    print(f"    {exists} {tf.filename} ({tf.language_code}) - {size:,} bytes")
                    
                    # 檢查檔案內容是否真的有翻譯
                    if file_path.exists() and tf.filename.endswith('.docx'):
                        try:
                            from docx import Document
                            doc = Document(str(file_path))
                            paragraph_count = len([p for p in doc.paragraphs if p.text.strip()])
                            print(f"      段落數: {paragraph_count}")
                            
                            # 顯示前幾段內容
                            sample_texts = []
                            for p in doc.paragraphs[:3]:
                                if p.text.strip():
                                    sample_texts.append(p.text.strip()[:50])
                            
                            if sample_texts:
                                print(f"      範例文字: {sample_texts[0]}...")
                        except Exception as e:
                            print(f"      ⚠️ 無法讀取檔案: {e}")
                
                # 檢查原始檔案
                original_file = job.get_original_file()
                if original_file:
                    orig_path = Path(original_file.file_path)
                    orig_exists = "✅" if orig_path.exists() else "❌"
                    orig_size = orig_path.stat().st_size if orig_path.exists() else 0
                    print(f"  📄 原始檔案: {orig_exists} {original_file.filename} - {orig_size:,} bytes")

if __name__ == "__main__":
    check_recent_jobs()