"""
Test script for the new last sync query functionality
"""
import sys
import os
from pathlib import Path

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

def test_imports():
    """Test that all necessary imports work"""
    print("Testing imports...")
    try:
        from mbetterclient.api_client.client import ReportsSyncResponseHandler
        print("✓ ReportsSyncResponseHandler imported successfully")
        return True
    except Exception as e:
        print(f"✗ Failed to import ReportsSyncResponseHandler: {e}")
        return False

def test_method_exists():
    """Test that new methods exist in ReportsSyncResponseHandler"""
    print("\nTesting method existence...")
    try:
        from mbetterclient.api_client.client import ReportsSyncResponseHandler
        from mbetterclient.database.manager import DatabaseManager
        from mbetterclient.config.manager import ConfigManager
        
        # Create a mock instance (we won't actually run it)
        # Just check that the methods exist
        methods_to_check = [
            'query_server_last_sync',
            'recover_local_tracking',
            'needs_recovery'
        ]
        
        for method_name in methods_to_check:
            if hasattr(ReportsSyncResponseHandler, method_name):
                print(f"✓ Method '{method_name}' exists")
            else:
                print(f"✗ Method '{method_name}' NOT found")
                return False
        
        return True
    except Exception as e:
        print(f"✗ Error checking methods: {e}")
        return False

def test_endpoint_configuration():
    """Test that the new endpoint is configured"""
    print("\nTesting endpoint configuration...")
    try:
        from mbetterclient.api_client.client import APIClient
        from mbetterclient.core.message_bus import MessageBus
        from mbetterclient.database.manager import DatabaseManager
        from mbetterclient.config.manager import ConfigManager
        from mbetterclient.config.settings import ApiConfig
        
        # Check if _get_default_endpoints method exists
        if hasattr(APIClient, '_get_default_endpoints'):
            print("✓ _get_default_endpoints method exists")
            
            # We can't actually instantiate APIClient without a full setup,
            # but we can check the method signature
            import inspect
            sig = inspect.signature(APIClient._get_default_endpoints)
            print(f"✓ Method signature: {sig}")
            return True
        else:
            print("✗ _get_default_endpoints method NOT found")
            return False
            
    except Exception as e:
        print(f"✗ Error checking endpoint configuration: {e}")
        import traceback
        traceback.print_exc()
        return False

def test_integration():
    """Test that the integration is correct"""
    print("\nTesting integration...")
    try:
        from mbetterclient.api_client.client import ReportsSyncResponseHandler
        import inspect
        
        # Check that collect_report_data method exists and has the right signature
        if hasattr(ReportsSyncResponseHandler, 'collect_report_data'):
            print("✓ collect_report_data method exists")
            
            sig = inspect.signature(ReportsSyncResponseHandler.collect_report_data)
            print(f"✓ Method signature: {sig}")
            return True
        else:
            print("✗ collect_report_data method NOT found")
            return False
            
    except Exception as e:
        print(f"✗ Error checking integration: {e}")
        return False

def main():
    """Run all tests"""
    print("=" * 60)
    print("Testing Last Sync Query Implementation")
    print("=" * 60)
    
    results = []
    
    # Run tests
    results.append(("Imports", test_imports()))
    results.append(("Method Existence", test_method_exists()))
    results.append(("Endpoint Configuration", test_endpoint_configuration()))
    results.append(("Integration", test_integration()))
    
    # Print summary
    print("\n" + "=" * 60)
    print("Test Summary")
    print("=" * 60)
    
    passed = sum(1 for _, result in results if result)
    total = len(results)
    
    for test_name, result in results:
        status = "✓ PASS" if result else "✗ FAIL"
        print(f"{test_name:.<40} {status}")
    
    print(f"\nTotal: {passed}/{total} tests passed")
    
    if passed == total:
        print("\n✓ All tests passed!")
        return 0
    else:
        print(f"\n✗ {total - passed} test(s) failed")
        return 1

if __name__ == "__main__":
    sys.exit(main())