import asyncio
import httpx
from datetime import datetime, timezone

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

import redis

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

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

ACTIVE_KEY = "echoweather:active_alerts"


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


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


async def run():
    print("[EchoWeather] Lifecycle engine started...")

    while True:
        try:
            data = await fetch()
            current_ids = extract_ids(data)

            # -----------------------------
            # STEP 1: mark active alerts
            # -----------------------------
            REDIS.delete(ACTIVE_KEY)
            if current_ids:
                REDIS.sadd(ACTIVE_KEY, *current_ids)

            # -----------------------------
            # STEP 2: find expired alerts
            # -----------------------------
            with SessionLocal() as db:
                active_db_alerts = db.query(Alert).filter(Alert.active == True).all()

                for alert in active_db_alerts:
                    if alert.id not in current_ids:

                        alert.active = False
                        db.commit()

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

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

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

        await asyncio.sleep(60)


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