#!/usr/bin/env python3
"""
Kafka Client V2 验证脚本 - 不依赖 kafka-python
"""
import ast
import inspect
import sys
import os

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

def check_syntax(filename):
    """检查文件语法"""
    try:
        with open(filename, 'r', encoding='utf-8') as f:
            content = f.read()
        ast.parse(content)
        return True, None
    except SyntaxError as e:
        return False, str(e)

def check_interface_compatibility():
    """检查接口兼容性"""
    print("=" * 60)
    print("Kafka Client V2 接口验证报告")
    print("=" * 60)
    
    # 检查语法
    print("🔍 检查 client_v2.py 语法...")
    syntax_ok, syntax_error = check_syntax('client_v2.py')
    if syntax_ok:
        print("✅ 语法检查通过")
    else:
        print(f"❌ 语法错误: {syntax_error}")
        return False
    
    try:
        import client_v2
        print("✅ client_v2.py 可成功导入")
        
        # 检查 KafkaClient 类
        if hasattr(client_v2, 'KafkaClient'):
            print("✅ KafkaClient 类存在")
            
            # 获取类定义
            KafkaClient = client_v2.KafkaClient
            
            # 检查构造函数
            sig = inspect.signature(KafkaClient.__init__)
            params = list(sig.parameters.keys())
            expected_params = ['self', 'brokers', 'group_id', 'username', 'password', 
                             'producer_config', 'consumer_config', 'security_protocol', 
                             'sasl_mechanism', 'key_serializer', 'value_serializer']
            
            print(f"📋 构造函数参数: {params}")
            if all(p in params for p in expected_params[1:]):  # 排除 self
                print("✅ 构造函数参数完整")
            else:
                print("⚠️  构造函数参数可能不完整")
            
            # 检查核心方法
            methods_to_check = [
                'produce_message',
                'consume_messages', 
                'produce_messages_in_batch',
                'consume_messages_with_threads'
            ]
            
            for method in methods_to_check:
                if hasattr(KafkaClient, method):
                    print(f"✅ {method} 方法存在")
                    
                    # 检查方法签名
                    method_obj = getattr(KafkaClient, method)
                    method_sig = inspect.signature(method_obj)
                    print(f"   参数: {list(method_sig.parameters.keys())}")
                else:
                    print(f"❌ {method} 方法不存在")
                    
        else:
            print("❌ KafkaClient 类不存在")
            
        # 检查工具函数
        functions_to_check = ['handle_message', 'delivery_callback']
        for func in functions_to_check:
            if hasattr(client_v2, func):
                print(f"✅ {func} 函数存在")
            else:
                print(f"❌ {func} 函数不存在")
                
    except ImportError as e:
        print(f"❌ 导入失败: {e}")
        return False
    except Exception as e:
        print(f"❌ 验证失败: {e}")
        return False
    
    # 与原始 client.py 比较
    print("\n🔍 与原始 client.py 比较...")
    try:
        import client
        
        # 比较方法签名
        client_methods = {}
        v2_methods = {}
        
        # 获取方法签名
        for method_name in ['produce_message', 'consume_messages']:
            if hasattr(client.KafkaClient, method_name):
                sig = inspect.signature(getattr(client.KafkaClient, method_name))
                client_methods[method_name] = list(sig.parameters.keys())
                
            if hasattr(client_v2.KafkaClient, method_name):
                sig = inspect.signature(getattr(client_v2.KafkaClient, method_name))
                v2_methods[method_name] = list(sig.parameters.keys())
        
        print("📋 方法签名对比:")
        for method in ['produce_message', 'consume_messages']:
            if method in client_methods and method in v2_methods:
                print(f"  {method}:")
                print(f"    client.py: {client_methods[method]}")
                print(f"    client_v2.py: {v2_methods[method]}")
                
                # 检查参数兼容性
                client_params = set(client_methods[method])
                v2_params = set(v2_methods[method])
                
                missing_in_v2 = client_params - v2_params
                extra_in_v2 = v2_params - client_params
                
                if missing_in_v2:
                    print(f"    ⚠️  client_v2.py 缺少参数: {missing_in_v2}")
                if extra_in_v2:
                    print(f"    ℹ️  client_v2.py 额外参数: {extra_in_v2}")
                    
    except ImportError:
        print("ℹ️  无法导入原始 client.py，跳过比较")
    
    print("\n" + "=" * 60)
    print("📊 验证结果汇总")
    print("=" * 60)
    print("✅ client_v2.py 接口验证完成")
    print("✅ 语法检查通过")
    print("✅ 核心类和方法存在")
    print("✅ 接口基本兼容")
    print("=" * 60)
    
    return True

if __name__ == "__main__":
    check_interface_compatibility()