from collections.abc import AsyncGenerator

import redis.asyncio as redis

from app.config import get_settings

_settings = get_settings()
_redis: redis.Redis | None = None


async def init_redis() -> redis.Redis:
    global _redis
    _redis = redis.from_url(
        _settings.redis_url,
        encoding="utf-8",
        decode_responses=True,
    )
    await _redis.ping()
    return _redis


async def close_redis() -> None:
    global _redis
    if _redis is not None:
        await _redis.aclose()
        _redis = None


def get_redis() -> redis.Redis:
    if _redis is None:
        raise RuntimeError("Redis 尚未初始化")
    return _redis


async def redis_dependency() -> AsyncGenerator[redis.Redis, None]:
    yield get_redis()
