#!/usr/bin/env python
"""
Quick test to verify all new components can be imported successfully.
Run this to ensure the Phase 5-7 implementation is properly set up.
"""

import sys
import os

# Add ws directory to path
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

def test_imports():
    """Test that all new components can be imported."""

    print("Testing Phase 5-7 Component Imports...")
    print("=" * 60)

    tests = []

    # Phase 5: Performance & Offline
    try:
        from performance.caching import PlayerDataCache, player_cache
        from performance.batch_messaging import MessageBatcher, message_batcher
        from performance.offline.queue import OfflineEventQueue, offline_queue
        tests.append(("✓", "Phase 5: Performance & Caching"))
    except Exception as e:
        tests.append(("✗", f"Phase 5: Performance & Caching - {e}"))

    # Phase 6: Analytics
    try:
        from analytics.events import AnalyticsTracker, track_event
        tests.append(("✓", "Phase 6: Analytics Events"))
    except Exception as e:
        tests.append(("✗", f"Phase 6: Analytics Events - {e}"))

    # Phase 6: Monitoring - Sentry
    try:
        from monitoring.sentry_setup import init_sentry, set_player_context
        tests.append(("✓", "Phase 6: Sentry Error Reporting"))
    except Exception as e:
        tests.append(("✗", f"Phase 6: Sentry Error Reporting - {e}"))

    # Phase 6: Monitoring - Performance
    try:
        from monitoring.performance import PerformanceMonitor, measure_performance
        tests.append(("✓", "Phase 6: Performance Monitoring"))
    except Exception as e:
        tests.append(("✗", f"Phase 6: Performance Monitoring - {e}"))

    # Phase 6: A/B Testing
    try:
        from experiments.ab_testing import ABTestingManager, get_variant
        tests.append(("✓", "Phase 6: A/B Testing"))
    except Exception as e:
        tests.append(("✗", f"Phase 6: A/B Testing - {e}"))

    # Phase 7: Health Check
    try:
        from deployment.health_check import HealthChecker, get_health_checker
        tests.append(("✓", "Phase 7: Health Check"))
    except Exception as e:
        tests.append(("✗", f"Phase 7: Health Check - {e}"))

    # Phase 7: GDPR Data Management
    try:
        from api.data_management import DataManagementService, export_user_data
        tests.append(("✓", "Phase 7: GDPR Data Management"))
    except Exception as e:
        tests.append(("✗", f"Phase 7: GDPR Data Management - {e}"))

    # Print results
    for status, message in tests:
        print(f"{status} {message}")

    print("=" * 60)

    # Count successes
    successes = sum(1 for status, _ in tests if status == "✓")
    total = len(tests)

    print(f"\nResults: {successes}/{total} components successfully imported")

    if successes == total:
        print("✓ All components are properly set up!")
        return True
    else:
        print("✗ Some components failed to import. Check error messages above.")
        return False


def test_basic_functionality():
    """Test basic functionality of key components."""

    print("\nTesting Basic Functionality...")
    print("=" * 60)

    try:
        # Test caching
        from performance.caching import PlayerDataCache
        cache = PlayerDataCache(maxsize=10, ttl=60)
        cache.set('test_player', {'name': 'Test'})
        data = cache.get('test_player')
        assert data is not None
        print("✓ Caching works")

        # Test batch messaging
        from performance.batch_messaging import MessageBatcher
        batcher = MessageBatcher(batch_size=5)
        stats = batcher.get_stats()
        assert 'batch_size' in stats
        print("✓ Batch messaging works")

        # Test offline queue
        from performance.offline.queue import OfflineEventQueue
        queue = OfflineEventQueue()
        queue.mark_offline('test_player')
        queue.queue_event('test_player', {'type': 'test'})
        events = queue.mark_online('test_player')
        assert len(events) == 1
        print("✓ Offline queue works")

        # Test A/B testing
        from experiments.ab_testing import ABTestingManager
        ab_manager = ABTestingManager()
        variant = ab_manager.get_variant('test_player', 'tutorial_flow')
        assert variant in ['control', 'treatment']
        print("✓ A/B testing works")

        # Test performance monitor
        from monitoring.performance import PerformanceMonitor
        monitor = PerformanceMonitor()
        monitor.record_duration('test_operation', 0.5)
        stats = monitor.get_stats('test_operation')
        assert stats is not None
        print("✓ Performance monitoring works")

        print("=" * 60)
        print("\n✓ All basic functionality tests passed!")
        return True

    except Exception as e:
        print(f"\n✗ Functionality test failed: {e}")
        import traceback
        traceback.print_exc()
        return False


if __name__ == "__main__":
    print("\n" + "=" * 60)
    print("PHASE 5-7 COMPONENTS VERIFICATION")
    print("=" * 60 + "\n")

    import_success = test_imports()

    if import_success:
        func_success = test_basic_functionality()

        if func_success:
            print("\n" + "=" * 60)
            print("✓ ALL TESTS PASSED - Components are ready to use!")
            print("=" * 60)
            sys.exit(0)

    print("\n" + "=" * 60)
    print("✗ SOME TESTS FAILED - Check errors above")
    print("=" * 60)
    sys.exit(1)
