#!/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_job_status():
    """檢查指定任務狀態"""
    
    app = create_app()
    
    with app.app_context():
        print("=== 檢查任務狀態 ===")
        
        job_uuid = "313e213e-6adf-457c-91a7-107fc3636c3a"
        job = TranslationJob.query.filter_by(job_uuid=job_uuid).first()
        
        if not job:
            print(f"任務不存在: {job_uuid}")
            return
        
        print(f"任務 UUID: {job.job_uuid}")
        print(f"檔名: {job.original_filename}")
        print(f"狀態: {job.status}")
        print(f"進度: {job.progress}%")
        print(f"總成本: ${job.total_cost}")
        print(f"總tokens: {job.total_tokens}")
        print(f"目標語言: {job.target_languages}")
        
        if job.error_message:
            print(f"❌ 錯誤: {job.error_message}")
        
        # 檢查翻譯檔案
        translated_files = job.get_translated_files()
        print(f"\n📁 翻譯檔案數: {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")
        
        # 檢查原始檔案
        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"\n📄 原始檔案: {orig_exists} {original_file.filename} - {orig_size:,} bytes")
        
        # 檢查所有檔案是否存在（用於批量下載）
        print(f"\n🔍 批量下載檢查:")
        all_files_exist = True
        
        if original_file:
            if not Path(original_file.file_path).exists():
                print(f"  ❌ 原始檔案缺失: {original_file.filename}")
                all_files_exist = False
        
        for tf in translated_files:
            if not Path(tf.file_path).exists():
                print(f"  ❌ 翻譯檔案缺失: {tf.filename}")
                all_files_exist = False
        
        if all_files_exist and len(translated_files) > 0:
            print(f"  ✅ 所有檔案都存在，批量下載應該可以正常工作")
        else:
            print(f"  ❌ 有檔案缺失，批量下載會失敗")

if __name__ == "__main__":
    check_job_status()