import asyncio
import json
import redis

from backend.discord.router import route

REDIS = redis.Redis(host="localhost", port=6379, decode_responses=True)

CHANNEL_MAP = {
    "storm-emergencies": 1522099044669984850,
    "tornado": 1522099061459521656,
    "severe-storms": 1522099083706105947,
    "flood": 1522099101930360862,
    "advisories": 1522099154804019220,
    "other-weather-alerts": 1522099168020271155,
}

bot = None
bot_ready = False


def start(discord_bot):
    global bot, bot_ready
    bot = discord_bot
    bot_ready = True
    asyncio.create_task(redis_loop())
    print("[StateEngine] Listening to Redis alerts...")


async def redis_loop():
    pubsub = REDIS.pubsub()
    pubsub.subscribe("echoweather:alerts:new")

    while True:
        try:
            msg = pubsub.get_message(ignore_subscribe_messages=True, timeout=1.0)

            if not msg:
                await asyncio.sleep(0.1)
                continue

            data = json.loads(msg["data"])

            # FORCE SAFE DICT ACCESS (NO OBJECTS EVER)
            event = data.get("event", "Unknown")
            tier = data.get("tier", "unknown")
            category = data.get("category", "unknown")
            headline = data.get("headline", "")
            description = data.get("description", "")

            channel_name = route(data)
            channel_id = CHANNEL_MAP.get(channel_name)

            if not channel_id or not bot_ready:
                continue

            channel = bot.get_channel(channel_id)

            if channel is None:
                continue

            await channel.send(
                f"🚨 **{event}**\n"
                f"Tier: {tier} | Category: {category}\n\n"
                f"{headline}\n\n"
                f"{description}"
            )

        except Exception as e:
            print("[STATE ENGINE ERROR]", e)
            await asyncio.sleep(1)


