"""
Unit tests for core.redis (Story 6-3).
Tests shared Redis client helpers when REDIS_URL is unset or connection fails.
"""
import pytest


def test_get_redis_url_empty_when_not_set(monkeypatch):
    """REDIS_URL not set -> get_redis_url returns empty string."""
    monkeypatch.delenv("REDIS_URL", raising=False)
    from core.redis import get_redis_url

    assert get_redis_url() == ""


def test_get_redis_url_returns_stripped_value(monkeypatch):
    """REDIS_URL set -> get_redis_url returns stripped value."""
    monkeypatch.setenv("REDIS_URL", " redis://localhost:6379/0 ")
    from core.redis import get_redis_url

    assert get_redis_url() == "redis://localhost:6379/0"


def test_ping_sync_not_configured(monkeypatch):
    """When get_sync_redis returns None, ping_sync returns (False, 'not_configured')."""
    from core.redis import ping_sync, get_sync_redis

    monkeypatch.setattr("core.redis.get_sync_redis", lambda: None)
    ok, err = ping_sync()
    assert ok is False
    assert err == "not_configured"


@pytest.mark.asyncio
async def test_get_job_status_async_returns_none_when_no_redis(monkeypatch):
    """When get_async_redis returns None, get_job_status_async returns None."""
    monkeypatch.setattr("core.redis.get_async_redis", lambda: None)
    from core.redis import get_job_status_async

    result = await get_job_status_async("tr_test_123")
    assert result is None


@pytest.mark.asyncio
async def test_set_job_status_async_returns_false_when_no_redis(monkeypatch):
    """When get_async_redis returns None, set_job_status_async returns False."""
    monkeypatch.setattr("core.redis.get_async_redis", lambda: None)
    from core.redis import set_job_status_async

    ok = await set_job_status_async("tr_test_123", {"status": "queued"})
    assert ok is False


def test_ping_sync_returns_true_when_redis_ok(monkeypatch):
    """When sync client pings successfully, ping_sync returns (True, '')."""
    mock_client = type("MockRedis", (), {"ping": lambda self: None})()
    monkeypatch.setattr("core.redis.get_sync_redis", lambda: mock_client)
    from core.redis import ping_sync

    ok, err = ping_sync()
    assert ok is True
    assert err == ""
