#!/usr/bin/env python3
"""Minimal example using mqtt_listener."""

import asyncio
import logging
import signal

from evse_hub.mqtt.interface import MQTTConfig, mqtt_listener

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s [%(levelname)s] %(name)s: %(message)s"
)
log = logging.getLogger(__name__)


async def handle_message(topic: str, payload: bytes) -> None:
    """Process incoming MQTT messages."""
    try:
        # Decode and log the message
        message = payload.decode('utf-8')
        log.info("Received on %s: %s", topic, message)
        
        # Add your message processing logic here
        # For example, parse JSON, extract power values, etc.
        
    except Exception as e:
        log.error("Error processing message from %s: %s", topic, e)




async def main() -> None:
    """Main entry point."""
    # Configuration
    config = MQTTConfig(
        broker="10.0.0.20",
        port=1883,
        mqtt_user="mqtt_user",
        mqtt_password="S9e4GgBTCLXXDVG",
        mqtt_interval=5.0,
        topics={
            "zigbee2mqtt/wohnung09": "wohnung09",
            "zigbee2mqtt/allgemeinstrom": "allgemeinstrom",
            "zigbee2mqtt/waermepumpe": "waermepumpe",
            "shellypro3em_bh/events/rpc": "begleitheizung"
        }
    )
    
    # Setup signal handling
    stop_event = asyncio.Event()
    
    def signal_handler(signum, frame):
        log.info("Received signal %s, shutting down...", signum)
        stop_event.set()
    
    signal.signal(signal.SIGINT, signal_handler)
    signal.signal(signal.SIGTERM, signal_handler)
    
    # Start MQTT listener
    log.info("Starting MQTT listener...")
    try:
        await mqtt_listener(config, stop_event, handle_message)
    except asyncio.CancelledError:
        log.info("Listener cancelled")
    finally:
        log.info("Shutdown complete")


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