import asyncio
import httpx
import redis

from backend.database.session import SessionLocal
from backend.database.models import Alert

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

URL = "https://api.weather.gov/alerts/active"


async def fetch():
    async with httpx.AsyncClient(timeout=30) as c:
        r = await c.get(URL)
        r.raise_for_status()
        return r.json()


def active_ids(data):
    return {f["properties"]["id"] for f in data.get("features", [])}


async def run():
    print("[Lifecycle] Started")

    while True:
        try:
            data = await fetch()
            current = active_ids(data)

            with SessionLocal() as db:
                db_alerts = db.query(Alert).filter(Alert.active == True).all()

                for alert in db_alerts:
                    if alert.id not in current:
                        alert.active = False
                        db.commit()

                        REDIS.publish(
                            "echoweather:alerts:expired",
                            alert.id
                        )

                        print(f"[EXPIRED] {alert.event}")

        except Exception as e:
            print("[LIFECYCLE ERROR]", e)

        await asyncio.sleep(60)


if __name__ == "__main__":
    asyncio.run(run())
