import asyncio
import logging

import requests
import json
from grpc_client import GrpcClient
from grpc_listener import GrpcListener
from result import ResultModel

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

# 定义消息处理函数
async def handle_message(request_path: str, request_data: str) -> ResultModel:
    print(f"Received request on path: {request_path}, data: {request_data}")
    return ResultModel(code=200, data={"message": "Request processed successfully"})

async def send_ping(listener: GrpcListener):
    """定时发送 ping 消息"""
    while True:
        try:
            await listener.send_to_all_stream("ping", "#ping", type=-1, retry_count=3)
        except Exception as e:
            logging.error(f"send ping error: {e}")
        await asyncio.sleep(5)  # 每 5 秒发送一次 ping

async def main():
    headers = {
        "Content-Type" : "application/x-www-form-urlencoded",
        "Sm4-Key" : "dUVNkTJLlzMHPqBTZh085jT0N6S7930l6sgddJsYSC8=",
        "Cookie" : "ENCRYPT_KEY=f48bf3-05fe-4978"
    }
    params = {"username":"api_tester",
              "password":"$SM4$Nd/e40vIS6UD9VMaSOmYGlrBORfo7r5/1z9D5d4E4es=$4MS$",
              "tenantCode":"API_test",
              "scope":"all",
              "client_id":"a68ad587830d41aebf418a919006353e",
              "client_secret":"Ninetech@123",
              "grant_type":"password"
    }
    res = requests.post(url="http://accounts-4j.sit.ninetechone.com/oauth/token",headers=headers,params=params)
    res1 = requests.get("http://bitagent.sit.ninetechone.com/api/system/config/client")
    grpc = json.loads(res1.json()["data"])
    # gRPC 配置
    config = {
        "token": "Bearer " + res.json()["access_token"],
        "client_id": "a68ad587830d41aebf418a919006353e",
        "host": grpc["grpc_host"],
        "is_ssl": grpc["grpc_use_ssl"]
    }
    print(config)

    # 创建 GrpcClient 实例
    client = GrpcClient()
    # 设置头部信息
    client.set_header(config["token"], config["client_id"])

    # 连接到 gRPC 服务器
    connected = await client.connect(config["host"], config["is_ssl"])
    if not connected:
        logging.error("Failed to connect to the gRPC server.")
        return

    # 创建 GrpcListener 实例
    listener = GrpcListener(client)
    # 设置消息处理函数
    listener.message_received = handle_message
    # 启动监听
    listener.start()

    # 启动发送 ping 任务
    ping_task = asyncio.create_task(send_ping(listener))

    try:
        # 保持程序运行
        while True:
            await asyncio.sleep(1)
    except KeyboardInterrupt:
        logging.info("Shutting down...")
        # 停止监听
        await listener.stop()
        # 断开连接
        await client.disconnect()
        # 取消 ping 任务
        ping_task.cancel()


if __name__ == "__main__":
    asyncio.run(main())