import dbus
from dbus.mainloop.glib import DBusGMainLoop
import logging

DBusGMainLoop(set_as_default=True)
logger = logging.getLogger(__name__)

bus = None
service = None
sam_interface = None
error = False
error_msg = None

try:
    bus = dbus.SystemBus()
    service = bus.get_object('io.stillhq.SamService', '/io/stillhq/SamService')
    sam_interface = dbus.Interface(service, 'io.stillhq.SamService')
    logger.debug("Connected to SAM D-Bus service")
except dbus.exceptions.DBusException as e:
    error = True
    error_msg = str(e)
    logger.error("Failed to connect to SAM D-Bus service: %s", e)

## Detect if there's an error
def get_sam_error() -> (bool, str):
    if error:
        return True, "SAM D-Bus connection error: " + error_msg
    try:
        # Try to get a property from the interface to verify connection
        sam_interface.get_version()
        logger.debug("SAM D-Bus health check succeeded")
        return False, "Connected successfully"
    except dbus.exceptions.DBusException as e:
        logger.error("SAM D-Bus health check failed: %s", e)
        return True, "SAM D-Bus connection error: " + str(e)
    except Exception as e:
        logger.exception("Unexpected error connecting to SAM")
        return True, "Unexpected error connecting to SAM: " + str(e)