#!/usr/bin/env python3
"""
Test script to verify comprehensive logging is working correctly.

This script simulates a video upload request flow to test all logging components.
"""

import os
import sys
import django
from pathlib import Path

# Add the project root to Python path
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))

# Setup Django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'src.settings')
django.setup()

import logging
import threading
from io import BytesIO
from django.core.files.uploadedfile import SimpleUploadedFile
from django.contrib.auth import get_user_model
from package_details.utils import ensure_user_has_storage_capacity
from common.storage.factory import StorageFactory

# Setup logging
logger = logging.getLogger('test_logging')

def test_logging_system():
    """Test the comprehensive logging system."""
    
    # Set up request context
    request_id = 'test_req_12345'
    threading.current_thread().request_id = request_id
    
    logger.info("Starting logging system test", extra={
        'request_id': request_id,
        'test_stage': 'initialization'
    })
    
    try:
        # Test 1: Storage Factory Logging
        logger.info("Testing storage factory logging")
        storage_backend = StorageFactory.get_storage_backend()
        logger.info(f"Storage backend type: {StorageFactory.get_backend_type()}")
        
        # Test 2: Create a test user (if needed)
        User = get_user_model()
        test_user = User.objects.filter(username='test_logging_user').first()
        if not test_user:
            logger.info("Creating test user for logging test")
            test_user = User.objects.create_user(
                username='test_logging_user',
                email='test@example.com',
                password='testpass123'
            )
        
        # Test 3: Create a mock video file
        logger.info("Creating mock video file for testing")
        video_content = b"fake video content for testing" * 1000  # ~30KB
        mock_video = SimpleUploadedFile(
            name="test_video.mp4",
            content=video_content,
            content_type="video/mp4"
        )
        
        # Test 4: Test storage capacity logging
        logger.info("Testing storage capacity logging")
        try:
            capacity_result = ensure_user_has_storage_capacity(
                user=test_user,
                incoming_file=mock_video,
                field_name="review_video"
            )
            logger.info(f"Storage capacity check result: {capacity_result}")
        except Exception as e:
            logger.error(f"Storage capacity check failed: {str(e)}")
        
        # Test 5: Test different log levels
        logger.debug("This is a debug message")
        logger.info("This is an info message")
        logger.warning("This is a warning message")
        logger.error("This is an error message")
        
        logger.info("Logging system test completed successfully", extra={
            'request_id': request_id,
            'test_stage': 'completion',
            'result': 'success'
        })
        
        print("✅ Logging test completed successfully!")
        print("📁 Check the following log files:")
        print("   - logs/django.log")
        print("   - logs/requests.log") 
        print("   - logs/storage.log")
        print("   - logs/errors.log")
        print("\n🔍 Use the analysis script to view results:")
        print(f"   python scripts/analyze_logs.py --request-id {request_id}")
        
    except Exception as e:
        logger.error(f"Logging test failed: {str(e)}", extra={
            'request_id': request_id,
            'test_stage': 'error',
            'error_message': str(e)
        })
        print(f"❌ Logging test failed: {str(e)}")
        return False
    
    return True

if __name__ == '__main__':
    success = test_logging_system()
    sys.exit(0 if success else 1)