import asyncio
import websockets
import logging

logger = logging.getLogger("cs_agent")

async def connect_flow(client):
    """连接 WebSocket 服务器并自动重连。"""
    while client.running:
        try:
            client.logger.info(f"[{client.get_time()}] 正在连接轻简API {client.uri}...")
            async with websockets.connect(client.uri) as websocket:
                client.websocket = websocket
                client.logger.info(f"[{client.get_time()}] 连接成功!")
                client.logger.info(f"[{client.get_time()}] 等待接收消息...")
                await client.receive_messages()

        except Exception as e:
            # 统一捕获异常，避免因为不同版本的 websockets 导致属性错误
            client.logger.info(f"[{client.get_time()}] 连接或运行错误: {e}")

        if client.running:
            client.logger.info(f"[{client.get_time()}] 5秒后尝试重连...")
            await asyncio.sleep(5)

async def receive_messages_flow(client):
    """持续接收消息。"""
    try:
        async for message in client.websocket:
            await client.handle_message(message)
    except Exception as e:
        client.logger.info(f"[{client.get_time()}] 接收消息中断: {e}")
