"""Redis-backed negative cache for Binance Vision 404 responses."""

from __future__ import annotations

import logging
from datetime import UTC, datetime

logger = logging.getLogger(__name__)


def _is_vision_cached_unavailable(symbol: str, date_str: str) -> bool:
    """Check if Vision 404 was recorded recently (via Redis)."""
    from opendeviationbar.clickhouse.write_lock import _get_redis_client

    client = _get_redis_client()
    if client is None:
        return False  # No Redis = no cache = always try
    try:
        import redis

        return client.exists(f"odb:vision:404:{symbol}:{date_str}") > 0
    except (OSError, redis.exceptions.RedisError):
        logger.debug("Redis vision cache read failed", exc_info=True)
        return False


def _mark_vision_unavailable(symbol: str, date_str: str) -> None:
    """Record Vision 404 in Redis (persistent, cross-daemon).

    Uses a shorter TTL (15 min) for dates within 2 days of today since
    Vision archives for recent dates may not yet be published (PYEF-02).
    """
    from opendeviationbar.clickhouse.write_lock import _get_redis_client

    client = _get_redis_client()
    if client is None:
        return  # Graceful degradation — no negative cache

    # Dynamic TTL: recent dates get shorter cache (PYEF-02)
    from opendeviationbar.config.backfill import BackfillConfig

    cfg = BackfillConfig()
    try:
        parsed = datetime.strptime(date_str, "%Y-%m-%d").replace(tzinfo=UTC).date()
        days_ago = (datetime.now(tz=UTC).date() - parsed).days
        ttl = cfg.vision_probe_ttl_recent_s if days_ago <= 2 else cfg.vision_probe_ttl_s
    except (ValueError, TypeError):
        ttl = cfg.vision_probe_ttl_s  # fallback to standard 1h

    try:
        import redis

        client.set(
            f"odb:vision:404:{symbol}:{date_str}",
            "1",
            ex=ttl,
        )
    except (OSError, redis.exceptions.RedisError):
        logger.debug("Redis vision cache write failed", exc_info=True)
