"""
测试文件：验证 client_v2.py 与现有接口的兼容性
"""
import os
import sys
import json

# 将当前目录添加到路径
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

# 测试 client_v2.py
from client_v2 import KafkaClient, handle_message, delivery_callback

# 测试配置
hosts = 'localhost:9092'

def test_client_v2_interface():
    """测试 client_v2.py 的接口兼容性"""
    print("测试 KafkaClient V2 接口兼容性...")
    
    # 测试配置
    consumer_config = {
        'auto_offset_reset': 'earliest',
        'enable_auto_commit': True,
        'max_poll_interval_ms': 8000000,
        'heartbeat_interval_ms': 3000,
        'session_timeout_ms': 30000
    }
    
    security_protocol = 'SASL_PLAINTEXT'
    sasl_mechanism = 'PLAIN'
    
    try:
        # 测试客户端创建
        kafka_client = KafkaClient(
            brokers=hosts,
            group_id='test-group-id',
            consumer_config=consumer_config,
            security_protocol=security_protocol,
            sasl_mechanism=sasl_mechanism,
        )
        
        print("✅ KafkaClient 创建成功")
        
        # 测试方法存在性
        assert hasattr(kafka_client, 'produce_message'), "缺少 produce_message 方法"
        assert hasattr(kafka_client, 'consume_messages'), "缺少 consume_messages 方法"
        assert hasattr(kafka_client, 'produce_messages_in_batch'), "缺少 produce_messages_in_batch 方法"
        assert hasattr(kafka_client, 'consume_messages_with_threads'), "缺少 consume_messages_with_threads 方法"
        
        print("✅ 所有方法都存在")
        
        # 测试工具函数
        assert callable(handle_message), "handle_message 不可调用"
        assert callable(delivery_callback), "delivery_callback 不可调用"
        
        print("✅ 工具函数存在")
        
        return True
        
    except Exception as e:
        print(f"❌ 测试失败: {e}")
        return False

def test_serialization():
    """测试序列化功能"""
    print("\n测试序列化功能...")
    
    client = KafkaClient(brokers=hosts)
    
    # 测试不同类型的数据序列化
    test_cases = [
        ("string", "hello world"),
        ("dict", {"key": "value", "number": 123}),
        ("list", [1, 2, 3, "test"]),
        ("int", 42),
        ("float", 3.14),
        ("bool", True),
        ("none", None),
    ]
    
    for data_type, data in test_cases:
        try:
            serialized = client.default_serializer(data)
            print(f"✅ {data_type}: {type(data)} -> {type(serialized)}")
        except Exception as e:
            print(f"❌ {data_type} 序列化失败: {e}")

def test_error_handling():
    """测试错误处理"""
    print("\n测试错误处理...")
    
    try:
        # 测试参数验证
        client = KafkaClient(brokers=hosts)
        
        # 测试 produce_message 参数验证
        try:
            client.produce_message(topic="test")
            print("❌ 应该抛出参数错误")
        except AssertionError as e:
            print("✅ 参数验证正常")
        except Exception as e:
            print(f"⚠️  意外错误: {e}")
            
    except Exception as e:
        print(f"❌ 错误处理测试失败: {e}")

def compare_interfaces():
    """比较两个客户端的接口"""
    print("\n比较接口兼容性...")
    
    try:
        # 导入原始 client
        from client import KafkaClient as OriginalKafkaClient
        
        # 获取两个类的公共方法
        original_methods = set([m for m in dir(OriginalKafkaClient) if not m.startswith('_')])
        new_methods = set([m for m in dir(KafkaClient) if not m.startswith('_')])
        
        # 检查缺失的方法
        missing = original_methods - new_methods
        if missing:
            print(f"⚠️  缺失方法: {missing}")
        else:
            print("✅ 所有原始方法都存在")
            
        # 检查额外的方法
        extra = new_methods - original_methods
        if extra:
            print(f"ℹ️  额外方法: {extra}")
        
        # 检查方法签名
        import inspect
        
        common_methods = original_methods & new_methods
        for method_name in ['produce_message', 'consume_messages']:
            if method_name in common_methods:
                original_sig = inspect.signature(getattr(OriginalKafkaClient, method_name))
                new_sig = inspect.signature(getattr(KafkaClient, method_name))
                
                original_params = set(original_sig.parameters.keys())
                new_params = set(new_sig.parameters.keys())
                
                if original_params == new_params:
                    print(f"✅ {method_name} 参数签名匹配")
                else:
                    print(f"⚠️  {method_name} 参数差异:")
                    print(f"   原始: {original_params}")
                    print(f"   新: {new_params}")
        
    except ImportError:
        print("ℹ️  无法导入原始 client.py，跳过接口比较")
    except Exception as e:
        print(f"❌ 接口比较失败: {e}")

if __name__ == "__main__":
    print("=" * 50)
    print("Kafka Client V2 兼容性测试")
    print("=" * 50)
    
    success = test_client_v2_interface()
    test_serialization()
    test_error_handling()
    compare_interfaces()
    
    print("\n" + "=" * 50)
    if success:
        print("✅ 所有基础测试通过")
    else:
        print("❌ 测试未完全通过")
    print("=" * 50)