import asyncio
import json
from evenage.core import EvenAgeConfig
from evenage.core.message_bus import MemoryBus
from evenage.core.storage import InMemoryStorage


def test_offload_on_large_response():
    storage = InMemoryStorage()
    bus = MemoryBus()
    # attach storage and low threshold to force offload
    setattr(bus, "_storage", storage)
    setattr(bus, "_storage_bucket", "evenage")
    setattr(bus, "_storage_threshold_kb", 1)  # 1 KB

    async def run():
        large_payload = {"data": "x" * 5000}
        task_id = "t-123"
        ok = await bus.publish_response(task_id, {"status": "success", "result": large_payload})
        assert ok
        resp = await bus.wait_for_response(task_id, 1)
        assert resp is not None
        assert resp.get("offloaded") is True
        # Ensure object exists in storage
        obj = await storage.get_object(resp["bucket"], resp["key"])  # type: ignore
        assert obj is not None
        # Optional: verify content decodes as JSON
        content = obj["body"] if isinstance(obj, dict) else obj  # InMemoryStorage may return dict
        if isinstance(content, (bytes, bytearray)):
            data = json.loads(content.decode("utf-8"))
            assert data["result"]["data"].startswith("x")

    asyncio.run(run())
