#!/usr/bin/env python3
"""
Test script to verify file upload functionality
"""
import sys
import os
sys.path.insert(0, '.')

from app import create_app
from app.upload.file_handler import get_file_upload_handler
from werkzeug.datastructures import FileStorage
from io import BytesIO

def test_upload_configuration():
    """Test upload configuration and directory creation"""
    print("Testing upload configuration...")
    
    app = create_app('production')
    with app.app_context():
        print(f"✅ Upload folder configured as: {app.config['UPLOAD_FOLDER']}")
        
        # Test file handler initialization
        handler = get_file_upload_handler()
        handler._ensure_initialized()
        print(f"✅ Handler upload folder: {handler.upload_folder}")
        
        # Check if directory exists or can be created
        if os.path.exists(handler.upload_folder):
            print("✅ Upload directory exists")
        else:
            print("📁 Upload directory will be created on first upload")
            
        return handler

def test_file_upload():
    """Test actual file upload functionality"""
    print("\nTesting file upload functionality...")
    
    app = create_app('production')
    with app.app_context():
        handler = get_file_upload_handler()
        
        # Create a mock CSV file
        csv_content = b"Team A,Team B,Date,Time\nLiverpool,Arsenal,2024-01-15,15:00\nChelsea,ManU,2024-01-16,17:30"
        mock_file = FileStorage(
            stream=BytesIO(csv_content),
            filename="test_fixture.csv",
            content_type="text/csv"
        )
        
        # Test upload
        upload_record, error_message = handler.process_upload(
            mock_file, 'fixture', user_id=1
        )
        
        if error_message:
            print(f"❌ Upload failed: {error_message}")
            return False
        else:
            print(f"✅ Upload successful: {upload_record.filename}")
            print(f"   File path: {upload_record.file_path}")
            print(f"   File size: {upload_record.file_size} bytes")
            return True

if __name__ == "__main__":
    try:
        handler = test_upload_configuration()
        success = test_file_upload()
        
        if success:
            print("\n🎉 All tests passed! Upload functionality is working.")
        else:
            print("\n❌ Upload test failed.")
            
    except Exception as e:
        print(f"❌ Test error: {e}")
        import traceback
        traceback.print_exc()