import os
import unittest

from websockets.protocol import State

from core.websocket_client import QingjianAPIClient


class _DummyWS:
    def __init__(self):
        self.state = State.OPEN
        self.sent = []

    async def send(self, msg_json: str):
        self.sent.append(msg_json)


class OutboundCooldownTest(unittest.IsolatedAsyncioTestCase):
    def setUp(self):
        os.environ["OUTBOUND_PER_CUSTOMER_COOLDOWN_SECONDS"] = "5"

    async def test_skip_second_reply_within_cooldown(self):
        c = QingjianAPIClient(enable_agent=False)
        c.websocket = _DummyWS()
        msg = {
            "acc_id": "shop_a",
            "from_id": "u001",
            "from_name": "u001",
            "acc_type": "AliWorkbench",
        }
        await c.send_reply(msg, "第一条")
        await c.send_reply(msg, "第二条")
        self.assertEqual(len(c.websocket.sent), 1)

    def tearDown(self):
        os.environ.pop("OUTBOUND_PER_CUSTOMER_COOLDOWN_SECONDS", None)


if __name__ == "__main__":
    unittest.main(verbosity=2)
