
import requests
import json
import time

class IFindClient:
    """
    同花顺 iFinD HTTP API 客户端基类，负责鉴权和请求分发。
    """
    def __init__(self, refresh_token: str):
        self.refresh_token = refresh_token
        self.access_token = None
        self.token_expiry = 0
        self.base_url = "https://quantapi.51ifind.com/api/v1"

    def _get_access_token(self):
        """获取或刷新当前的 access_token"""
        if self.access_token and time.time() < self.token_expiry:
            return self.access_token

        url = f"{self.base_url}/get_access_token"
        headers = {
            "Content-Type": "application/json",
            "refresh_token": self.refresh_token
        }
        
        try:
            response = requests.post(url, headers=headers)
            data = response.json()
            if data.get("errorcode") == 0:
                self.access_token = data["data"]["access_token"]
                # 按照手册说明，有效期 7 天，我们设为 6 天以防万一
                self.token_expiry = time.time() + (6 * 24 * 3600)
                return self.access_token
            else:
                error_msg = f"iFinD access token error: {data.get('errmsg')} (Code: {data.get('errorcode')})"
                if data.get("errorcode") == -1301:
                    print(f"\nCRITICAL ERROR: {error_msg}")
                    print("Please check your IFIND_REFRESH_TOKEN in .env file.")
                    import sys
                    sys.exit(1)
                raise Exception(error_msg)
        except Exception as e:
            print(f"Error refreshing iFinD access token: {e}")
            return None

    def post(self, endpoint: str, params: dict):
        """发送 POST 请求到指定的 API 端点"""
        token = self._get_access_token()
        if not token:
            return None
        
        url = f"{self.base_url}/{endpoint}"
        headers = {
            "Content-Type": "application/json",
            "access_token": token
        }
        
        # 记录重试次数或简单报错
        try:
            response = requests.post(url, headers=headers, json=params)
            if response.status_code != 200:
                print(f"iFinD API HTTP Error: {response.status_code} - {response.text}")
                return None
            return response.json()
        except Exception as e:
            print(f"iFinD API Request Error on {endpoint}: {e}")
            return None
