"""
Einfache MQTT-Hilfsfunktion für Client-Gruppenzuordnungen
"""
import os
import json
import logging
import paho.mqtt.client as mqtt

logger = logging.getLogger(__name__)


def publish_client_group(client_uuid: str, group_id: int) -> bool:
    """
    Publiziert die Gruppenzuordnung eines Clients als retained message

    Args:
        client_uuid: UUID des Clients
        group_id: ID der Gruppe

    Returns:
        bool: True bei Erfolg, False bei Fehler
    """
    try:
        # MQTT-Konfiguration aus .env
        broker_host = os.getenv("MQTT_BROKER_HOST", "mqtt")
        broker_port = int(os.getenv("MQTT_BROKER_PORT", 1883))
        username = os.getenv("MQTT_USER")
        password = os.getenv("MQTT_PASSWORD")

        # Topic und Payload
        topic = f"infoscreen/{client_uuid}/group_id"
        payload = json.dumps({
            "group_id": group_id,
            "client_uuid": client_uuid
        })

        # MQTT-Client erstellen und verbinden
        client = mqtt.Client()
        if username and password:
            client.username_pw_set(username, password)

        client.connect(broker_host, broker_port, 60)

        # Retained message publizieren
        result = client.publish(topic, payload, qos=1, retain=True)
        result.wait_for_publish(timeout=5.0)

        client.disconnect()

        logger.info(
            f"Group assignment published for client {client_uuid}: group_id={group_id}")
        return True

    except Exception as e:
        logger.error(
            f"Error publishing group assignment for client {client_uuid}: {e}")
        return False


def publish_multiple_client_groups(client_group_mappings: dict) -> tuple[int, int]:
    """
    Publiziert Gruppenzuordnungen für mehrere Clients in einer Verbindung

    Args:
        client_group_mappings: Dict mit {client_uuid: group_id}

    Returns:
        tuple: (success_count, failed_count)
    """
    try:
        broker_host = os.getenv("MQTT_BROKER_HOST", "mqtt")
        broker_port = int(os.getenv("MQTT_BROKER_PORT", 1883))
        username = os.getenv("MQTT_USER")
        password = os.getenv("MQTT_PASSWORD")

        client = mqtt.Client()
        if username and password:
            client.username_pw_set(username, password)

        client.connect(broker_host, broker_port, 60)

        success_count = 0
        failed_count = 0

        for client_uuid, group_id in client_group_mappings.items():
            try:
                topic = f"infoscreen/{client_uuid}/group_id"
                payload = json.dumps({
                    "group_id": group_id,
                    "client_uuid": client_uuid
                })

                result = client.publish(topic, payload, qos=1, retain=True)
                result.wait_for_publish(timeout=5.0)
                success_count += 1

            except Exception as e:
                logger.error(f"Failed to publish for {client_uuid}: {e}")
                failed_count += 1

        client.disconnect()

        logger.info(
            f"Bulk publish completed: {success_count} success, {failed_count} failed")
        return success_count, failed_count

    except Exception as e:
        logger.error(f"Error in bulk publish: {e}")
        return 0, len(client_group_mappings)


def delete_client_group_message(client_uuid: str) -> bool:
    """
    Löscht die retained message für einen Client (bei Client-Löschung)
    """
    try:
        broker_host = os.getenv("MQTT_BROKER_HOST", "mqtt")
        broker_port = int(os.getenv("MQTT_BROKER_PORT", 1883))
        username = os.getenv("MQTT_USER")
        password = os.getenv("MQTT_PASSWORD")

        topic = f"infoscreen/{client_uuid}/group_id"

        client = mqtt.Client()
        if username and password:
            client.username_pw_set(username, password)

        client.connect(broker_host, broker_port, 60)

        # Leere retained message löscht die vorherige
        result = client.publish(topic, "", qos=1, retain=True)
        result.wait_for_publish(timeout=5.0)

        client.disconnect()

        logger.info(f"Deleted retained group message for client {client_uuid}")
        return True

    except Exception as e:
        logger.error(
            f"Error deleting group message for client {client_uuid}: {e}")
        return False
