import threading
import sys
import os

# 导入配置
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))))
from jingrow.config import Config

_thread_local = threading.local()

def set_context(context):
    """设置当前线程的context"""
    _thread_local.context = context

def get_jingrow_api_headers():
    """获取 Jingrow API 认证头部，用于系统级调用"""
    api_key = Config.jingrow_api_key
    api_secret = Config.jingrow_api_secret
    
    if not api_key or not api_secret:
        return None
        
    return {
        "Authorization": f"token {api_key}:{api_secret}",
        "Content-Type": "application/json"
    }

def get_session_api_headers():
    """获取session认证的API头部，类似jingrow系统中的get_jingrow_api_headers()"""
    headers = {
        "Content-Type": "application/json",
        "Accept": "application/json"
    }
    
    # 从线程本地存储获取context
    context = getattr(_thread_local, 'context', None)
    if context:
        session_cookie = context.get('session_cookie')
        if session_cookie:
            headers["Cookie"] = f"sid={session_cookie}"
    
    return headers

def get_jingrow_cloud_api_url():
    """获取jingrow cloud API URL"""
    return Config.jingrow_cloud_api_url

def get_jingrow_cloud_url():
    """获取jingrow cloud API URL"""
    return Config.jingrow_cloud_url

def get_jingrow_cloud_api_headers():
    headers = {
        "Content-Type": "application/json",
        "Accept": "application/json"
    }
    
    api_key = Config.jingrow_cloud_api_key
    api_secret = Config.jingrow_cloud_api_secret
    
    if api_key and api_secret:
        headers["Authorization"] = f"token {api_key}:{api_secret}"
    
    return headers
