"""企业工商信息查询模块"""
import requests
import json
from typing import Dict, Any


class BusinessQuery:
    """企业工商信息查询类"""
    
    def __init__(self, api_key: str):
        self.api_key = api_key
        self.base_url = "https://openapi.chinaz.net/v1/1035/business4get"
    
    @staticmethod
    def _safe_serialize(obj: Any) -> Any:
        """
        安全序列化对象，确保可以被 JSON 序列化
        
        Args:
            obj: 需要序列化的对象
            
        Returns:
            可序列化的对象
        """
        try:
            # 尝试序列化，如果失败则转换为字符串
            json.dumps(obj)
            return obj
        except (TypeError, ValueError):
            # 如果是字典，递归处理每个值
            if isinstance(obj, dict):
                return {k: BusinessQuery._safe_serialize(v) for k, v in obj.items()}
            # 如果是列表，递归处理每个元素
            elif isinstance(obj, (list, tuple)):
                return [BusinessQuery._safe_serialize(item) for item in obj]
            # 其他类型转换为字符串
            else:
                return str(obj)
    
    def query_business_info(self, keyword: str) -> Dict[str, Any]:
        """
        查询企业工商信息
        
        Args:
            keyword: 企业名称关键词
            
        Returns:
            包含企业工商信息的字典
        """
        params = {
            "APIKey": self.api_key,
            "ChinazVer": "1.0",
            "keyword": keyword
        }
        
        try:
            response = requests.get(self.base_url, params=params, timeout=60)
            
            # 确保返回的是可序列化的字典
            if response.status_code == 200:
                try:
                    result = response.json()
                    # 安全序列化处理
                    result = self._safe_serialize(result)
                except ValueError:
                    result = {"raw_text": response.text}
            else:
                result = {"error": f"HTTP {response.status_code}", "raw_text": response.text}
            
            return {
                "status_code": response.status_code,
                "success": response.status_code == 200,
                "data": result
            }
        except requests.exceptions.Timeout:
            return {
                "status_code": 0,
                "success": False,
                "error": "请求超时"
            }
        except requests.exceptions.RequestException as e:
            return {
                "status_code": 0,
                "success": False,
                "error": f"请求异常: {str(e)}"
            }
        except Exception as e:
            return {
                "status_code": 0,
                "success": False,
                "error": f"系统异常: {str(e)}"
            }
