# scheduler/scheduler.py
from scheduler.db_utils import get_active_events
import paho.mqtt.client as mqtt
import json
import datetime
import time

def main():
    # Fix für die veraltete API - explizit callback_api_version setzen
    client = mqtt.Client(callback_api_version=mqtt.CallbackAPIVersion.VERSION2)
    client.connect("mqtt", 1883)

    POLL_INTERVAL = 10  # Sekunden
    last_sent_event_ids = set()

    while True:
        now = datetime.datetime.now()
        # Hole alle Events, die jetzt aktiv sind (start < now < end)
        events = get_active_events(now, now)
        current_event_ids = set(event.id for event in events)

        # Sende nur neue Events (die noch nicht gesendet wurden)
        new_event_ids = current_event_ids - last_sent_event_ids
        for event in events:
            if event.id in new_event_ids:
                # Beispiel: Sende Event-Daten als JSON auf Topic "infoscreen/events"
                payload = json.dumps({
                    "id": event.id,
                    "title": getattr(event, "title", ""),
                    "start": str(getattr(event, "start", "")),
                    "end": str(getattr(event, "end", "")),
                    "group_id": getattr(event, "group_id", None),
                })
                client.publish("infoscreen/events", payload)
                print(f"Event {event.id} gesendet: {payload}")

        last_sent_event_ids = current_event_ids
        time.sleep(POLL_INTERVAL)


if __name__ == "__main__":
    main()
