#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Test batch download functionality
"""

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'))

import tempfile
import zipfile
from pathlib import Path
from app import create_app
from app.models.job import TranslationJob

def test_batch_download():
    """Test batch download ZIP creation"""
    
    app = create_app()
    
    with app.app_context():
        # Get the most recent completed job
        job = TranslationJob.query.filter_by(status='COMPLETED').order_by(TranslationJob.created_at.desc()).first()
        
        if not job:
            print("No completed jobs found to test")
            return
        
        print(f"Testing batch download for job: {job.job_uuid}")
        print(f"Original filename: {job.original_filename}")
        print(f"Target languages: {job.target_languages}")
        
        # Get translated files
        translated_files = job.get_translated_files()
        original_file = job.get_original_file()
        
        print(f"Found {len(translated_files)} translated files:")
        for tf in translated_files:
            exists = Path(tf.file_path).exists()
            print(f"  - {tf.filename} ({tf.language_code}) - {'EXISTS' if exists else 'MISSING'}")
        
        if original_file:
            exists = Path(original_file.file_path).exists()
            print(f"Original file: {original_file.filename} - {'EXISTS' if exists else 'MISSING'}")
        
        # Test ZIP creation
        print(f"\n=== Testing ZIP creation ===")
        
        temp_dir = tempfile.gettempdir()
        zip_filename = f"{job.original_filename.split('.')[0]}_translations_{job.job_uuid[:8]}.zip"
        zip_path = Path(temp_dir) / zip_filename
        
        try:
            with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zip_file:
                files_added = 0
                
                # Add original file
                if original_file and Path(original_file.file_path).exists():
                    zip_file.write(
                        original_file.file_path,
                        f"original/{original_file.filename}"
                    )
                    files_added += 1
                    print(f"✅ Added original file: original/{original_file.filename}")
                
                # Add translated files
                for tf in translated_files:
                    file_path = Path(tf.file_path)
                    if file_path.exists():
                        archive_name = f"{tf.language_code}/{tf.filename}"
                        zip_file.write(str(file_path), archive_name)
                        files_added += 1
                        print(f"✅ Added translation: {archive_name}")
                    else:
                        print(f"❌ Translation file missing: {tf.file_path}")
                
                print(f"\nTotal files added to ZIP: {files_added}")
            
            # Check ZIP file
            if zip_path.exists():
                zip_size = zip_path.stat().st_size
                print(f"✅ ZIP file created successfully: {zip_filename} ({zip_size:,} bytes)")
                
                # List ZIP contents
                print(f"\n=== ZIP Contents ===")
                with zipfile.ZipFile(zip_path, 'r') as zip_file:
                    for info in zip_file.infolist():
                        print(f"  📁 {info.filename} - {info.file_size:,} bytes")
                
                # Test extracting a sample file to verify integrity
                print(f"\n=== Testing ZIP integrity ===")
                try:
                    with zipfile.ZipFile(zip_path, 'r') as zip_file:
                        # Test extraction of first file
                        if zip_file.namelist():
                            first_file = zip_file.namelist()[0]
                            extracted_data = zip_file.read(first_file)
                            print(f"✅ Successfully extracted {first_file} ({len(extracted_data):,} bytes)")
                        else:
                            print("❌ ZIP file is empty")
                except Exception as e:
                    print(f"❌ ZIP integrity test failed: {e}")
                
            else:
                print("❌ ZIP file was not created")
            
        except Exception as e:
            print(f"❌ ZIP creation failed: {e}")
            import traceback
            traceback.print_exc()
        
        finally:
            # Clean up
            if zip_path.exists():
                try:
                    zip_path.unlink()
                    print(f"\n🧹 Cleaned up temporary ZIP file")
                except Exception as e:
                    print(f"⚠️  Could not clean up ZIP file: {e}")

if __name__ == "__main__":
    test_batch_download()