"""
AkShare 查询模块
提供函数搜索和格式化功能
"""

from typing import Dict, Any, List, Optional

try:
    from .scanner import scan_akshare_functions, get_function_info
except ImportError:
    from scanner import scan_akshare_functions, get_function_info


def format_function_detail(func_info: Dict[str, Any]) -> Dict[str, Any]:
    """
    格式化函数详情，使参数更规范易读
    
    Args:
        func_info: 原始函数信息
        
    Returns:
        格式化后的函数信息，包含：
        - name: 函数名
        - description: 简短描述（文档第一行）
        - parameters: 规范化的参数列表
        - full_doc: 完整文档
    """
    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(
    keyword: Optional[str] = None,
    limit: int = 10,
    include_detail: bool = False
) -> Dict[str, Any]:
    """
    搜索 AkShare 函数
    
    支持多关键词组合搜索，可选返回详细信息。
    
    Args:
        keyword: 搜索关键词，支持空格分隔多个关键词
                例如："stock zh hist" 会搜索同时包含这三个词的函数
        limit: 返回数量限制
        include_detail: 是否返回详细信息（参数类型、默认值等）
        
    Returns:
        搜索结果字典，包含：
        - success: 是否成功
        - functions: 函数列表
        - count: 结果数量
        - keyword: 搜索关键词
        - include_detail: 是否包含详情
        
    Examples:
        >>> # 简单搜索
        >>> result = search_functions(keyword="stock", limit=5)
        
        >>> # 多关键词搜索并获取详情
        >>> result = search_functions(keyword="stock zh hist", include_detail=True)
    """
    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()
                
                # 检查所有关键词是否都匹配（AND 逻辑）
                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 Exception:
                    # 如果获取详情失败，使用简略信息
                    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
        }
