import datetime
import json
import logging
from typing import Literal

import requests
from cachetools import TTLCache

from capinvest_capdata.utils.data_path import auth_url

CAPDATA_INTERVALS = ["1m", "15m", "30m", "1h", "d", "w"]
CapdataIntervals = Literal["1m", "15m", "30m", "1h", "d", "w"]
logger = logging.getLogger("uvicorn.info")
capdata_user_api_key_cache = TTLCache(maxsize=1000, ttl=60 * 3)


def post_by_token(url, params, credentials: dict):
    token = get_capdata_token(credentials)
    logger.info(f"{datetime.datetime.now()} capdata url: {url}")
    headers = {'Accept': 'application/json', 'content-type': 'application/json', 'Accept-Encoding': 'gzip',
               'x-access-token': token}
    response = requests.post(url, json=params, headers=headers).text
    res = json.loads(response)
    if 'respCode' not in res.keys():
        raise Exception(res["error"])
    code = res["respCode"]
    if str(code) == 'SUCCEED':
        if 'data' in res:
            return res["data"]
        else:
            return None
    else:
        raise Exception(res["message"])


def get_capdata_token(credentials: dict):
    """Get CapData token using API key or username/password.
    
    Supports two authentication methods:
    1. Using capdata_api_key directly
    """
    # Check if api_key is provided and not empty
    api_key = credentials.get("capdata_api_key") if credentials else None
    if api_key and api_key.strip():
        if "@_@" not in api_key:
            return api_key
        else:
            if api_key in capdata_user_api_key_cache:
                return capdata_user_api_key_cache.get(api_key)
            api_keys = api_key.split("@_@")
            capdata_user_name = api_keys[0]
            capdata_user_pwd = api_keys[1]
            header = {'Accept': 'application/json', 'content-type': 'application/json', 'Accept-Encoding': 'gzip'}
            response = requests.post(auth_url,
                                     json={"account": capdata_user_name,
                                           "pwd": capdata_user_pwd},
                                     headers=header).text
            res = json.loads(response)
            if 'respCode' not in res.keys():
                raise Exception(res["error"])
            code = res["respCode"]
            if str(code) == 'SUCCEED':
                token = res["data"]
                capdata_user_api_key_cache[api_key] = token
                return token
            else:
                raise Exception(res["message"])
    raise PermissionError(
        "Capdata authentication failed: Please provide either capdata_api_key(如果是账号密码格式为:capdata_user_name@_@capdata_user_pwd)")
