"""Hezor2 API 客户端。

用于与 Hezor2 API 进行交互。
"""

import logging
from pathlib import Path

import httpx

from hezor_common.data_model.creations.core.creation_generate_result import (
    CreationGenerateResult,
)
from hezor_common.data_model.creations.execution.webhook import (
    CreationWebhookRequest,
    CreationWebhookResponse,
)
from hezor_common.transfer.base_sdk import BaseAPIClient, MetaInfo
from hezor_common.transfer.hezor2_sdk.base.constants import (
    DEFAULT_API_BASE_URL,
    DEFAULT_API_KEY,
)

logger = logging.getLogger(__name__)


class Hezor2APIClient(BaseAPIClient):
    """Hezor2 API 客户端。

    用于与 Hezor2 API 进行交互。
    继承自 BaseAPIClient，提供通用的认证和请求头管理功能。

    Examples
    --------
    >>> async with Hezor2APIClient() as client:
    ...     response = await client.get("/api/endpoint")
    ...     data = response.json()
    """

    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,
    ):
        """初始化客户端。

        Parameters
        ----------
        base_url : str
            API 基础 URL
        timeout : float
            请求超时时间（秒）
        api_key : str | None
            API 密钥，用于 Bearer token 认证。如果为 None，则不添加 Authorization 头
        meta_info : MetaInfo | None
            元信息对象，用于生成请求头。如果为 None，则不添加元信息头
        private_key_path : str | Path | None
            私钥文件路径，用于 JWT 签名。如果为 None 且提供了 meta_info，将使用匿名密钥
        password : bytes | None
            私钥密码，如果私钥加密则需要提供
        meta_info_expires_in : int
            MetaInfo JWT token 过期时间（秒），默认 3600 秒
        """
        super().__init__(
            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 publish_creation_report(
        self,
        payload: CreationGenerateResult,
        task_id: str,
        execution_id: str,
    ) -> CreationWebhookResponse:
        """发布创作报告到 Webhook。

        将生成的创作报告发送到 Hezor2 API 的 webhook 接口进行处理。

        Parameters
        ----------
        payload : CreationGenerateResult
            生成的创作结果数据
        task_id : str
            任务 ID（如 "monthly_report"），定义执行什么任务，可以重复表明同一任务
        execution_id : str
            执行 ID（如 "exec_2026_01_21_xxx"），表示一次具体的执行实例，唯一

        Returns
        -------
        CreationWebhookResponse
            Webhook 响应，包含处理状态和相关 ID

        Raises
        ------
        httpx.HTTPError
            HTTP 请求失败时抛出
        ValueError
            响应数据格式错误时抛出

        Examples
        --------
        >>> from hezor_common.data_model.creations.core import CreationGenerateResult
        >>> async with Hezor2APIClient() as client:
        ...     result = CreationGenerateResult(...)
        ...     response = await client.publish_creation_report(
        ...         payload=result,
        ...         task_id="monthly_report",
        ...         execution_id="exec_2026_01_27_001"
        ...     )
        ...     print(f"Status: {response.status}")
        ...     print(f"Report ID: {response.report_id}")
        """
        path = "/creations/webhook"

        # 构造请求
        request = CreationWebhookRequest(
            action="publish_creation_report",
            payload=payload,
            task_id=task_id,
            execution_id=execution_id,
        )

        logger.info(f"Publishing creation report: task_id={task_id}, execution_id={execution_id}")

        try:
            response = await self.post(
                path,
                json=request.model_dump(),
            )
            response.raise_for_status()

            data = response.json()
            webhook_response = CreationWebhookResponse.model_validate(data)

            logger.info(
                f"Creation report published successfully: report_id={webhook_response.report_id}"
            )
            return webhook_response

        except httpx.HTTPError as e:
            logger.error(f"HTTP error during creation report publishing: {e}")
            raise
        except Exception as e:
            logger.error(f"Error parsing webhook response: {e}")
            raise ValueError(f"Invalid webhook response format: {e}") from e

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

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

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

        Raises
        ------
        httpx.HTTPError
            HTTP 请求失败时抛出

        Examples
        --------
        >>> async with Hezor2APIClient() as client:
        ...     is_healthy, health = await client.health_check()
        ...     if is_healthy:
        ...         print(f"Status: {health.get('status')}")
        """
        path = "/health"

        logger.info("Executing health check")

        try:
            response = await self.get(path)
            response.raise_for_status()

            data = response.json()
            is_healthy = data.get("status") == "healthy"
            logger.info(f"Health check completed: {data}, is_healthy={is_healthy}")
            return is_healthy, data

        except httpx.HTTPError as e:
            logger.error(f"HTTP error during health check: {e}")
            raise


__all__ = ["Hezor2APIClient"]
