import time
import sys
import os
import threading

# Add application directory to path
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from config.db import get_db_connection
from config.mqtt_config import BROKER, PORT, TOPIC_UTILS, TOPIC_POWER, MQTTClientBase
from blueprints.mqtt_device import handle_utils_message
from blueprints.power_monitor import on_message_callback

def start_utils_client():
    print(f"🚀 Starting MQTT subscriber for Topic: {TOPIC_UTILS}")
    client = MQTTClientBase(
        broker=BROKER,
        port=PORT,
        topic=TOPIC_UTILS,
        on_message_callback=handle_utils_message
    )
    # Loop forever in this thread
    client.client.connect(client.broker, client.port, 60)
    client.client.loop_forever()

def start_power_client():
    print(f"🚀 Starting MQTT subscriber for Topic: {TOPIC_POWER}")
    client = MQTTClientBase(
        broker=BROKER,
        port=PORT,
        topic=TOPIC_POWER,
        on_message_callback=on_message_callback
    )
    # Loop forever in this thread
    client.client.connect(client.broker, client.port, 60)
    client.client.loop_forever()

if __name__ == "__main__":
    import fcntl
    # File lock to prevent multiple instances from running on shared hosting (no pgrep needed)
    lock_file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'run_mqtt.lock')
    try:
        lock_file = open(lock_file_path, 'w')
        fcntl.lockf(lock_file, fcntl.LOCK_EX | fcntl.LOCK_NB)
    except IOError:
        print("[INFO] Another instance of run_mqtt.py is already running. Exiting.")
        sys.exit(0)

    print("=== IoT MQTT Background Daemon ===")
    print(f"Broker: {BROKER}:{PORT}")
    
    # Run both subscribers in threads
    t1 = threading.Thread(target=start_utils_client)
    t2 = threading.Thread(target=start_power_client)
    
    t1.daemon = True
    t2.daemon = True
    
    t1.start()
    t2.start()
    
    # Keep main thread alive
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        print("\nStopping MQTT daemon...")
