"""Redis connection and key scanning utilities."""

from __future__ import annotations

import redis.asyncio as aioredis


async def create_redis_client(url: str) -> aioredis.Redis:
    """Create an async Redis client from a URL."""
    return aioredis.from_url(url, decode_responses=True)


async def scan_keys(
    client: aioredis.Redis,
    pattern: str = "*",
    count: int = 100,
    cursor: int = 0,
) -> tuple[int, list[str]]:
    """Scan keys matching a glob pattern. Returns (next_cursor, keys)."""
    next_cursor, keys = await client.scan(cursor=cursor, match=pattern, count=count)
    return next_cursor, keys


async def get_key_info(client: aioredis.Redis, key: str) -> dict:
    """Get type, TTL, and value for a key."""
    key_type = await client.type(key)
    ttl = await client.ttl(key)
    size = await client.memory_usage(key) if key_type != "none" else None

    value = None
    if key_type == "string":
        value = await client.get(key)
    elif key_type == "list":
        length = await client.llen(key)
        value = await client.lrange(key, 0, min(length, 100) - 1)
    elif key_type == "set":
        members = await client.smembers(key)
        value = sorted(members)[:100]
    elif key_type == "zset":
        value = await client.zrange(key, 0, 99, withscores=True)
    elif key_type == "hash":
        value = await client.hgetall(key)
    elif key_type == "stream":
        value = await client.xrange(key, count=100)

    return {
        "key": key,
        "type": key_type,
        "ttl": ttl if ttl >= 0 else None,
        "size": size,
        "value": value,
    }
