#!/usr/bin/env python3
"""
表格识别路由逻辑测试脚本

验证：
1. process_table_element_wired 和 process_table_element_vlm 方法是否可调用
2. 路由选择逻辑是否正确（基于配置）
3. Fallback 机制是否工作
"""
import sys
from pathlib import Path

# 添加路径
project_root = Path(__file__).parents[2]
sys.path.insert(0, str(project_root))

from core.element_processors import ElementProcessors


def test_method_existence():
    """测试新方法是否存在"""
    print("🧪 Testing method existence...")
    
    # 检查 ElementProcessors 类是否有新的方法
    required_methods = [
        'process_table_element_wired',
        'process_table_element_vlm',
        '_prepare_table_ocr',
        '_create_empty_table_result',
    ]
    
    for method_name in required_methods:
        if hasattr(ElementProcessors, method_name):
            print(f"  ✅ {method_name} exists")
        else:
            print(f"  ❌ {method_name} NOT found")
            return False
    
    # 检查旧方法是否已删除
    if hasattr(ElementProcessors, 'process_table_element'):
        print(f"  ❌ Old process_table_element still exists (should be removed)")
        return False
    else:
        print(f"  ✅ Old process_table_element removed")
    
    return True


def test_method_signatures():
    """测试方法签名"""
    print("\n🧪 Testing method signatures...")
    import inspect
    
    # 检查 wired 方法签名
    wired_sig = inspect.signature(ElementProcessors.process_table_element_wired)
    expected_params = {'self', 'image', 'layout_item', 'scale', 'pre_matched_spans'}
    actual_params = set(wired_sig.parameters.keys())
    
    if actual_params == expected_params:
        print(f"  ✅ process_table_element_wired signature correct")
    else:
        print(f"  ❌ process_table_element_wired signature mismatch")
        print(f"    Expected: {expected_params}")
        print(f"    Actual: {actual_params}")
        return False
    
    # 检查 vlm 方法签名
    vlm_sig = inspect.signature(ElementProcessors.process_table_element_vlm)
    if actual_params == expected_params:
        print(f"  ✅ process_table_element_vlm signature correct")
    else:
        print(f"  ❌ process_table_element_vlm signature mismatch")
        return False
    
    return True


def test_config_removal():
    """测试配置参数是否从 __init__ 中移除"""
    print("\n🧪 Testing __init__ parameters...")
    import inspect
    
    init_sig = inspect.signature(ElementProcessors.__init__)
    params = list(init_sig.parameters.keys())
    
    # table_config 不应该在参数中
    if 'table_config' in params:
        print(f"  ❌ table_config still in __init__ parameters (should be removed)")
        return False
    else:
        print(f"  ✅ table_config removed from __init__ parameters")
    
    # wired_table_recognizer 应该在参数中
    if 'wired_table_recognizer' in params:
        print(f"  ✅ wired_table_recognizer in __init__ parameters")
    else:
        print(f"  ❌ wired_table_recognizer NOT in __init__ parameters")
        return False
    
    return True


def test_routing_logic_structure():
    """测试路由逻辑结构（在 pipeline_manager_v2.py 中）"""
    print("\n🧪 Testing routing logic in pipeline_manager_v2...")
    
    # 读取 pipeline_manager_v2.py 并检查路由逻辑
    pipeline_file = Path(__file__).parent / 'core' / 'pipeline_manager_v2.py'
    
    with open(pipeline_file, 'r') as f:
        content = f.read()
    
    # 检查是否包含新的路由逻辑
    required_patterns = [
        'use_wired_unet = self.table_config.get',
        'process_table_element_wired',
        'process_table_element_vlm',
        'falling back to VLM',
    ]
    
    for pattern in required_patterns:
        if pattern in content:
            print(f"  ✅ Found: '{pattern[:50]}...'")
        else:
            print(f"  ❌ Missing: '{pattern}'")
            return False
    
    # 检查旧的 process_table_element 调用是否已移除
    if 'process_table_element(' in content and 'process_table_element_' not in content.split('process_table_element(')[1][:100]:
        print(f"  ❌ Old process_table_element call still exists")
        return False
    else:
        print(f"  ✅ Old process_table_element call removed")
    
    return True


def main():
    """主测试函数"""
    print("=" * 70)
    print("表格识别路由逻辑验证测试")
    print("=" * 70)
    
    tests = [
        ("方法存在性", test_method_existence),
        ("方法签名", test_method_signatures),
        ("配置参数移除", test_config_removal),
        ("路由逻辑结构", test_routing_logic_structure),
    ]
    
    results = []
    for test_name, test_func in tests:
        try:
            result = test_func()
            results.append((test_name, result))
        except Exception as e:
            print(f"\n❌ Test '{test_name}' failed with exception:")
            print(f"   {type(e).__name__}: {e}")
            results.append((test_name, False))
    
    # 汇总结果
    print("\n" + "=" * 70)
    print("测试汇总")
    print("=" * 70)
    
    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"{status}: {test_name}")
    
    print(f"\n总计: {passed}/{total} 测试通过")
    
    if passed == total:
        print("\n🎉 所有测试通过！架构重构成功")
        return 0
    else:
        print(f"\n⚠️  {total - passed} 个测试失败")
        return 1


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