"""
AkShare MCP Server 测试文件 - 重构版
测试两个核心工具：search_functions 和 execute_function
"""

import json
import sys
import os

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from scanner import scan_akshare_functions, get_function_info
from executor import AkShareExecutor


def format_function_detail(func_info):
    """格式化函数详情"""
    formatted = {
        "name": func_info['name'],
        "description": func_info['doc'].split('\n')[0] if func_info['doc'] else "无描述",
        "parameters": [],
        "full_doc": func_info['doc']
    }
    
    for param in func_info.get('params', []):
        param_type = param.get('annotation', 'any')
        if param_type:
            param_type = str(param_type).replace("<class '", "").replace("'>", "").replace("class ", "")
        else:
            param_type = "any"
        
        param_formatted = {
            "name": param['name'],
            "type": param_type,
            "required": param.get('required', False),
            "default": param.get('default') if not param.get('required', False) else None,
            "description": ""
        }
        
        if func_info['doc']:
            param_pattern = f":param {param['name']}:"
            if param_pattern in func_info['doc']:
                lines = func_info['doc'].split('\n')
                for line in lines:
                    if param_pattern in line:
                        desc = line.split(param_pattern)[1].strip()
                        if desc:
                            param_formatted['description'] = desc
                        break
        
        formatted['parameters'].append(param_formatted)
    
    return formatted


def search_functions_impl(keyword=None, limit=10, include_detail=False):
    """实现搜索功能"""
    try:
        functions = scan_akshare_functions()
        
        if keyword:
            keywords = [k.strip().lower() for k in keyword.split() if k.strip()]
            filtered_functions = []
            
            for func in functions:
                func_name_normalized = func['name'].lower().replace('_', ' ')
                func_doc_lower = func['doc'].lower()
                
                match = all(
                    kw in func_name_normalized or kw in func_doc_lower
                    for kw in keywords
                )
                
                if match:
                    filtered_functions.append(func)
            
            functions = filtered_functions
        
        functions = functions[:limit]
        
        if include_detail:
            detailed_functions = []
            for func in functions:
                try:
                    detail = get_function_info(func['name'])
                    formatted_detail = format_function_detail(detail)
                    detailed_functions.append(formatted_detail)
                except:
                    detailed_functions.append(func)
            functions = detailed_functions
        
        return {
            "success": True,
            "functions": functions,
            "count": len(functions),
            "keyword": keyword,
            "include_detail": include_detail
        }
    except Exception as e:
        return {
            "success": False,
            "error": str(e),
            "data": None
        }


def test_search_simple():
    """测试简单搜索"""
    print("🔍 测试 1: 简单搜索 - 查找股票相关函数")
    print("=" * 80)
    
    result = search_functions_impl(keyword="stock zh hist", limit=5, include_detail=False)
    
    if result['success']:
        print(f"   ✅ 找到 {result['count']} 个函数:\n")
        for func in result['functions']:
            print(f"   • {func['name']}")
            print(f"     {func['doc'][:80]}...")
            print()
    else:
        print(f"   ❌ 搜索失败: {result['error']}")


def test_search_with_detail():
    """测试带详情的搜索"""
    print("\n🔍 测试 2: 详细搜索 - 获取完整参数信息")
    print("=" * 80)
    
    result = search_functions_impl(keyword="stock zh a hist", limit=2, include_detail=True)
    
    if result['success']:
        print(f"   ✅ 找到 {result['count']} 个函数:\n")
        for func in result['functions']:
            print(f"   函数: {func['name']}")
            print(f"   描述: {func['description']}")
            print(f"   参数:")
            
            if func['parameters']:
                for param in func['parameters']:
                    required = "✓必需" if param['required'] else "○可选"
                    default = f", 默认: {param['default']}" if param.get('default') else ""
                    desc = f"\n        说明: {param['description']}" if param.get('description') else ""
                    print(f"     [{required}] {param['name']} ({param['type']}){default}{desc}")
            else:
                print("     无参数")
            print()
    else:
        print(f"   ❌ 搜索失败: {result['error']}")


def test_execute():
    """测试执行函数"""
    print("\n🔍 测试 3: 执行函数 - 获取实际数据")
    print("=" * 80)
    
    executor = AkShareExecutor()
    
    # 测试无参数函数 - 改用数据量较小的函数
    print("\n   3.1 执行无参数函数: macro_china_gdp (中国GDP数据)")
    print("   " + "-" * 76)
    
    try:
        result = executor.execute_function("macro_china_gdp", {})
        print(f"   ✅ 成功获取 {len(result)} 条数据")
        if result:
            print(f"   示例数据（前2条）:")
            for i, item in enumerate(result[:2], 1):
                item_str = json.dumps(item, ensure_ascii=False)
                print(f"   {i}. {item_str[:120]}...")
    except Exception as e:
        print(f"   ❌ 执行失败: {e}")
    
    # 测试带参数函数
    print("\n   3.2 执行带参数函数: stock_zh_a_hist (A股历史数据)")
    print("   " + "-" * 76)
    
    try:
        result = executor.execute_function(
            "stock_zh_a_hist",
            {
                "symbol": "000001",
                "period": "daily",
                "start_date": "20240101",
                "end_date": "20240105"
            }
        )
        print(f"   ✅ 成功获取 {len(result)} 条数据")
        if result:
            print(f"   示例数据（前2条）:")
            for i, item in enumerate(result[:2], 1):
                item_str = json.dumps(item, ensure_ascii=False)
                print(f"   {i}. {item_str[:120]}...")
    except Exception as e:
        print(f"   ❌ 执行失败: {e}")


def test_workflow():
    """测试完整工作流程"""
    print("\n🔍 测试 4: 完整工作流程 - 从搜索到执行")
    print("=" * 80)
    
    print("\n   步骤 1: 搜索中国GDP相关函数")
    print("   " + "-" * 76)
    
    search_result = search_functions_impl(keyword="china gdp", limit=3, include_detail=True)
    
    if search_result['success'] and search_result['count'] > 0:
        func = search_result['functions'][0]
        print(f"   ✅ 找到函数: {func['name']}")
        print(f"      描述: {func['description']}")
        print(f"      参数数量: {len(func['parameters'])}")
        
        print("\n   步骤 2: 执行该函数获取数据")
        print("   " + "-" * 76)
        
        executor = AkShareExecutor()
        try:
            result = executor.execute_function(func['name'], {})
            print(f"   ✅ 成功获取 {len(result)} 条数据")
            if result:
                print(f"   示例数据（前2条）:")
                for i, item in enumerate(result[:2], 1):
                    item_str = json.dumps(item, ensure_ascii=False)
                    print(f"   {i}. {item_str[:100]}...")
        except Exception as e:
            print(f"   ❌ 执行失败: {e}")
    else:
        print("   ❌ 未找到相关函数")


def test_multi_keyword():
    """测试多关键词搜索"""
    print("\n🔍 测试 5: 多关键词搜索")
    print("=" * 80)
    
    test_cases = [
        ("stock zh spot", "A股实时行情"),
        ("fund etf", "ETF基金"),
        ("futures main", "期货主力合约"),
        ("macro china", "中国宏观数据"),
    ]
    
    for keyword, desc in test_cases:
        result = search_functions_impl(keyword=keyword, limit=3, include_detail=False)
        if result['success'] and result['count'] > 0:
            print(f"\n   ✅ '{keyword}' ({desc}) - 找到 {result['count']} 个函数:")
            for func in result['functions']:
                print(f"      • {func['name']}")
        else:
            print(f"\n   ❌ '{keyword}' - 未找到函数")


def show_comparison():
    """显示重构对比"""
    print("\n📊 重构对比")
    print("=" * 80)
    
    print("\n   【重构前】3个工具：")
    print("     1. list_functions - 列出函数")
    print("     2. get_function_detail - 获取详情")
    print("     3. execute_function - 执行函数")
    print("\n     问题：需要两步才能获取完整信息")
    
    print("\n   【重构后】2个工具：")
    print("     1. search_functions - 智能搜索（可选详情）")
    print("     2. execute_function - 执行函数")
    
    print("\n   ✨ 改进：")
    print("     • 一步到位：include_detail=True 直接获取完整信息")
    print("     • 多关键词搜索：支持空格分隔的组合搜索")
    print("     • 参数规范化：类型、默认值、描述清晰展示")
    print("     • 下划线处理：'stock hist' 可匹配 'stock_zh_a_hist'")


def main():
    """主测试函数"""
    print("🚀 开始测试重构后的 AkShare MCP Server")
    print("=" * 80)
    print()
    
    test_search_simple()
    test_search_with_detail()
    test_execute()
    test_workflow()
    test_multi_keyword()
    show_comparison()
    
    print("\n" + "=" * 80)
    print("🎉 所有测试完成")


if __name__ == "__main__":
    main()
