#!/usr/bin/env python3
"""
测试 API 兼容性
验证 KafkaConsumerWrapper 提供与 confluent-kafka 兼容的 API
"""

import os
import sys
import logging

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

from client_v2 import KafkaClient

# 设置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

def test_timeout_parameter_compatibility():
    """测试 timeout 参数兼容性"""
    print("=== 测试 timeout 参数兼容性 ===")
    
    # 模拟业务代码调用方式
    try:
        # 创建 KafkaClient 实例（不实际连接）
        client = KafkaClient(
            brokers='localhost:9092',
            group_id='test-group',
            consumer_config={
                'auto_offset_reset': 'earliest'
            }
        )
        
        # 创建消费者（不实际订阅）
        consumer = client.create_consumer(topics=['test-topic'])
        
        # 测试不同的 poll 调用方式
        print("1. 测试 poll(timeout=1.0) 格式...")
        try:
            # 模拟业务代码调用方式
            result = consumer.poll(timeout=1.0)
            print("   ✓ poll(timeout=1.0) 调用成功")
        except Exception as e:
            print(f"   ✗ poll(timeout=1.0) 调用失败: {e}")
            return False
            
        print("2. 测试 poll(timeout_ms=1000) 格式...")
        try:
            # 测试 kafka-python 原生格式
            result = consumer.poll(timeout_ms=1000)
            print("   ✓ poll(timeout_ms=1000) 调用成功")
        except Exception as e:
            print(f"   ✗ poll(timeout_ms=1000) 调用失败: {e}")
            return False
            
        print("3. 测试 poll() 无参数格式...")
        try:
            result = consumer.poll()
            print("   ✓ poll() 无参数调用成功")
        except Exception as e:
            print(f"   ✗ poll() 无参数调用失败: {e}")
            return False
            
        return True
        
    except Exception as e:
        print(f"测试初始化失败: {e}")
        return False

def test_message_object_compatibility():
    """测试消息对象兼容性"""
    print("\n=== 测试消息对象兼容性 ===")
    
    try:
        from client_v2 import KafkaMessageWrapper
        
        # 创建模拟消息记录
        class MockRecord:
            def __init__(self):
                self.topic = "test-topic"
                self.partition = 0
                self.offset = 12345
                self.timestamp = 1234567890
                self.key = b"test-key"
                self.value = b"test-value"
                self.headers = [("header1", b"value1")]
        
        record = MockRecord()
        message = KafkaMessageWrapper(record)
        
        # 测试消息对象属性访问
        tests = [
            ("topic", message.topic()),
            ("partition", message.partition()),
            ("offset", message.offset()),
            ("timestamp", message.timestamp()),
            ("key", message.key()),
            ("value", message.value()),
            ("headers", message.headers()),
            ("error", message.error())
        ]
        
        for attr_name, value in tests:
            try:
                print(f"   ✓ {attr_name}: {value}")
            except Exception as e:
                print(f"   ✗ {attr_name}: 访问失败 - {e}")
                return False
                
        return True
        
    except Exception as e:
        print(f"消息对象测试失败: {e}")
        return False

def test_business_code_pattern():
    """测试业务代码调用模式"""
    print("\n=== 测试业务代码调用模式 ===")
    
    try:
        # 模拟业务代码中的调用模式
        POLL_TIMEOUT = 1.0
        
        # 创建消费者（模拟业务代码）
        client = KafkaClient(
            brokers='localhost:9092',
            group_id='business-test-group',
            consumer_config={
                'auto_offset_reset': 'latest'
            }
        )
        
        consumer = client.create_consumer(topics=['business-topic'])
        
        # 模拟业务代码中的循环调用
        print("模拟业务代码调用模式...")
        try:
            # 这是业务代码中的实际调用方式
            msg = consumer.poll(timeout=POLL_TIMEOUT)
            print("   ✓ 业务代码模式调用成功")
            
            # 测试消息对象访问
            if msg is not None:
                print(f"   ✓ 消息对象 topic: {msg.topic()}")
                print(f"   ✓ 消息对象 value: {msg.value()}")
            else:
                print("   ✓ 无消息返回（正常情况）")
                
            return True
            
        except Exception as e:
            print(f"   ✗ 业务代码模式调用失败: {e}")
            return False
            
    except Exception as e:
        print(f"业务代码模式测试失败: {e}")
        return False

def main():
    """主测试函数"""
    print("开始 API 兼容性测试...")
    
    results = []
    
    # 运行各项测试
    results.append(test_timeout_parameter_compatibility())
    results.append(test_message_object_compatibility())
    results.append(test_business_code_pattern())
    
    # 汇总结果
    print("\n=== 测试结果汇总 ===")
    if all(results):
        print("✓ 所有测试通过！API 兼容性良好")
        return 0
    else:
        print("✗ 部分测试失败，需要检查")
        return 1

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