"""
AkShare 函数执行器
"""

from __future__ import annotations

import pandas as pd
from datetime import date, datetime
from typing import Dict, Any, List


class AkShareExecutor:
    """AkShare 函数执行器"""
    
    def _convert_to_json_serializable(self, obj: Any) -> Any:
        """
        将对象转换为 JSON 可序列化的格式
        
        Args:
            obj: 需要转换的对象
            
        Returns:
            JSON 可序列化的对象
        """
        if isinstance(obj, (date, datetime)):
            return obj.isoformat()
        elif isinstance(obj, pd.Timestamp):
            return obj.isoformat()
        elif pd.isna(obj):
            return None
        else:
            return obj
    
    def execute_function(
        self,
        function_name: str,
        params: Dict[str, Any] = None
    ) -> List[Dict[str, Any]]:
        """
        执行 AkShare 函数
        
        Args:
            function_name: 函数名
            params: 函数参数字典
            
        Returns:
            执行结果（JSON 可序列化）
        """
        try:
            import akshare as ak
        except ImportError:
            raise ImportError("请先安装 akshare: pip install akshare")
        
        # 检查函数是否存在
        if not hasattr(ak, function_name):
            raise ValueError(f"函数不存在: {function_name}")
        
        func = getattr(ak, function_name)
        
        if not callable(func):
            raise ValueError(f"{function_name} 不是可调用函数")
        
        try:
            # 执行函数
            call_params = params or {}
            result = func(**call_params)
            
            # 转换结果为字典列表
            if hasattr(result, 'to_dict'):
                # pandas DataFrame - 转换为 records 格式
                data = result.to_dict('records')
                
                # 处理日期和特殊类型
                for record in data:
                    for key, value in record.items():
                        record[key] = self._convert_to_json_serializable(value)
                
            elif isinstance(result, (dict, list)):
                data = result if isinstance(result, list) else [result]
            else:
                # 其他类型转换为字符串
                data = [{"value": str(result)}]
            
            return data
            
        except Exception as e:
            raise Exception(f"执行函数失败: {str(e)}")
