import json
import logging

import pytest

from target_simulator.core.payload_router import PayloadRouter


def test_get_handlers_contains_expected_keys():
    router = PayloadRouter()
    handlers = router.get_handlers()
    assert isinstance(handlers, dict)
    # Expect flows for 'M','S','B','J'
    for ch in (ord('M'), ord('S'), ord('B'), ord('J')):
        assert ch in handlers
        assert callable(handlers[ch])


def test_handle_json_payload_valid(monkeypatch, caplog):
    router = PayloadRouter()
    payload = json.dumps({"type": "status_update", "value": 42}).encode('utf-8')
    caplog.set_level(logging.INFO)
    # Should not raise
    router.handle_json_payload(payload)
    # Expect log mentioning decoded type
    assert any("Decoded JSON message" in r.message or "Decoded JSON" in r.message for r in caplog.records)


def test_handle_json_payload_invalid(caplog):
    router = PayloadRouter()
    payload = b"not-a-json"
    caplog.set_level(logging.ERROR)
    router.handle_json_payload(payload)
    assert any("Error decoding JSON payload" in r.message for r in caplog.records)
