#!/usr/bin/env python
"""
@Project ：django_base_ai
@File    ：client.py
@Author  ：congxing.wang
@Date    ：2026/02/25
@Desc    ：消息客户端与通知发送
"""

import json
import logging

import requests

from django_base_ai import dispatch

logger = logging.getLogger(__name__)


class Client:
    def __init__(self):
        self.domain = dispatch.get_system_config_values("message.client_server_url")
        self.agent_id = dispatch.get_system_config_values("message.client_server_appid")
        self.app_secret = dispatch.get_system_config_values("message.client_server_secret")
        logger.debug("消息客户端初始化 domain=%s agent_id=%s", self.domain, self.agent_id)
        self.get_suite_token = f"{self.domain}/base/api/system/apps/get_suite_token/"
        self.open_api_create_message = f"{self.domain}/base/api/system/message_center/open_api_create_message/"
        self.open_api_get_message = f"{self.domain}/base/api/system/message_center/open_api_get_message/?agent_id="
        self.open_api_message_user_list = (
            f"{self.domain}/base/api/system/message_center_target_user/open_api_message_user_list/?nid="
        )
        try:
            r = requests.request(
                "POST", self.get_suite_token, data={"agent_id": self.agent_id, "secret": self.app_secret}
            )
            token = r.json().get("data", None) if r.ok else None
        except Exception as e:
            logger.warning("获取 suite token 失败: %s", e)
            token = None
        self.headers = {
            "Content-Type": "application/json",
            "Authorization": token,
        }
        logger.debug("消息客户端 headers 已设置")

    def read(self):
        response = requests.request("GET", f"{self.open_api_get_message}{self.agent_id}", headers=self.headers)
        logger.debug("消息列表响应 status=%s", response.status_code)
        return response.json()

    def send(self, payload):
        response = requests.request(
            "POST", f"{self.open_api_create_message}", headers=self.headers, data=json.dumps(payload)
        )
        logger.info("发送消息 status=%s", response.status_code)
        return response.json()

    def user_list(self, nid):
        response = requests.request("GET", f"{self.open_api_get_message}{nid}", headers=self.headers)
        logger.debug("消息用户列表 nid=%s status=%s", nid, response.status_code)
        return response.json()


if __name__ == "__main__":
    import os
    import django
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "DjangoBaseAi.settings")
    django.setup()
    # 需在系统配置中设置 message.client_server_url / message.client_server_appid / message.client_server_secret
    client = Client()
    payload = {
        "title": "通知标题",
        "short_content": "示例内容",
        "message_type": 0,
        "thumbnail": "#",
        "content": "内容",
        "url": "#",
        "send_user_info": [],
    }
    print(client.send(payload))
