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

def check_pending_jobs():
    """檢查等待處理的任務狀態"""
    
    app = create_app()
    
    with app.app_context():
        print("=== 檢查等待處理的任務 ===")
        
        # 查找所有等待處理的任務
        pending_jobs = TranslationJob.query.filter_by(status='PENDING').order_by(TranslationJob.created_at.desc()).all()
        
        print(f"找到 {len(pending_jobs)} 個等待處理的任務:")
        
        for job in pending_jobs:
            print(f"\n任務ID: {job.job_uuid}")
            print(f"  原始檔名: {job.original_filename}")
            print(f"  目標語言: {job.target_languages}")
            print(f"  創建時間: {job.created_at}")
            print(f"  進度: {job.progress}%")
            print(f"  狀態: {job.status}")
            print(f"  用戶ID: {job.user_id}")
            
            if job.error_message:
                print(f"  錯誤信息: {job.error_message}")
        
        # 檢查其他狀態的任務
        print(f"\n=== 任務統計 ===")
        all_jobs = TranslationJob.query.all()
        status_counts = {}
        for job in all_jobs:
            status_counts[job.status] = status_counts.get(job.status, 0) + 1
        
        for status, count in status_counts.items():
            print(f"{status}: {count}")
        
        # 檢查最新任務的詳細信息
        if pending_jobs:
            latest_job = pending_jobs[0]
            print(f"\n=== 最新任務詳細信息 ===")
            print(f"任務UUID: {latest_job.job_uuid}")
            print(f"檔案路徑: {latest_job.file_path}")
            print(f"目標語言: {latest_job.target_languages}")
            
            # 檢查檔案是否存在
            from pathlib import Path
            if latest_job.file_path and Path(latest_job.file_path).exists():
                file_size = Path(latest_job.file_path).stat().st_size
                print(f"檔案存在: {latest_job.file_path} ({file_size:,} bytes)")
            else:
                print(f"檔案不存在: {latest_job.file_path}")
            
            # 檢查原始檔案記錄
            original_file = latest_job.get_original_file()
            if original_file:
                print(f"原始檔案記錄: {original_file.filename}")
                print(f"  檔案大小: {original_file.file_size:,} bytes")
                print(f"  檔案路徑: {original_file.file_path}")

if __name__ == "__main__":
    check_pending_jobs()