import json
import redis.asyncio as redis

class RedisService:
    def __init__(self, host: str, port: int):
        self.client = redis.Redis(host=host, port=port, decode_responses=True)
    
    async def publish_task(self, task_data: dict):
        channel = "audio_tasks"
        await self.client.publish(channel, json.dumps(task_data))
    
    async def wait_for_text(self, user_id: int, chat_id: int, message_id: int, timeout: int = 30):
        pubsub = self.client.pubsub()
        await pubsub.subscribe("texts")
        try:
            async for message in pubsub.listen():
                if message["type"] != "message":
                    continue
                try:
                    data = json.loads(message["data"])
                except Exception:
                    continue
                if (data.get("user_id") == user_id and
                    data.get("chat_id") == chat_id and
                    data.get("message_id") == message_id):
                    return data.get("text")
        finally:
            await pubsub.unsubscribe("texts")
        return None