import dbus
from dbus.mainloop.glib import DBusGMainLoop

DBusGMainLoop(set_as_default=True)

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')
except dbus.exceptions.DBusException as e:
    error = True
    error_msg = str(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()
        return False, "Connected successfully"
    except dbus.exceptions.DBusException as e:
        return True, "SAM D-Bus connection error: " + str(e)
    except Exception as e:
        return True, "Unexpected error connecting to SAM: " + str(e)