#!/usr/bin/env python3
# SPDX-FileCopyrightText: Copyright (c) 2026 misc-de
# SPDX-License-Identifier: MIT
"""Reconnect a Bluetooth audio device that nobody is reconnecting.

BlueZ dials a paired device on its own in exactly two situations: when the
adapter is powered on, and when a connection was lost to radio trouble. A
device that simply hung up - earbuds going into their case, a headset whose
battery ran out, a car that drove away - is never called again. On Android
something does; on phosh nothing does, so the earbuds sit in your ears, awake
and in range, while the phone plays through its loudspeaker.

Measured on 2026-09-15: the earbuds disconnected at 12:05:21, and at 13:44
they answered a remote name request within a second - both sides ready, no
connection, because neither side had any reason to start one. The adapter was
powered and page-scanning the whole time, so nothing was broken. It was simply
that nobody dialled.

This dials. What it does NOT do is poll: every attempt is a page, which is
seconds of radio and a real cost on a phone that never suspends. So it works
by occasions, of which there are four:

  a disconnect     a short series of attempts with growing gaps, for earbuds
                   that went briefly out of range or into a pocket.

  waking up        one attempt when the phone comes back from idle or from
                   the lock screen - you picked the phone up, so you are
                   there, and so, probably, are the earbuds.

  display on       one attempt when the display is switched on, as MCE
                   announces it (MCE_SIGNAL_IFACE). Earlier than the lock
                   screen going away, and it also happens on a phone without
                   a lock screen.

  music starts     one attempt when a media player starts playing (MPRIS).
                   Taking the earbuds out of their case with the phone already
                   in hand is no occasion at all otherwise, and pressing play
                   is the moment the earbuds are wanted.

Earbuds do try to connect themselves when they leave their case, and mostly it
works. Measured on the Plinius on 2026-11-11 with a pair of earbuds: out
of the case at 13:24:48, connected the same second, nothing dialled. An hour
earlier the same earbuds came out of the same case and nothing arrived at the
phone's BlueZ at all - their own attempt is short, and when it misses, it is not
repeated. The occasions are for that.

Between the occasions it does nothing at all, which is the point: a phone that
pages a device every thirty seconds all night to find it switched off has
spent the battery this repository has spent months protecting.

The candidate is only ever a device this service watched disconnect - and,
since a reboot would forget it, one it watched disconnect before the reboot
(STATE_FILE). Paired audio devices on this phone include a car kit and an OBD
adapter, and paging those because somebody's headset is missing would be noise
on the air and a car radio switching on in a parked car. A car kit calls itself
an audio headset in BlueZ's Icon as well, so the device class decides: only
headphones and wearable headsets are dialled (is_headphones). Nothing is
dialled that was not there a moment ago.
"""

import json
import os
import time

import gi

gi.require_version("Gio", "2.0")
from gi.repository import Gio, GLib  # noqa: E402

# Same list as the pause-on-disconnect watcher: the profiles that carry sound.
# A keyboard or a fitness tracker dropping off is not something to dial back.
AUDIO_UUID_PREFIXES = (
    "0000110a",   # AudioSource   (A2DP)
    "0000110b",   # AudioSink     (A2DP)
    "00001108",   # Headset
    "00001112",   # Headset AG
    "0000111e",   # Handsfree
    "0000111f",   # Handsfree AG
)

# Seconds after a disconnect at which to try again. They grow because the
# cost does not: a failed attempt is a page timeout, around ten seconds of
# radio, whether it is the first or the fifth. Four attempts over a quarter of
# an hour cover "walked out of range and came back" and then stop - after that
# the earbuds are off or elsewhere, and waking up is the better occasion.
RETRY_DELAYS_S = (20, 60, 180, 600)

# How long a connection has to last before it counts as wanted. Earbuds with
# multipoint hand themselves to a laptop and drop us again within a couple of
# seconds; dialling them back turns that into a tug of war, with the music
# jumping between two machines. Under this, the device is left alone until the
# next occasion.
KEPT_S = 30

# The shortest gap between two attempts made because the phone woke up.
#
# Not a theory: the first run of this service on the phone connected through
# the waking-up path within seconds of a disconnect, because logind's IdleHint
# had gone false. That occasion is unbounded - a phone is picked up and put
# down all day, and every attempt is a page, ten seconds of radio when the
# device is not there. The series after a disconnect needs no such limit
# because it stops by itself after four.
WAKE_MIN_GAP_S = 300

# The shortest gap before an attempt because music started. Shorter than the
# one for waking up, because pressing play is something somebody did on
# purpose, and there are not dozens of those an hour - but not none, because a
# player that skips through a playlist reports Playing for every track.
MUSIC_MIN_GAP_S = 60

# The display state as MCE broadcasts it: display_status_ind("on" | "dimmed" |
# "off") on the system bus, the interface Sailfish OS uses and ofono listens
# to. On the Plinius it comes from plinius-mce, which is told by
# plinius-backlight-wake - the always-on clock counting as off. Nothing else on
# phosh publishes the display state. Without an MCE the signal never arrives
# and this occasion simply does not happen.
MCE_SERVICE = "com.nokia.mce"
MCE_SIGNAL_PATH = "/com/nokia/mce/signal"
MCE_SIGNAL_IFACE = "com.nokia.mce.signal"

# Where the candidate is kept across a restart of this service or the phone:
# earbuds that went into their case before a reboot are just as worth dialling
# after it, and without this a reboot is a day of nothing being dialled.
STATE_FILE = os.path.join(
    os.environ.get("XDG_STATE_HOME")
    or os.path.join(os.path.expanduser("~"), ".local", "state"),
    "furios-audio", "bt-reconnect.json")
RESTORE_TRIES = 6
RESTORE_RETRY_S = 10

# Bluetooth class of device: major class Audio/Video, and the minor classes
# that are something worn on the head. A car kit is Audio/Video too, with the
# minor class hands-free (2) or car audio (8) - and BlueZ gives it the same
# Icon "audio-headset" as earbuds, so the Icon cannot tell them apart.
# Measured on the Plinius: earbuds 0x248404 (minor 1), the
# car kit 0x240408 (minor 2).
CLASS_MAJOR_AUDIO_VIDEO = 4
HEADPHONE_MINOR_CLASSES = (
    1,      # wearable headset
    6,      # headphones
)

# How long a device stays worth dialling after it went. Earbuds left in a
# drawer over a weekend must not be paged on every unlock for the rest of the
# month; after a day of nothing, the next connection can be made by hand.
CANDIDATE_TTL_S = 24 * 3600

# BlueZ takes as long as a page timeout to answer Connect(), and the answer is
# worth waiting for - it says whether the device was there at all.
CONNECT_TIMEOUT_MS = 30000

# Music on a headset that is still connected.
#
# A WirePlumber restart unregisters its A2DP endpoints, BlueZ closes the music
# stream with them, and the new WirePlumber registers fresh endpoints that
# nobody connects to. The headset stays on the air - hands-free comes back by
# itself - so there is no disconnect for the series above to react to, and
# the card offers nothing but hands-free: music plays narrow-band and mono, or
# not on the headset at all. Seen after every restart on 2026-09-25 (17:40,
# 17:52, 18:14, 18:33); ConnectProfile for the A2DP sink brought it back each
# time, by hand.
#
# So when a music transport goes away under a device that stays connected,
# look again after A2DP_CHECK_S - long enough for WirePlumber to be back and
# for the headset to reconnect on its own if it is going to - and connect the
# A2DP profile if it is still missing. At most once per A2DP_MIN_GAP_S per
# device: earbuds that hand their music to a laptop drop the stream too, and
# pulling it back every few seconds would be a tug of war.
A2DP_SINK_UUID = "0000110b-0000-1000-8000-00805f9b34fb"
A2DP_CHECK_S = 8
A2DP_MIN_GAP_S = 300


def carries_audio(system, path):
    """Is this a device that could carry sound?

    The opposite of the pause watcher's question, and so the opposite default:
    there, doubt means pause, because the cost of not pausing is a podcast on
    a loudspeaker. Here, doubt means leave it alone - the cost of dialling
    something that is not a headset is paging a car in a car park.
    """
    try:
        uuids = system.call_sync(
            "org.bluez", path, "org.freedesktop.DBus.Properties", "Get",
            GLib.Variant("(ss)", ("org.bluez.Device1", "UUIDs")),
            GLib.VariantType("(v)"), Gio.DBusCallFlags.NONE, 1000, None,
        ).unpack()[0]
    except GLib.Error as err:
        print("could not read what %s is: %s - leaving it alone"
              % (path.rsplit("/", 1)[-1], err), flush=True)
        return False
    if not isinstance(uuids, (list, tuple)):
        return False
    return any(str(u)[:8].lower() in AUDIO_UUID_PREFIXES for u in uuids)


def is_trusted(system, path):
    """Has this device been trusted to connect without being asked?

    Trusted is BlueZ's own word for "this may connect whenever it likes", set
    when the device was paired from the phone. Dialling an untrusted device
    would be deciding something the pairing deliberately left open.
    """
    try:
        return bool(system.call_sync(
            "org.bluez", path, "org.freedesktop.DBus.Properties", "Get",
            GLib.Variant("(ss)", ("org.bluez.Device1", "Trusted")),
            GLib.VariantType("(v)"), Gio.DBusCallFlags.NONE, 1000, None,
        ).unpack()[0])
    except GLib.Error as err:
        print("could not read whether %s is trusted: %s - leaving it alone"
              % (path.rsplit("/", 1)[-1], err), flush=True)
        return False


def is_headphones(system, path):
    """Is this something worn on the head - not a car kit, not a speaker?

    By the class of device, see HEADPHONE_MINOR_CLASSES. A device without a
    class (BLE only, or never seen in an inquiry) is left alone: doubt means
    leave it alone here, as in carries_audio.
    """
    try:
        cls = system.call_sync(
            "org.bluez", path, "org.freedesktop.DBus.Properties", "Get",
            GLib.Variant("(ss)", ("org.bluez.Device1", "Class")),
            GLib.VariantType("(v)"), Gio.DBusCallFlags.NONE, 1000, None,
        ).unpack()[0]
    except GLib.Error:
        return False
    if not isinstance(cls, int):
        return False
    return ((cls >> 8) & 0x1f == CLASS_MAJOR_AUDIO_VIDEO
            and (cls >> 2) & 0x3f in HEADPHONE_MINOR_CLASSES)


def bluez_answers(system):
    """Is bluetoothd on the bus? Asked of the bus, not of BlueZ."""
    try:
        return bool(system.call_sync(
            "org.freedesktop.DBus", "/org/freedesktop/DBus",
            "org.freedesktop.DBus", "NameHasOwner",
            GLib.Variant("(s)", ("org.bluez",)), GLib.VariantType("(b)"),
            Gio.DBusCallFlags.NONE, 1000, None,
        ).unpack()[0])
    except GLib.Error:
        return False


def save_candidate(path, name, state_file=None):
    """Remember the candidate on disk, with the wall-clock time it went.

    Wall clock and not monotonic, because the point is to survive a reboot,
    and the monotonic clock starts again at zero with every boot. Failing to
    write is said and otherwise ignored: the service works as before, it only
    forgets the candidate at the next restart.
    """
    state_file = state_file or STATE_FILE
    try:
        os.makedirs(os.path.dirname(state_file), exist_ok=True)
        tmp = state_file + ".tmp"
        with open(tmp, "w", encoding="utf-8") as f:
            json.dump({"path": path, "name": name, "gone_at": time.time()}, f)
        os.replace(tmp, state_file)
    except OSError as err:
        print("could not remember %s: %s" % (name, err), flush=True)


def forget_candidate(state_file=None):
    try:
        os.unlink(state_file or STATE_FILE)
    except FileNotFoundError:
        pass
    except OSError as err:
        print("could not forget the candidate: %s" % err, flush=True)


def load_candidate(state_file=None):
    """(path, name, seconds since it went), or None.

    None for anything that is not a candidate any more: no file, a file that
    cannot be read, older than CANDIDATE_TTL_S, or from the future - a clock
    that was wrong when it was written says nothing about how long ago that
    was.
    """
    try:
        with open(state_file or STATE_FILE, encoding="utf-8") as f:
            data = json.load(f)
        path = str(data["path"])
        name = str(data["name"])
        age = time.time() - float(data["gone_at"])
    except FileNotFoundError:
        return None
    except (OSError, ValueError, KeyError, TypeError) as err:
        print("could not read the remembered candidate: %s" % err,
              flush=True)
        return None
    if not path.startswith("/org/bluez/") or age < 0 or age > CANDIDATE_TTL_S:
        return None
    return path, name, age


def in_a_call(session):
    """Is callaudiod switching the card for a call right now?

    callaudiod is the most fragile thing in this stack - it looks a card up
    once and keeps the index, and a card appearing underneath it mid-call is
    how a call ends up silent in both directions. A headset is not worth that:
    whatever is being dialled here can wait until the call is over.

    Unreadable counts as "in a call": a callaudiod that is there but not
    answering is exactly the state this is meant to stay out of. Not being
    there at all is different and has to be told apart, or a phone without
    callaudiod would never reconnect anything and never say why.
    """
    try:
        mode = session.call_sync(
            "org.mobian_project.CallAudio", "/org/mobian_project/CallAudio",
            "org.freedesktop.DBus.Properties", "Get",
            GLib.Variant("(ss)", ("org.mobian_project.CallAudio",
                                  "AudioMode")),
            GLib.VariantType("(v)"), Gio.DBusCallFlags.NONE, 2000, None,
        ).unpack()[0]
    except GLib.Error as err:
        if (Gio.DBusError.is_remote_error(err)
                and Gio.DBusError.get_remote_error(err)
                == "org.freedesktop.DBus.Error.ServiceUnknown"):
            return False    # no callaudiod, so no call to get in the way
        print("callaudiod did not answer (%s) - not dialling now"
              % err.message, flush=True)
        return True
    return mode != 0


def device_of(path):
    """/org/bluez/hci0/dev_XX/sep1/fd0 -> /org/bluez/hci0/dev_XX, or None."""
    parts = path.split("/")
    if len(parts) < 5 or not parts[4].startswith("dev_"):
        return None
    return "/".join(parts[:5])


def device_prop(system, path, prop):
    """One Device1 property, or None when it cannot be read."""
    try:
        return system.call_sync(
            "org.bluez", path, "org.freedesktop.DBus.Properties", "Get",
            GLib.Variant("(ss)", ("org.bluez.Device1", prop)),
            GLib.VariantType("(v)"), Gio.DBusCallFlags.NONE, 1000, None,
        ).unpack()[0]
    except GLib.Error:
        return None


def has_music_transport(system, dev):
    """Does BlueZ hold a media transport under this device right now?

    None when BlueZ cannot be asked, which the caller reads as "do nothing".
    """
    try:
        objects = system.call_sync(
            "org.bluez", "/", "org.freedesktop.DBus.ObjectManager",
            "GetManagedObjects", None, GLib.VariantType("(a{oa{sa{sv}}})"),
            Gio.DBusCallFlags.NONE, 2000, None,
        ).unpack()[0]
    except GLib.Error as err:
        print("could not ask BlueZ for its objects: %s" % err, flush=True)
        return None
    prefix = dev + "/"
    return any(path.startswith(prefix) and "org.bluez.MediaTransport1" in ifaces
               for path, ifaces in objects.items())


class Candidate:
    """The one device this service may dial, and what is owed to it.

    There is at most one. Two sets of earbuds fighting over the same output
    is not a thing to build on purpose, and the second one to disconnect is
    the one the phone was last using anyway.
    """

    def __init__(self, path, name):
        self.path = path
        self.name = name
        self.attempts_left = len(RETRY_DELAYS_S)
        self.busy = False          # a Connect() is out and unanswered
        self.timer = 0             # the pending GLib timeout, 0 for none
        self.connected = False     # it is on the air right now
        self.connected_at = 0.0    # monotonic, when it last came up
        self.seen_at = GLib.get_monotonic_time() / 1e6

    def cancel_timer(self):
        if self.timer:
            GLib.source_remove(self.timer)
            self.timer = 0


class Reconnector:
    """Holds the bus connections, the candidate, and the occasions.

    The connections are attributes and not locals, and that is not style. A
    subscription made on a connection that Python then frees is collected with
    it: the service stays running, the signal never arrives, and nothing is
    logged - the shape of a bug that cost this project two days in the
    killswitch indicator on 2026-09-14. Keep the connection, keep the signal.
    """

    def __init__(self, system, session, state_file=None):
        self.system = system
        self.session = session
        self.state_file = state_file or STATE_FILE
        self.candidate = None
        self.last_attempt = 0.0    # monotonic, any attempt, any occasion
        # Is the phone in someone's hand? Read from logind at startup and
        # kept current by on_session_props. It decides only one thing: who
        # is likely to have hung up - see on_disconnected.
        self.active = True
        # Music that went missing under a connected headset: the pending look
        # per device, and when the profile was last connected for it.
        self.a2dp_checks = {}
        self.a2dp_last = {}

    # -- dialling ---------------------------------------------------------

    def try_connect(self, why):
        """One attempt, asynchronously. True if one was actually started."""
        cand = self.candidate
        if cand is None or cand.busy:
            return False
        if cand.connected:
            return False    # already on the air; Connect() would only error
        if in_a_call(self.session):
            print("%s: not dialling %s during a call"
                  % (why, cand.name), flush=True)
            return False

        cand.busy = True
        self.last_attempt = GLib.get_monotonic_time() / 1e6
        print("%s: connecting %s" % (why, cand.name), flush=True)
        self.system.call(
            "org.bluez", cand.path, "org.bluez.Device1", "Connect", None,
            None, Gio.DBusCallFlags.NONE, CONNECT_TIMEOUT_MS, None,
            self.on_connect_done, cand,
        )
        return True

    def on_connect_done(self, conn, result, cand):
        cand.busy = False
        try:
            conn.call_finish(result)
        except GLib.Error as err:
            # Every failure mode lands here and they all mean the same thing
            # in practice - the device did not answer the page. Say which,
            # because "Host is down" (switched off or in its case) and
            # "Connection refused" (busy with another phone) are different
            # stories when somebody reads this later.
            print("could not connect %s: %s" % (cand.name, err.message),
                  flush=True)
            return
        # The Connected property arrives as its own signal and does the
        # bookkeeping; nothing to do here but say it worked.
        print("connected %s" % cand.name, flush=True)

    # -- the series after a disconnect ------------------------------------

    def schedule_next(self):
        cand = self.candidate
        if cand is None or cand.attempts_left <= 0:
            return
        delay = RETRY_DELAYS_S[len(RETRY_DELAYS_S) - cand.attempts_left]
        cand.timer = GLib.timeout_add_seconds(delay, self.on_timer)

    def on_timer(self):
        cand = self.candidate
        if cand is None:
            return False
        cand.timer = 0
        cand.attempts_left -= 1
        self.try_connect("retry")
        self.schedule_next()
        return False    # each delay is scheduled once, from the one before

    # -- occasions --------------------------------------------------------

    def on_bluez_props(self, _conn, _sender, path, _iface, _signal, params):
        iface, changed, _invalidated = params.unpack()
        if iface != "org.bluez.Device1":
            return
        connected = changed.get("Connected")
        if connected is True:
            self.on_connected(path)
            self.look_for_music(path)
        elif connected is False:
            self.on_disconnected(path)

    def on_connected(self, path):
        """Something connected. If it is what we were dialling, we are done."""
        cand = self.candidate
        if cand is None or cand.path != path:
            return
        cand.cancel_timer()
        cand.connected = True
        cand.connected_at = GLib.get_monotonic_time() / 1e6
        cand.attempts_left = 0

    def on_disconnected(self, path):
        name = path.rsplit("/", 1)[-1]

        # It came back and then left again straight away: multipoint earbuds
        # handing themselves to something else. Dialling into that is a tug
        # of war, so this one is left until the next time the phone wakes up.
        cand = self.candidate
        if (cand is not None and cand.path == path and cand.connected_at
                and GLib.get_monotonic_time() / 1e6 - cand.connected_at
                < KEPT_S):
            print("%s dropped us again after a moment - leaving it to settle"
                  % name, flush=True)
            cand.cancel_timer()
            cand.attempts_left = 0
            cand.connected = False
            cand.connected_at = 0.0
            return

        if not carries_audio(self.system, path):
            return
        if not is_trusted(self.system, path):
            print("%s disconnected, but it is not trusted - leaving it alone"
                  % name, flush=True)
            return
        if not is_headphones(self.system, path):
            print("%s disconnected, but it is not headphones - leaving it "
                  "to call back itself" % name, flush=True)
            return

        if cand is not None:
            cand.cancel_timer()
        self.candidate = Candidate(path, name)
        save_candidate(path, name, self.state_file)

        # Who hung up? There is no way to ask - BlueZ does not pass the
        # disconnect reason to D-Bus - but there is a good proxy. If the phone
        # was in your hand when it happened, it was probably you, in the
        # settings, and dialling straight back would be this service arguing
        # with its owner. If the phone was idle or locked, nobody here did
        # anything, and the earbuds went flat or went into their case.
        #
        # Either way the device is remembered, so waking up will still try.
        if self.active:
            print("%s disconnected while the phone was in use - remembering "
                  "it, but not dialling back" % name, flush=True)
            return

        print("%s disconnected" % name, flush=True)
        self.schedule_next()

    def on_removed(self, _conn, _sender, _path, _iface, _signal, params):
        """The device was unpaired or forgotten: forget it here too.

        Only when Device1 itself goes. Other interfaces live on the same path
        and come and go with the programs that provide them - WirePlumber's
        battery report among them - and reading their removal as the device
        leaving made this say "gone from BlueZ" at every WirePlumber restart
        while the headset was still connected.
        """
        path, ifaces = params.unpack()
        if "org.bluez.MediaTransport1" in ifaces:
            self.on_music_gone(path)
        if "org.bluez.Device1" not in ifaces:
            return
        cand = self.candidate
        if cand is not None and cand.path == path:
            cand.cancel_timer()
            self.candidate = None
            forget_candidate(self.state_file)
            print("%s is gone from BlueZ - nothing to reconnect"
                  % cand.name, flush=True)

    # -- music on a headset that stayed connected -------------------------

    def on_music_gone(self, transport):
        """A music stream closed. Look again in a moment - see A2DP_CHECK_S."""
        dev = device_of(transport)
        if dev is not None:
            self.look_for_music(dev)

    def look_for_music(self, dev):
        """Check in A2DP_CHECK_S that this device has a music transport.

        Also on every connect, not only when a stream closes: on 2026-09-29
        the earbuds came back after a reboot with AVRCP alone, no A2DP, no
        transport, and nothing ever closed - music stayed on the speaker until
        ConnectProfile by hand. check_music leaves anything alone that is not
        a trusted A2DP sink, so a car kit or a keyboard connecting costs one
        property read.
        """
        if dev in self.a2dp_checks:
            return
        self.a2dp_checks[dev] = GLib.timeout_add_seconds(
            A2DP_CHECK_S, lambda: self.check_music(dev))

    def check_music(self, dev):
        self.a2dp_checks.pop(dev, None)
        name = dev.rsplit("/", 1)[-1]
        if device_prop(self.system, dev, "Connected") is not True:
            return False    # it left; the series after a disconnect has it
        uuids = device_prop(self.system, dev, "UUIDs") or []
        if A2DP_SINK_UUID not in [str(u).lower() for u in uuids]:
            return False    # a car kit on hands-free only, say
        if device_prop(self.system, dev, "Trusted") is not True:
            return False
        if has_music_transport(self.system, dev) is not False:
            return False    # back by itself, or BlueZ could not be asked
        now = GLib.get_monotonic_time() / 1e6
        last = self.a2dp_last.get(dev)
        if last is not None and now - last < A2DP_MIN_GAP_S:
            print("%s lost its music again - leaving it this time" % name,
                  flush=True)
            return False
        if in_a_call(self.session):
            # A call is on hands-free; music can wait until it is over, and
            # the next transport that goes away will ask again.
            print("%s has no music, but a call is up - not now" % name,
                  flush=True)
            return False
        self.a2dp_last[dev] = now
        print("%s is connected without music - connecting A2DP" % name,
              flush=True)
        self.system.call(
            "org.bluez", dev, "org.bluez.Device1", "ConnectProfile",
            GLib.Variant("(s)", (A2DP_SINK_UUID,)), None,
            Gio.DBusCallFlags.NONE, CONNECT_TIMEOUT_MS, None,
            self.on_music_done, dev,
        )
        return False

    def on_music_done(self, conn, result, dev):
        name = dev.rsplit("/", 1)[-1]
        try:
            conn.call_finish(result)
        except GLib.Error as err:
            print("could not connect A2DP on %s: %s" % (name, err.message),
                  flush=True)
            return
        # BlueZ accepting the profile is not music yet: on 2026-09-28 this
        # said "A2DP back" and the sound still came from the phone's speaker.
        # Only a media transport is something PipeWire can play to.
        GLib.timeout_add_seconds(A2DP_CHECK_S,
                                 lambda: self.confirm_music(dev))

    def confirm_music(self, dev):
        name = dev.rsplit("/", 1)[-1]
        if has_music_transport(self.system, dev):
            print("A2DP back on %s" % name, flush=True)
        else:
            print("A2DP connected on %s, but no music transport after %d s"
                  % (name, A2DP_CHECK_S), flush=True)
        return False

    def on_session_props(self, _conn, _sender, _path, _iface, _signal,
                         params):
        """logind: the phone went idle or locked, or came back.

        Both keys are watched because both are real and they do not arrive
        together - IdleHint comes first, when the screen goes off, LockedHint
        only when the lock actually takes. Measured 2026-09-14.
        """
        _iface_name, changed, _invalidated = params.unpack()
        hints = [changed[k] for k in ("IdleHint", "LockedHint")
                 if k in changed]
        if not hints:
            return
        was_active = self.active
        self.active = not any(hints)
        if self.active and not was_active:
            self.on_wakeup()

    def on_wakeup(self):
        """The phone is back in someone's hand. One attempt, if one is owed.

        Rate-limited, and that limit is the whole reason this is safe to leave
        running. A phone is unlocked dozens of times a day, and IdleHint goes
        false for reasons that have nothing to do with anyone touching it -
        measured on this phone the first time the service ran. Without the
        gap, this occasion would be a poller with extra steps.
        """
        self.occasion("phone back in use", WAKE_MIN_GAP_S)

    def on_display(self, _conn, _sender, _path, _iface, _signal, params):
        """MCE: the display was switched on, dimmed or off.

        Only "on" is an occasion. The rate limit is the one for waking up,
        because it is the same event seen earlier: the display comes on, and
        a moment later logind may say the session is no longer idle - the gap
        makes that one attempt and not two.
        """
        try:
            state = params.unpack()[0]
        except (TypeError, IndexError, AttributeError):
            return
        if state == "on":
            self.occasion("display on", WAKE_MIN_GAP_S)

    def on_player_props(self, _conn, _sender, _path, _iface, _signal,
                        params):
        """MPRIS: a media player started playing."""
        try:
            iface, changed, _invalidated = params.unpack()
        except (TypeError, ValueError, AttributeError):
            return
        if iface != "org.mpris.MediaPlayer2.Player":
            return
        if changed.get("PlaybackStatus") == "Playing":
            self.occasion("music started", MUSIC_MIN_GAP_S)

    def occasion(self, why, min_gap):
        """One attempt for the candidate, if one is owed and not too soon."""
        cand = self.candidate
        if cand is None:
            return
        now = GLib.get_monotonic_time() / 1e6
        if now - cand.seen_at > CANDIDATE_TTL_S:
            print("%s has been gone for a day - not dialling it any more"
                  % cand.name, flush=True)
            cand.cancel_timer()
            self.candidate = None
            forget_candidate(self.state_file)
            return
        if cand.connected or cand.busy:
            return    # nothing to do, and not worth spending the gap on
        if self.last_attempt and now - self.last_attempt < min_gap:
            return
        cand.cancel_timer()
        cand.attempts_left = 0     # the series, if any, is over
        self.try_connect(why)

    def restore(self, tries_left=RESTORE_TRIES):
        """Take over the candidate remembered before a restart, if any.

        Checked again against BlueZ, because a day is long enough to unpair
        something. A device that is connected right now is not taken over:
        its next disconnect makes it a candidate the ordinary way. No attempt
        is made here - BlueZ dials paired devices itself when the adapter
        powers on, and the occasions take it from there.

        At boot this service can be up before bluetoothd, and a device BlueZ
        cannot be asked about is not a device that was unpaired. So that case
        asks again, RESTORE_TRIES times RESTORE_RETRY_S apart, and keeps the
        file whatever happens; only BlueZ answering "no such device" drops it.
        """
        remembered = load_candidate(self.state_file)
        if remembered is None:
            forget_candidate(self.state_file)
            return False
        path, name, age = remembered
        if not bluez_answers(self.system):
            if tries_left > 1:
                GLib.timeout_add_seconds(
                    RESTORE_RETRY_S, lambda: self.restore(tries_left - 1))
            else:
                print("BlueZ is not answering - %s is not taken over this "
                      "time" % name, flush=True)
            return False
        if self.candidate is not None:
            return False    # something disconnected meanwhile; that one wins
        connected = device_prop(self.system, path, "Connected")
        if connected is None:
            print("%s, remembered from before, is gone from BlueZ" % name,
                  flush=True)
            forget_candidate(self.state_file)
            return False
        if connected:
            return False
        if not (carries_audio(self.system, path)
                and is_trusted(self.system, path)
                and is_headphones(self.system, path)):
            forget_candidate(self.state_file)
            return False
        cand = Candidate(path, name)
        cand.attempts_left = 0     # the series belonged to the last run
        cand.seen_at -= age
        self.candidate = cand
        print("remembered %s, gone for %d min" % (name, age // 60),
              flush=True)
        return False    # also ends the retry timer this may run from


def session_path(system):
    """This user's logind session object, or None if it cannot be had.

    Without it there is no waking-up occasion and only the series after a
    disconnect survives - worth saying out loud rather than failing, because
    the service is still useful with one occasion instead of two.
    """
    try:
        return system.call_sync(
            "org.freedesktop.login1", "/org/freedesktop/login1",
            "org.freedesktop.login1.Manager", "GetSession",
            GLib.Variant("(s)", ("auto",)), GLib.VariantType("(o)"),
            Gio.DBusCallFlags.NONE, 2000, None,
        ).unpack()[0]
    except GLib.Error as err:
        print("no logind session (%s) - waking the phone will not "
              "reconnect anything" % err.message, flush=True)
        return None


def session_in_use(system, path):
    """Is the phone being used right now, per logind?

    Read once at startup, because the signals only ever say what CHANGED. A
    service that starts while the screen is off and assumes otherwise sees the
    next unlock as no change at all, and the waking-up occasion goes missing
    until the screen has gone off once more - which on a phone that is put
    down and picked up all day is a long time to be wrong.
    """
    def hint(key):
        try:
            return bool(system.call_sync(
                "org.freedesktop.login1", path,
                "org.freedesktop.DBus.Properties", "Get",
                GLib.Variant("(ss)", ("org.freedesktop.login1.Session", key)),
                GLib.VariantType("(v)"), Gio.DBusCallFlags.NONE, 2000, None,
            ).unpack()[0])
        except GLib.Error:
            return False
    return not (hint("IdleHint") or hint("LockedHint"))


def main():
    system = Gio.bus_get_sync(Gio.BusType.SYSTEM, None)
    session = Gio.bus_get_sync(Gio.BusType.SESSION, None)
    rc = Reconnector(system, session)

    system.signal_subscribe(
        "org.bluez", "org.freedesktop.DBus.Properties", "PropertiesChanged",
        None, None, Gio.DBusSignalFlags.NONE, rc.on_bluez_props,
    )
    system.signal_subscribe(
        "org.bluez", "org.freedesktop.DBus.ObjectManager",
        "InterfacesRemoved", None, None, Gio.DBusSignalFlags.NONE,
        rc.on_removed,
    )
    path = session_path(system)
    if path is not None:
        rc.active = session_in_use(system, path)
        system.signal_subscribe(
            "org.freedesktop.login1", "org.freedesktop.DBus.Properties",
            "PropertiesChanged", path, None, Gio.DBusSignalFlags.NONE,
            rc.on_session_props,
        )
    system.signal_subscribe(
        MCE_SERVICE, MCE_SIGNAL_IFACE, "display_status_ind", MCE_SIGNAL_PATH,
        None, Gio.DBusSignalFlags.NONE, rc.on_display,
    )
    session.signal_subscribe(
        None, "org.freedesktop.DBus.Properties", "PropertiesChanged",
        "/org/mpris/MediaPlayer2", "org.mpris.MediaPlayer2.Player",
        Gio.DBusSignalFlags.NONE, rc.on_player_props,
    )
    rc.restore()

    print("watching for a Bluetooth audio device to dial back", flush=True)
    GLib.MainLoop().run()


if __name__ == "__main__":
    main()
