"""Knowledge Graph SDK - 统一的 SDK 接口。

提供便捷的上下文管理器接口，集成所有 Knowledge Graph API 功能。
"""

import logging
from pathlib import Path

import httpx

from hezor_common.data_model.searching import (
    VectorSearchResponse,
)
from hezor_common.transfer.base_sdk import MetaInfo
from hezor_common.transfer.knowledge_graph_sdk.base.constants import (
    DEFAULT_API_BASE_URL,
    DEFAULT_API_KEY,
)
from hezor_common.transfer.knowledge_graph_sdk.base.knowledge_graph_api_client import (
    KnowledgeGraphAPIClient,
)
from hezor_common.transfer.knowledge_graph_sdk.vector_search import (
    vector_search as _vector_search,
)

logger = logging.getLogger(__name__)


class KnowledgeGraphSDK:
    """Knowledge Graph SDK 统一接口。

    提供便捷的上下文管理器接口，集成向量搜索等功能。

    Parameters
    ----------
    base_url : str
        API 基础 URL，默认使用 DEFAULT_API_BASE_URL
    timeout : float
        请求超时时间（秒）
    api_key : str | None
        API 密钥，用于认证
    meta_info : MetaInfo | None
        元信息对象，用于签名认证
    private_key_path : str | Path | None
        私钥文件路径，用于签名认证（与 meta_info 配合使用）
    password : bytes | None
        私钥密码
    meta_info_expires_in : int
        MetaInfo JWT token 过期时间（秒）

    Examples
    --------
    >>> # 基本使用
    >>> async with KnowledgeGraphSDK() as sdk:
    ...     result = await sdk.vector_search(
    ...         question="菜品有哪些",
    ...         limit=10
    ...     )

    >>> # 使用认证
    >>> async with KnowledgeGraphSDK(api_key="your-key") as sdk:
    ...     result = await sdk.vector_search(question="...")
    """

    def __init__(
        self,
        base_url: str = DEFAULT_API_BASE_URL,
        timeout: float = 120.0,
        api_key: str | None = DEFAULT_API_KEY,
        meta_info: MetaInfo | None = None,
        private_key_path: str | Path | None = None,
        password: bytes | None = None,
        meta_info_expires_in: int = 3600,
    ):
        """初始化 Knowledge Graph SDK。

        Parameters
        ----------
        base_url : str
            API 基础 URL
        timeout : float
            请求超时时间（秒）
        api_key : str | None
            API 密钥
        meta_info : MetaInfo | None
            元信息对象
        private_key_path : str | Path | None
            私钥文件路径
        password : bytes | None
            私钥密码
        meta_info_expires_in : int
            MetaInfo JWT token 过期时间（秒）
        """
        self._client = KnowledgeGraphAPIClient(
            base_url=base_url,
            timeout=timeout,
            api_key=api_key,
            meta_info=meta_info,
            private_key_path=private_key_path,
            password=password,
            meta_info_expires_in=meta_info_expires_in,
        )

    async def __aenter__(self) -> "KnowledgeGraphSDK":
        """进入异步上下文管理器。

        Returns
        -------
        KnowledgeGraphSDK
            SDK 实例
        """
        await self._client.__aenter__()
        logger.debug("KnowledgeGraphSDK context manager entered")
        return self

    async def __aexit__(self, exc_type, exc_val, exc_tb) -> None:
        """退出异步上下文管理器。

        Parameters
        ----------
        exc_type : type | None
            异常类型
        exc_val : Exception | None
            异常值
        exc_tb : TracebackType | None
            异常 traceback
        """
        await self._client.__aexit__(exc_type, exc_val, exc_tb)
        logger.debug("KnowledgeGraphSDK context manager exited")

    async def vector_search(
        self,
        question: str,
        limit: int = 10,
        score_threshold: float = 0.5,
        offset: int = 0,
        enable_entity_extraction: bool = True,
    ) -> VectorSearchResponse:
        """执行向量搜索。

        Parameters
        ----------
        question : str
            搜索问题
        limit : int
            返回结果数量限制，范围 1-50，默认 10
        score_threshold : float
            相似度阈值，范围 0.0-1.0，默认 0.5
        offset : int
            结果偏移量，用于分页，默认 0
        enable_entity_extraction : bool
            是否启用实体抽取，默认 true

        Returns
        -------
        VectorSearchResponse
            搜索响应结果

        Raises
        ------
        httpx.HTTPError
            如果 HTTP 请求失败

        Examples
        --------
        >>> async with KnowledgeGraphSDK() as sdk:
        ...     result = await sdk.vector_search(question="菜品有哪些")
        ...     print(f"Found {len(result.search_results.entities)} entities")
        """
        return await _vector_search(
            question=question,
            limit=limit,
            score_threshold=score_threshold,
            offset=offset,
            enable_entity_extraction=enable_entity_extraction,
            base_url=self._client.base_url,
            api_key=self._client.api_key,
            meta_info=self._client.meta_info,
            private_key_path=self._client.private_key_path,
            password=self._client.password,
            timeout=self._client.timeout,
        )

    async def health_check(self) -> tuple[bool, dict]:
        """执行健康检查。

        调用 GET /health 端点检查 Knowledge Graph 服务状态。

        Returns
        -------
        tuple[bool, dict]
            - bool: 健康检查是否通过（基于 response.status == "healthy"）
            - dict: 原始健康检查响应数据

        Raises
        ------
        httpx.HTTPError
            如果 HTTP 请求失败

        Examples
        --------
        >>> async with KnowledgeGraphSDK() as sdk:
        ...     is_healthy, health_data = await sdk.health_check()
        ...     if is_healthy:
        ...         print("Service is healthy")
        ...     print(f"Details: {health_data}")
        """
        try:
            return await self._client.health_check()
        except httpx.HTTPError:
            # HTTP 请求失败，服务不健康
            return False, {"error": "HTTP request failed"}


__all__ = ["KnowledgeGraphSDK"]
