"""
Message bus connector helpers.

Provides connect_bus() for redis and memory implementations in core.message_bus.
Optionally accepts a storage backend and threshold to enable large-response offload.
"""
from __future__ import annotations

from typing import Any, Literal


def connect_bus(
    backend: Literal["redis", "memory", "kafka"],
    *,
    redis_url: str | None = None,
    kafka_bootstrap: str | None = None,
    storage: Any | None = None,
    storage_bucket: str | None = None,
    storage_threshold_kb: int | None = None,
) -> Any:
    """
    Connect to a message bus backend.

    Args:
        backend: "redis" or "memory"
        redis_url: Required if backend="redis"
        storage: Optional storage backend for auto-offload
        storage_bucket: Optional bucket name for offloaded responses
        storage_threshold_kb: Optional threshold in KB to offload

    Returns:
        RedisBus or MemoryBus instance
    """
    from evenage.core.backends.queue import KafkaBus, MemoryBus, RedisBus

    if backend == "redis":
        if not redis_url:
            raise ValueError("redis_url is required for redis backend")
        bus = RedisBus(redis_url)
    elif backend == "memory":
        bus = MemoryBus()
    elif backend == "kafka":
        if not kafka_bootstrap:
            raise ValueError("kafka_bootstrap is required for kafka backend")
        bus = KafkaBus(kafka_bootstrap)
    else:
        raise ValueError(f"Unsupported bus backend: {backend}")

    # If the bus supports setting optional storage/threshold, attach them here.
    # The core bus may not know these attributes yet; set them conditionally.
    if storage is not None:
        bus._storage = storage
    if storage_bucket is not None:
        bus._storage_bucket = storage_bucket
    if storage_threshold_kb is not None:
        bus._storage_threshold_kb = storage_threshold_kb

    return bus
