"""Data API 便捷函数。

提供简化的函数接口用于快速访问数据 API。
"""

import logging
from pathlib import Path
from typing import Any

from hezor_common.data_model.searching.data.api_models import (
    ExecuteResponse,
)
from hezor_common.transfer.datahub_sdk.base.constants import (
    DEFAULT_DATA_API_BASE_URL,
    DEFAULT_DATA_API_KEY,
    DEFAULT_HEADER_PK_FILEPATH,
    DEFAULT_HEADER_PK_PASSWORD,
)
from hezor_common.transfer.datahub_sdk.base.data_api_client import DataAPIClient
from hezor_common.transfer.datahub_sdk.base.meta_info import MetaInfo

logger = logging.getLogger(__name__)


async def execute_tool(
    tool_name: str,
    args: dict[str, Any],
    base_url: str = DEFAULT_DATA_API_BASE_URL,
    api_key: str | None = DEFAULT_DATA_API_KEY,
    meta_info: MetaInfo | None = None,
    private_key_path: str | Path | None = None,
    password: bytes | None = None,
    meta_info_expires_in: int = 3600,
) -> ExecuteResponse:
    """执行工具的便捷函数。

    Parameters
    ----------
    tool_name : str
        工具名称
    args : dict[str, Any]
        工具参数字典
    base_url : str
        API基础URL
    api_key : str | None
        API密钥，用于Bearer token认证
    meta_info : MetaInfo | None
        元信息对象，用于生成请求头
    private_key_path : str | Path | None
        私钥文件路径，用于JWT签名。默认从环境变量 DATAHUB_HEADER_PK_FILEPATH 读取
    password : bytes | None
        私钥密码。默认从环境变量 DATAHUB_HEADER_PK_PASSWORD 读取
    meta_info_expires_in : int
        MetaInfo JWT token过期时间（秒）

    Returns
    -------
    ExecuteResponse
        执行响应，包含执行结果数据

    Examples
    --------
    >>> response = await execute_tool(
    ...     tool_name="get_weather",
    ...     args={"city": "北京"}
    ... )
    >>> print(response.data)
    """
    # 处理默认值
    if private_key_path is None:
        private_key_path = DEFAULT_HEADER_PK_FILEPATH
    if password is None and DEFAULT_HEADER_PK_PASSWORD:
        password = DEFAULT_HEADER_PK_PASSWORD.encode()

    async with DataAPIClient(
        base_url=base_url,
        api_key=api_key,
        meta_info=meta_info,
        private_key_path=private_key_path,
        password=password,
        meta_info_expires_in=meta_info_expires_in,
    ) as client:
        return await client.execute_tool(tool_name, args)


async def execute_tool_from_json(
    request_json: str,
    base_url: str = DEFAULT_DATA_API_BASE_URL,
    api_key: str | None = DEFAULT_DATA_API_KEY,
    meta_info: MetaInfo | None = None,
    private_key_path: str | Path | None = None,
    password: bytes | None = None,
    meta_info_expires_in: int = 3600,
) -> ExecuteResponse:
    """从JSON字符串执行工具的便捷函数。

    Parameters
    ----------
    request_json : str
        JSON格式的执行请求字符串，格式为: {"tool": "tool_name", "args": {...}}
    base_url : str
        API基础URL
    api_key : str | None
        API密钥，用于Bearer token认证
    meta_info : MetaInfo | None
        元信息对象，用于生成请求头
    private_key_path : str | Path | None
        私钥文件路径，用于JWT签名。默认从环境变量 DATAHUB_HEADER_PK_FILEPATH 读取
    password : bytes | None
        私钥密码。默认从环境变量 DATAHUB_HEADER_PK_PASSWORD 读取
    meta_info_expires_in : int
        MetaInfo JWT token过期时间（秒）

    Returns
    -------
    ExecuteResponse
        执行响应，包含执行结果数据

    Examples
    --------
    >>> json_str = '{"tool": "get_weather", "args": {"city": "北京"}}'
    >>> response = await execute_tool_from_json(json_str)
    >>> print(response.data)
    """
    # 处理默认值
    if private_key_path is None:
        private_key_path = DEFAULT_HEADER_PK_FILEPATH
    if password is None and DEFAULT_HEADER_PK_PASSWORD:
        password = DEFAULT_HEADER_PK_PASSWORD.encode()

    async with DataAPIClient(
        base_url=base_url,
        api_key=api_key,
        meta_info=meta_info,
        private_key_path=private_key_path,
        password=password,
        meta_info_expires_in=meta_info_expires_in,
    ) as client:
        return await client.execute_tool_from_json(request_json)
