#!/usr/bin/env python3
"""
Test script to demonstrate the logging system with rotation and cleanup
"""

import os
import sys
import time
from pathlib import Path

# Add the src directory to the path
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root / 'src'))

def test_logging_system():
    """Test the logging system with rotation and cleanup."""
    print("๐Ÿงช Testing Advanced Logging System")
    print("=" * 60)
    
    # Set up test environment
    os.environ['LOG_TO_FILE'] = 'true'
    os.environ['LOG_FILE_PATH'] = 'test_logs/bot_test.log'
    os.environ['LOG_MAX_SIZE_MB'] = '1'  # Small size for testing
    os.environ['LOG_BACKUP_COUNT'] = '3'
    os.environ['LOG_ROTATION_TYPE'] = 'size'
    os.environ['LOG_LEVEL'] = 'INFO'
    
    # Import after setting environment
    from logging_config import setup_logging, cleanup_logs, get_log_stats, format_log_stats
    
    print("๐Ÿ“Š Test Configuration:")
    print(f"   Log File: test_logs/bot_test.log")
    print(f"   Max Size: 1 MB")
    print(f"   Backup Count: 3")
    print(f"   Rotation Type: size")
    print()
    
    # Initialize logging
    print("๐Ÿ”ง Initializing logging system...")
    logger = setup_logging()
    print("โœ… Logging system initialized")
    print()
    
    # Generate lots of log entries to trigger rotation
    print("๐Ÿ“ Generating log entries to test rotation...")
    for i in range(1000):
        logger.info(f"Test log message {i:04d} - This is a sample trading bot log entry with some details about market data, orders, and trading activity.")
        
        if i % 100 == 0:
            print(f"   Generated {i} log entries...")
    
    print("โœ… Log generation complete")
    print()
    
    # Check log statistics
    print("๐Ÿ“Š Log File Statistics:")
    stats = get_log_stats()
    for key, value in stats.items():
        if key == 'current_size_mb' or key == 'total_size_mb':
            print(f"   {key}: {value:.2f} MB")
        else:
            print(f"   {key}: {value}")
    print()
    
    # Show formatted stats
    print("๐Ÿ“‹ Formatted Log Status:")
    formatted_stats = format_log_stats()
    print(formatted_stats)
    print()
    
    # Test cleanup function
    print("๐Ÿงน Testing log cleanup (keeping files from last 1 day)...")
    cleanup_logs(days_to_keep=1)
    print("โœ… Cleanup test complete")
    print()
    
    # Final statistics
    print("๐Ÿ“Š Final Statistics:")
    final_stats = get_log_stats()
    print(format_log_stats(final_stats))
    print()
    
    # Show actual files created
    test_log_dir = Path('test_logs')
    if test_log_dir.exists():
        print("๐Ÿ“ Created Log Files:")
        for log_file in sorted(test_log_dir.glob('*.log*')):
            size_mb = log_file.stat().st_size / (1024 * 1024)
            print(f"   ๐Ÿ“„ {log_file.name} ({size_mb:.2f} MB)")
    
    print()
    print("๐ŸŽ‰ Logging system test complete!")
    print()
    print("๐Ÿ’ก Key Features Demonstrated:")
    print("   โœ… Automatic log rotation by file size")
    print("   โœ… Backup file management") 
    print("   โœ… Log cleanup functionality")
    print("   โœ… Statistics and monitoring")
    print("   โœ… Configurable via environment variables")
    print()
    print("๐Ÿš€ Ready for production use!")

if __name__ == "__main__":
    test_logging_system()