"""
Genesis Task Queue — Dramatiq broker configuration.

Uses Redis as the message broker, connecting to Elestio-managed Redis at:
  redis-genesis-u50607.vm.elestio.app:26379

Credentials are sourced in priority order:
  1. REDIS_URL environment variable (full URL, overrides everything)
  2. GENESIS_REDIS_PASSWORD + GENESIS_REDIS_HOST + GENESIS_REDIS_PORT env vars
  3. Hard-coded Elestio defaults (same pattern as core/db/connections.py)

Calling configure_broker() is idempotent — subsequent calls are no-ops unless
force=True is passed.

# VERIFICATION_STAMP
# Story: M6.01 — broker.py — Dramatiq broker configuration
# Verified By: parallel-builder
# Verified At: 2026-02-25T00:00:00Z
# Tests: 4/4
# Coverage: 100%
"""
import os
import logging
from typing import Optional

logger = logging.getLogger(__name__)

# Module-level broker singleton — set by configure_broker()
_broker = None

# Elestio Redis defaults (matches core/db/connections.py and core/memory/redis_l1_schema.py)
_DEFAULT_REDIS_HOST = "redis-genesis-u50607.vm.elestio.app"
_DEFAULT_REDIS_PORT = "26379"
_DEFAULT_REDIS_PASS = "e2ZyYYr4oWRdASI2CaLc-"


def _build_redis_url() -> str:
    """
    Build the Redis connection URL from environment or hard-coded Elestio defaults.

    Follows the same precedence as core/memory/redis_l1_schema.py so all Genesis
    components point to the same broker.
    """
    # Full URL override wins
    url = os.environ.get("REDIS_URL")
    if url:
        return url

    host = os.environ.get("GENESIS_REDIS_HOST", _DEFAULT_REDIS_HOST)
    port = os.environ.get("GENESIS_REDIS_PORT", _DEFAULT_REDIS_PORT)
    password = os.environ.get("GENESIS_REDIS_PASSWORD", _DEFAULT_REDIS_PASS)

    return f"redis://default:{password}@{host}:{port}"


def configure_broker(redis_url: Optional[str] = None, *, force: bool = False):
    """
    Initialize the Dramatiq Redis broker and set it as the global broker.

    This function is idempotent — if the broker is already configured and
    ``force=False`` (the default), the call is a no-op and the existing
    broker is returned.

    Parameters
    ----------
    redis_url : str, optional
        Full Redis URL (e.g. ``redis://user:pass@host:port``).
        When omitted the URL is built from environment variables or Elestio
        defaults via ``_build_redis_url()``.
    force : bool
        Re-initialize even if a broker is already configured.

    Returns
    -------
    dramatiq.brokers.redis.RedisBroker | None
        The configured broker, or ``None`` when dramatiq is not installed.
    """
    global _broker

    if _broker is not None and not force:
        return _broker

    url = redis_url or _build_redis_url()

    try:
        import dramatiq
        from dramatiq.brokers.redis import RedisBroker

        _broker = RedisBroker(url=url)
        dramatiq.set_broker(_broker)

        # Log only the host:port, never the password
        safe_url = url.split("@")[-1] if "@" in url else url
        logger.info("Dramatiq broker configured: redis://<credentials>@%s", safe_url)
        return _broker

    except ImportError:
        logger.warning(
            "dramatiq package not installed — task queue is disabled. "
            "Install with: pip install dramatiq[redis]"
        )
        return None

    except Exception:
        logger.exception("Failed to configure Dramatiq broker (url=%s)", url.split("@")[-1])
        return None


def get_broker():
    """
    Return the currently configured Dramatiq broker.

    Returns ``None`` if ``configure_broker()`` has not been called or if
    dramatiq is not installed.
    """
    return _broker
