import json
from unittest.mock import AsyncMock, MagicMock

import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient

from control_backend.api.v1.endpoints import robot
from control_backend.schemas.ri_message import SpeechCommand


@pytest.fixture
def app():
    """
    Creates a FastAPI test app and attaches the router under test.
    Also sets up a mock internal_comm_socket.
    """
    app = FastAPI()
    app.include_router(robot.router)
    return app


@pytest.fixture
def client(app):
    """Create a test client for the app."""
    return TestClient(app)


def test_receive_command_success(client):
    """
    Test for successful reception of a command. Ensures the status code is 202 and the response body
    is correct. It also verifies that the ZeroMQ socket's send_multipart method is called with the
    expected data.
    """
    # Arrange
    mock_pub_socket = AsyncMock()
    client.app.state.endpoints_pub_socket = mock_pub_socket

    command_data = {"endpoint": "actuate/speech", "data": "This is a test"}
    speech_command = SpeechCommand(**command_data)

    # Act
    response = client.post("/command", json=command_data)

    # Assert
    assert response.status_code == 202
    assert response.json() == {"status": "Command received"}

    # Verify that the ZMQ socket was used correctly
    mock_pub_socket.send_multipart.assert_awaited_once_with(
        [b"command", speech_command.model_dump_json().encode()]
    )


def test_receive_command_invalid_payload(client):
    """
    Test invalid data handling (schema validation).
    """
    # Missing required field(s)
    bad_payload = {"invalid": "data"}
    response = client.post("/command", json=bad_payload)
    assert response.status_code == 422  # validation error


def test_ping_check_returns_none(client):
    """Ensure /ping_check returns 200 and None (currently unimplemented)."""
    response = client.get("/ping_check")
    assert response.status_code == 200
    assert response.json() is None


@pytest.mark.asyncio
async def test_ping_stream_yields_ping_event(monkeypatch):
    """Test that ping_stream yields a proper SSE message when a ping is received."""
    mock_sub_socket = AsyncMock()
    mock_sub_socket.connect = MagicMock()
    mock_sub_socket.setsockopt = MagicMock()
    mock_sub_socket.recv_multipart = AsyncMock(return_value=[b"ping", b"true"])

    mock_context = MagicMock()
    mock_context.socket.return_value = mock_sub_socket
    monkeypatch.setattr(robot.Context, "instance", lambda: mock_context)

    mock_request = AsyncMock()
    mock_request.is_disconnected = AsyncMock(side_effect=[False, True])

    response = await robot.ping_stream(mock_request)
    generator = aiter(response.body_iterator)

    event = await anext(generator)
    event_text = event.decode() if isinstance(event, bytes) else str(event)
    assert event_text.strip() == "data: true"

    with pytest.raises(StopAsyncIteration):
        await anext(generator)

    mock_sub_socket.connect.assert_called_once()
    mock_sub_socket.setsockopt.assert_called_once_with(robot.zmq.SUBSCRIBE, b"ping")
    mock_sub_socket.recv_multipart.assert_awaited()


@pytest.mark.asyncio
async def test_ping_stream_handles_timeout(monkeypatch):
    """Test that ping_stream continues looping on TimeoutError."""
    mock_sub_socket = AsyncMock()
    mock_sub_socket.connect = MagicMock()
    mock_sub_socket.setsockopt = MagicMock()
    mock_sub_socket.recv_multipart.side_effect = TimeoutError()

    mock_context = MagicMock()
    mock_context.socket.return_value = mock_sub_socket
    monkeypatch.setattr(robot.Context, "instance", lambda: mock_context)

    mock_request = AsyncMock()
    mock_request.is_disconnected = AsyncMock(return_value=True)

    response = await robot.ping_stream(mock_request)
    generator = aiter(response.body_iterator)

    with pytest.raises(StopAsyncIteration):
        await anext(generator)

    mock_sub_socket.connect.assert_called_once()
    mock_sub_socket.setsockopt.assert_called_once_with(robot.zmq.SUBSCRIBE, b"ping")
    mock_sub_socket.recv_multipart.assert_awaited()


@pytest.mark.asyncio
async def test_ping_stream_yields_json_values(monkeypatch):
    """Ensure ping_stream correctly parses and yields JSON body values."""
    mock_sub_socket = AsyncMock()
    mock_sub_socket.connect = MagicMock()
    mock_sub_socket.setsockopt = MagicMock()
    mock_sub_socket.recv_multipart = AsyncMock(
        return_value=[b"ping", json.dumps({"connected": True}).encode()]
    )

    mock_context = MagicMock()
    mock_context.socket.return_value = mock_sub_socket
    monkeypatch.setattr(robot.Context, "instance", lambda: mock_context)

    mock_request = AsyncMock()
    mock_request.is_disconnected = AsyncMock(side_effect=[False, True])

    response = await robot.ping_stream(mock_request)
    generator = aiter(response.body_iterator)

    event = await anext(generator)
    event_text = event.decode() if isinstance(event, bytes) else str(event)

    assert "connected" in event_text
    assert "true" in event_text

    mock_sub_socket.connect.assert_called_once()
    mock_sub_socket.setsockopt.assert_called_once_with(robot.zmq.SUBSCRIBE, b"ping")
    mock_sub_socket.recv_multipart.assert_awaited()
