#!/usr/bin/env python3
"""
Test script for file compression and email sending.
"""

import os
import zipfile
from features.export_mailer import ExportMailer

def create_test_large_file(filename="test_large.csv", size_mb=25):
    """Create a test large CSV file."""
    print(f"Creating test file {filename} (~{size_mb}MB)...")
    
    with open(filename, "w") as f:
        # Write header
        f.write("data\n")
        
        # Write data rows
        row = "test data row with some content to make it larger\n"
        target_size = size_mb * 1024 * 1024  # Convert MB to bytes
        current_size = 0
        
        while current_size < target_size:
            f.write(row)
            current_size += len(row.encode('utf-8'))
    
    actual_size = os.path.getsize(filename) / (1024 * 1024)
    print(f"Created {filename}: {actual_size:.2f}MB")
    return filename

def test_compression():
    """Test file compression functionality."""
    print("Testing file compression...")
    
    export_mailer = ExportMailer()
    
    # Test with small file (should not compress)
    small_file = "test_small.csv"
    if not os.path.exists(small_file):
        with open(small_file, "w") as f:
            f.write("small test data\n")
    
    result_small = export_mailer.compress_file_if_needed(small_file)
    print(f"Small file result: {result_small}")
    
    # Test with large file (should compress)
    large_file = create_test_large_file()
    result_large = export_mailer.compress_file_if_needed(large_file)
    print(f"Large file result: {result_large}")
    
    # Check sizes
    if result_large != large_file:
        original_size = os.path.getsize(large_file) / (1024 * 1024)
        compressed_size = os.path.getsize(result_large) / (1024 * 1024)
        print(f"Original: {original_size:.2f}MB -> Compressed: {compressed_size:.2f}MB")
        
        # Test sending compressed file
        from core.mailer import create_mailer
        from core.config import get_config
        
        config = get_config()
        mailer = create_mailer()
        
        print(f"\nTesting email with compressed file...")
        # Use the mailer class which has proper SSL configuration
        from core.config import get_config
        config = get_config()
        
        from core.mailer import send_mail
        success = send_mail(
            sendfrom=config.get('sendfrom'),
            sendto=config.get('sendto'),
            subject="TEST: Compressed File",
            body="TEST EMAIL WITH COMPRESSED FILE - PLEASE IGNORE",
            attachment_path=result_large,
            pwd=config.get('pwd'),
            mailserver=config.get('mailserver'),
            port=config.get_int('port', 465),  # Ensure port is 465
            ssl=config.get_int('ssl', 1)       # Ensure SSL is enabled
        )
        
        if success:
            print("✓ Email with compressed file sent successfully!")
        else:
            print("✗ Email with compressed file failed!")
        
        # Clean up
        os.remove(result_large)
    
    # Clean up
    os.remove(large_file)
    
    export_mailer.cleanup()

if __name__ == "__main__":
    test_compression()