import json
from unittest.mock import AsyncMock
import pytest

from konabot.common.apis.wolfx import CencEewReport, WolfxAPIService, WolfxWebSocket


obj_example = {
    "ID": "bacby4yab1oyb",
    "EventID": "202603100805.0001",
    "ReportTime": "2026-03-10 08:05:29",
    "ReportNum": 1,
    "OriginTime": "2026-03-10 08:05:29",
    "HypoCenter": "新疆昌吉州呼图壁县",
    "Latitude": 43.687,
    "Longitude": 86.427,
    "Magnitude": 4.0,
    "Depth": 14,
    "MaxIntensity": 5,
}


@pytest.mark.asyncio
async def test_wolfx_websocket_handle():
    ws = WolfxWebSocket("")

    mock_callback = AsyncMock()
    ws.signal.append(mock_callback)
    ws.signal.freeze()

    obj1 = {
        "type": "heartbeat",
        "ver": 18,
        "id": "a69edf6436c5b605",
        "timestamp": 1773111106701,
    }
    data1 = json.dumps(obj1).encode()
    await ws.handle(data1)
    mock_callback.assert_not_called()
    mock_callback.reset_mock()

    obj2 = obj_example
    data2 = json.dumps(obj2).encode()
    await ws.handle(data2)
    mock_callback.assert_called_once_with(data2)
    mock_callback.reset_mock()

    data3 = b"what the f"
    await ws.handle(data3)
    mock_callback.assert_not_called()


@pytest.mark.asyncio
async def test_wolfx_bind_pydantic():
    sv = WolfxAPIService()
    called: list[CencEewReport] = []

    @sv.cenc_eew.append
    async def _(data: CencEewReport):
        called.append(data)

    sv._cenc_eew_ws.signal.freeze()
    sv.cenc_eew.freeze()

    data = json.dumps(obj_example).encode()
    await sv._cenc_eew_ws.signal.send(data)

    assert len(called) == 1
    data = called[0]

    assert data.HypoCenter == obj_example["HypoCenter"]
    assert data.EventID == obj_example["EventID"]

    # Don't panic when the object is invalid
    data = json.dumps({"type": "给"}).encode()
    await sv._cenc_eew_ws.signal.send(data)

    assert len(called) == 1
