import os
import json
import logging
import paho.mqtt.client as mqtt

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from models.models import Client

# Logging
logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s [%(levelname)s] %(message)s')

# DB-Konfiguration (Beispiel: MariaDB/MySQL, anpassen!)
DB_URL = os.environ.get(
    "DB_URL", "mysql+pymysql://user:password@db/infoscreen")
engine = create_engine(DB_URL)
Session = sessionmaker(bind=engine)


# MQTT-Callback


def on_message(client, userdata, msg):
    try:
        payload = json.loads(msg.payload.decode())
        logging.info(f"Discovery empfangen: {payload}")
        session = Session()
        # Prüfen, ob Client schon existiert
        existing = session.query(Client).filter_by(
            client_id=payload["client_id"]).first()
        if not existing:
            new_client = Client(
                client_id=payload.get("client_id"),
                hardware_token=payload.get("hardware_token"),
                ip=payload.get("ip"),
                type=payload.get("type"),
                hostname=payload.get("hostname"),
                os_version=payload.get("os_version"),
                software_version=payload.get("software_version"),
                macs=",".join(payload.get("macs", [])),
                model=payload.get("model"),
            )
            session.add(new_client)
            session.commit()
            logging.info(f"Neuer Client registriert: {payload['client_id']}")
        else:
            logging.info(f"Client bereits bekannt: {payload['client_id']}")
        session.close()
    except Exception as e:
        logging.error(f"Fehler bei Verarbeitung: {e}")


def main():
    mqtt_client = mqtt.Client(protocol=mqtt.MQTTv311, callback_api_version=2)
    mqtt_client.on_message = on_message
    mqtt_client.connect("mqtt", 1883)
    mqtt_client.subscribe("infoscreen/discovery")
    logging.info("Listener gestartet und abonniert auf infoscreen/discovery")
    mqtt_client.loop_forever()


if __name__ == "__main__":
    main()
