"""Redis-based alert deduplication for heartbeat monitoring."""

from __future__ import annotations

import hashlib
import logging
import os

from heartbeat.config import ALERT_DEDUP_TTL

logger = logging.getLogger("health-heartbeat")


def get_redis() -> object | None:
    """Get Redis client (best-effort, returns None if unavailable)."""
    try:
        import redis

        r = redis.Redis(
            host=os.environ.get("OPENDEVIATIONBAR_REDIS_HOST", "localhost"),
            port=int(os.environ.get("OPENDEVIATIONBAR_REDIS_PORT", "6379")),
            socket_timeout=2,
        )
        r.ping()
        return r
    except Exception:
        logger.warning("Redis connect failed — continuing without dedup", exc_info=True)
        return None


def should_alert(redis_client: object | None, condition: str) -> bool:
    """Check if we should send an alert for this condition (Redis dedup).

    Returns True if the alert should be sent (not a duplicate within TTL).
    Always returns True if Redis is unavailable (fail-open).
    """
    if redis_client is None:
        return True
    key = f"odb:heartbeat:alert:{hashlib.md5(condition.encode()).hexdigest()[:12]}"
    try:
        if redis_client.exists(key):
            return False
        redis_client.setex(key, ALERT_DEDUP_TTL, "1")
        return True
    except Exception:
        logger.warning("Redis dedup check failed — sending alert (fail-open)", exc_info=True)
        return True  # Fail-open: send the alert
