#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Test the fixed translation service
"""

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.services.translation_service import TranslationService
from app.models.job import TranslationJob

def test_fixed_translation_service():
    """Test the fixed translation service on a real job"""
    
    app = create_app()
    
    with app.app_context():
        # Get the most recent job to test with
        job = TranslationJob.query.order_by(TranslationJob.created_at.desc()).first()
        
        if not job:
            print("No jobs found to test")
            return
        
        print(f"Testing translation service on job: {job.job_uuid}")
        print(f"Original filename: {job.original_filename}")
        print(f"Target languages: {job.target_languages}")
        print(f"File path: {job.file_path}")
        
        # Reset job status to PENDING for testing
        job.status = 'PENDING'
        job.progress = 0.0
        job.error_message = None
        
        from app import db
        db.session.commit()
        
        print(f"Reset job status to PENDING")
        
        # Create translation service and test
        service = TranslationService()
        
        try:
            print("Starting translation...")
            result = service.translate_document(job.job_uuid)
            
            print(f"Translation completed!")
            print(f"Result: {result}")
            
            # Check the job status
            db.session.refresh(job)
            print(f"Final job status: {job.status}")
            print(f"Progress: {job.progress}%")
            print(f"Total tokens: {job.total_tokens}")
            print(f"Total cost: ${job.total_cost}")
            
            if job.error_message:
                print(f"Error message: {job.error_message}")
            
            # Check translated files
            translated_files = job.get_translated_files()
            print(f"Generated {len(translated_files)} translated files:")
            for tf in translated_files:
                print(f"  - {tf.filename} ({tf.language_code}) - Size: {tf.file_size} bytes")
                
                # Check if file exists and has content
                from pathlib import Path
                if Path(tf.file_path).exists():
                    size = Path(tf.file_path).stat().st_size
                    print(f"    File exists with {size} bytes")
                    
                    # Quick check if it contains translations (different from original)
                    if size != job.get_original_file().file_size:
                        print(f"    ✅ File size differs from original - likely contains translations")
                    else:
                        print(f"    ⚠️  File size same as original - may not contain translations")
                else:
                    print(f"    ❌ File not found at: {tf.file_path}")
            
        except Exception as e:
            print(f"Translation failed with error: {e}")
            import traceback
            traceback.print_exc()

if __name__ == "__main__":
    test_fixed_translation_service()