# Copyright (c) 2025, JINGROW and contributors
# For license information, please see license.txt

"""
Client 相关白名单函数 - 转发到 SaaS 端
"""

import jingrow
import requests
import logging
from jingrow.config import Config
from jingrow.utils.auth import get_request_session_cookie

logger = logging.getLogger(__name__)


@jingrow.whitelist()
def get_list(**kwargs):
    """获取列表 - 转发到 SaaS 端"""
    url = f"{Config.jingrow_server_url}/api/action/jingrow.client.get_list"
    headers = {"Accept": "application/json", "Content-Type": "application/json"}
    
    session_cookie = get_request_session_cookie()
    if session_cookie:
        headers["Cookie"] = f"sid={session_cookie}"
    
    resp = requests.post(url, headers=headers, json=kwargs, timeout=30)
    if resp.status_code == 200:
        return resp.json().get("message", [])
    logger.error(f"[get_list] SaaS error: {resp.status_code} - {resp.text[:200]}")
    return []


@jingrow.whitelist()
def get_value(**kwargs):
    """获取值 - 转发到 SaaS 端"""
    url = f"{Config.jingrow_server_url}/api/action/jingrow.client.get_value"
    headers = {"Accept": "application/json", "Content-Type": "application/json"}
    
    session_cookie = get_request_session_cookie()
    if session_cookie:
        headers["Cookie"] = f"sid={session_cookie}"
    
    resp = requests.post(url, headers=headers, json=kwargs, timeout=30)
    if resp.status_code == 200:
        return resp.json().get("message")
    logger.error(f"[get_value] SaaS error: {resp.status_code} - {resp.text[:200]}")
    return None


@jingrow.whitelist()
def get_count(**kwargs):
    """获取计数 - 转发到 SaaS 端"""
    url = f"{Config.jingrow_server_url}/api/action/jingrow.client.get_count"
    headers = {"Accept": "application/json", "Content-Type": "application/json"}
    
    session_cookie = get_request_session_cookie()
    if session_cookie:
        headers["Cookie"] = f"sid={session_cookie}"
    
    resp = requests.get(url, headers=headers, params=kwargs, timeout=30)
    if resp.status_code == 200:
        return resp.json().get("message", 0)
    logger.error(f"[get_count] SaaS error: {resp.status_code} - {resp.text[:200]}")
    return 0
