import asyncio
import websockets
import logging

# 設定日誌，這樣您就可以看到所有訊息
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

def play_audio(data):
    """ 模擬播放聲音的函數 """
    logging.info(f"準備播放聲音，資料長度: {len(data)} bytes")
    try:
        # --- 在這裡加入您實際的播放聲音邏輯 ---
        # 例如使用 pyaudio, simpleaudio 等函式庫
        # 如果播放失敗，下面的 except 會捕捉到錯誤並印出
        logging.info("聲音播放成功 (模擬)")
        pass
    except Exception as e:
        logging.error(f"播放聲音時發生錯誤: {e}", exc_info=True)

async def client_handler():
    # 請確認您的伺服器位址和埠號是正確的
    uri = "wss://www.winway.tw:8765" 
    
    while True:
        try:
            async with websockets.connect(uri) as websocket:
                logging.info(f"成功連接到伺服器: {uri}")
                while True:
                    message = await websocket.recv()
                    logging.info("從伺服器收到訊息。")
                    play_audio(message)
        except websockets.ConnectionClosed:
            logging.warning("伺服器連線已關閉。")
        except (ConnectionRefusedError, OSError, websockets.exceptions.InvalidURI, websockets.exceptions.WebSocketException) as e:
            logging.error(f"無法連接到伺服器 {uri}: {e}")
        except Exception as e:
            logging.error(f"發生未預期的錯誤: {e}", exc_info=True)
        
        logging.info("5 秒後嘗試重新連線...")
        await asyncio.sleep(5)

if __name__ == "__main__":
    try:
        asyncio.run(client_handler())
    except KeyboardInterrupt:
        print("\n收到使用者中斷指令 (CTRL+C)，程式正在關閉。")