"""Tradepose API 客戶端"""

import os
import redis
from typing import Optional

from .api.strategy import StrategyAPI
from .api.export import ExportAPI
from .api.engine import EngineAPI
from .api.health import HealthAPI


class TradeposeClient(StrategyAPI, ExportAPI, EngineAPI, HealthAPI):
    """Tradepose API 客戶端

    整合所有 API 功能的主客戶端類
    """

    def __init__(
        self,
        api_url: str = "http://localhost:8080",
        redis_url: str = "redis://:tradepose_password@localhost:6379",
        api_token: Optional[str] = None,
    ):
        """初始化客戶端

        Args:
            api_url: Tradepose API 基礎 URL
            redis_url: Redis 連接 URL
            api_token: JWT Bearer Token (如果為 None，從 TRADEPOSE_API_TOKEN 環境變數讀取)
        """
        self.api_url = api_url.rstrip("/")
        self.redis_url = redis_url
        self.api_token = api_token or os.getenv("TRADEPOSE_API_TOKEN")
        self._redis_client = None

    @property
    def redis(self):
        """懶加載 Redis 客戶端"""
        if self._redis_client is None:
            self._redis_client = redis.from_url(self.redis_url, decode_responses=True)
        return self._redis_client

    def _get_headers(self, additional_headers: Optional[dict] = None) -> dict:
        """獲取包含認證信息的請求 headers

        Args:
            additional_headers: 額外的 headers (可選)

        Returns:
            dict: 包含 Content-Type 和 Authorization 的 headers
        """
        headers = {"Content-Type": "application/json"}
        if self.api_token:
            headers["Authorization"] = f"Bearer {self.api_token}"
        if additional_headers:
            headers.update(additional_headers)
        return headers
