#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-2.0-only
# Bananarchy Bluetooth OBEX Object Push (OPP) Server & Client

import os
import sys
import time
import fcntl
import select
import struct
import socket
import signal
import subprocess
import threading

sys.dont_write_bytecode = True

OPP_UUID = "00001105-0000-1000-8000-00805f9b34fb"
RX_STATUS_FILE = "/tmp/bananarchy_bt_rx.status"
TX_STATUS_FILE = "/tmp/bananarchy_bt_tx.status"
PID_FILE = "/tmp/bananarchy_bt_obex.pid"
DURESS_FLAG = "/tmp/bananarchy_duress_mode"
OBEX_CFG_FILE = "/home/user/.config/sxmo/bt_obex_dir"
OBEX_IPC_DIR = "/run/bananarchy/bt-obex"
OBEX_PROMPT_FILE = "/run/bananarchy/bt-obex/prompt.tsv"
OBEX_DECISION_FILE = "/run/bananarchy/bt-obex/decision.tsv"
PAIR_PROMPT_FILE = "/run/bananarchy/bt-obex/pair_prompt.tsv"
PAIR_DECISION_FILE = "/run/bananarchy/bt-obex/pair_decision.tsv"
OP_DONE_FILE = "/run/bananarchy/bt-obex/op_done.tsv"
AGENT_READY_FILE = "/run/bananarchy/bt-obex/agent_ready"
BT_STATE_FILE = "/run/bananarchy/bt-obex/bt_state.tsv"
CTRL_READY_FILE = "/run/bananarchy/bt-obex/ctrl_ready"
EPHEMERAL_DEV_PROPS = frozenset((
  "RSSI",
  "TxPower",
  "ManufacturerData",
  "ServiceData",
  "AdvertisingData",
  "AdvertisingFlags",
))
OBEX_PROMPT_LOCK = threading.Lock()
PAIR_PROMPT_LOCK = threading.Lock()
PAIR_CANCEL_EVENT = threading.Event()
DBUS_SEND_LOCK = threading.Lock()


def is_duress_mode():
  return os.path.exists(DURESS_FLAG)


def shorten_obex_dir(path):
  if not path:
    return "~/Downloads"
  if path == "/home/user":
    return "~"
  if path.startswith("/home/user/"):
    return "~/" + path[len("/home/user/"):]
  return path


def sanitize_obex_target_dir(raw_dir):
  duress_base = "/tmp/duress_home"
  default_dir = os.path.join(duress_base, "Downloads") if is_duress_mode() else "/home/user/Downloads"
  cand = str(raw_dir or "").strip()
  if not cand or "\n" in cand or "\r" in cand or "\t" in cand:
    cand = default_dir
  if not cand.startswith("/"):
    cand = default_dir
  norm = os.path.normpath(cand)
  if is_duress_mode():
    if norm != duress_base and not norm.startswith(duress_base + "/"):
      norm = default_dir
  os.makedirs(norm, exist_ok=True)
  if norm.startswith("/home/user") or norm.startswith(duress_base):
    try:
      os.chown(norm, 10000, 10000)
    except OSError:
      pass
  return norm


def get_configured_obex_dir():
  raw = ""
  if not is_duress_mode() and os.path.exists(OBEX_CFG_FILE):
    try:
      with open(OBEX_CFG_FILE, "r", encoding="utf-8") as cf:
        raw = cf.readline().strip()
    except OSError:
      raw = ""
  return sanitize_obex_target_dir(raw)


def get_downloads_dir():
  return get_configured_obex_dir()


def ensure_obex_ipc_dir():
  parent = os.path.dirname(OBEX_IPC_DIR)
  if parent:
    try:
      os.makedirs(parent, mode=0o755, exist_ok=True)
      os.chmod(parent, 0o755)
    except OSError:
      pass
  os.makedirs(OBEX_IPC_DIR, mode=0o755, exist_ok=True)
  try:
    os.chmod(OBEX_IPC_DIR, 0o755)
    os.chown(OBEX_IPC_DIR, 10000, 10000)
  except OSError:
    pass


def _atomic_write_text(path, content):
  tmp = f"{path}.{os.getpid()}.tmp"
  try:
    with open(tmp, "w", encoding="utf-8") as f:
      f.write(content)
    os.chmod(tmp, 0o644)
    try:
      os.chown(tmp, 10000, 10000)
    except OSError:
      pass
    try:
      os.replace(tmp, path)
    except PermissionError:
      try:
        os.unlink(path)
      except OSError:
        pass
      os.replace(tmp, path)
  except OSError:
    try:
      if os.path.exists(tmp):
        os.unlink(tmp)
    except OSError:
      pass


def write_status(path, text):
  _atomic_write_text(path, text.strip() + "\n")


def write_multiline_atomic(path, content):
  text = content if content.endswith("\n") else (content + "\n")
  _atomic_write_text(path, text)


def notify_networks_ui(msg="REFRESH_BT\n"):
  fifo = "/tmp/dwm_plugin_networks.fifo"
  if os.path.exists(fifo):
    try:
      fd = os.open(fifo, os.O_WRONLY | os.O_NONBLOCK)
      os.write(fd, msg.encode("utf-8"))
      os.close(fd)
      return True
    except OSError:
      pass
  return False


def wake_and_alert_ui(fifo_cmd, fallback_arg):
  if os.environ.get("BANANARCHY_OBEX_NO_UI") == "1":
    notify_networks_ui(fifo_cmd)
    return
  try:
    if os.path.exists("/usr/bin/bananarchy-lid-gate.sh"):
      subprocess.Popen(
        ["/usr/bin/bananarchy-lid-gate.sh", "wake"],
        stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
      )
  except Exception:
    pass
  if not os.path.exists("/home/user/.config/sxmo/.novibrate"):
    try:
      if os.geteuid() == 0:
        subprocess.Popen(
          ["su", "-", "user", "-c", "sxmo_vibrate 180"],
          stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
        )
      else:
        subprocess.Popen(
          ["sxmo_vibrate", "180"],
          stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
        )
    except Exception:
      pass
  if not notify_networks_ui(fifo_cmd):
    try:
      if os.geteuid() == 0:
        subprocess.Popen(
          ["su", "-", "user", "-c",
           f"DISPLAY=:0 /usr/bin/dwm-plugin networks {fallback_arg}"],
          stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
        )
      else:
        subprocess.Popen(
          ["/usr/bin/dwm-plugin", "networks", fallback_arg],
          stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
        )
    except Exception:
      pass


def notify_user(title, body):
  try:
    bus_addr = "unix:path=/run/user/10000/bus"
    if os.path.exists("/run/user/10000/dbus.bus"):
      try:
        with open("/run/user/10000/dbus.bus", "r", encoding="utf-8") as bf:
          line = bf.readline().strip()
          if line:
            bus_addr = line
      except OSError:
        pass
    if os.geteuid() == 0:
      subprocess.Popen([
        "su", "-", "user", "-c",
        f"DISPLAY=:0 DBUS_SESSION_BUS_ADDRESS={subprocess.list2cmdline([bus_addr])} notify-send {subprocess.list2cmdline([title, body])}"
      ], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    else:
      env = os.environ.copy()
      env.setdefault("DISPLAY", ":0")
      env.setdefault("DBUS_SESSION_BUS_ADDRESS", bus_addr)
      subprocess.Popen(["notify-send", title, body],
                       env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
  except Exception:
    pass


def format_size(num_bytes):
  if num_bytes >= 1024 * 1024:
    return f"{num_bytes / (1024.0 * 1024.0):.1f} MB"
  if num_bytes >= 1024:
    return f"{num_bytes / 1024.0:.1f} KB"
  return f"{num_bytes} B"


def safe_filename(raw_name):
  name = os.path.basename(raw_name.replace("\\", "/")).strip()
  clean = "".join(c if (c.isalnum() or c in "._- ()[]") else "_" for c in name)
  if not clean or clean in (".", ".."):
    clean = f"bt_file_{int(time.time())}.bin"
  return clean


def unique_dest_path(directory, filename):
  cand = os.path.join(directory, filename)
  if not os.path.exists(cand):
    return cand
  stem, ext = os.path.splitext(filename)
  idx = 1
  while True:
    cand = os.path.join(directory, f"{stem}_{idx}{ext}")
    if not os.path.exists(cand):
      return cand
    idx += 1


class ObexPacketReader:
  """Read OBEX PDUs safely over both RFCOMM SOCK_STREAM and L2CAP SOCK_SEQPACKET."""

  def __init__(self, sock):
    self.sock = sock
    self.buf = bytearray()
    seq_val = getattr(socket, "SOCK_SEQPACKET", 5)
    stype = getattr(sock, "type", socket.SOCK_STREAM)
    try:
      stype = sock.getsockopt(socket.SOL_SOCKET, socket.SO_TYPE)
    except Exception:
      pass
    self.is_seqpacket = (stype == seq_val)

  def _recv_exact_stream(self, n):
    while len(self.buf) < n:
      chunk = self.sock.recv(max(4096, n - len(self.buf)))
      if not chunk:
        return None
      self.buf.extend(chunk)
    out = bytes(self.buf[:n])
    del self.buf[:n]
    return out

  def recv_packet(self):
    if self.is_seqpacket and not self.buf:
      dat = self.sock.recv(65536)
      if not dat or len(dat) < 3:
        return None, None
      opcode = dat[0]
      pkt_len = struct.unpack(">H", dat[1:3])[0]
      if pkt_len < 3:
        return opcode, b""
      if pkt_len <= len(dat):
        return opcode, bytes(dat[3:pkt_len])
      self.buf.extend(dat)
      hdr = self._recv_exact_stream(3)
      if not hdr:
        return None, None
      payload = self._recv_exact_stream(pkt_len - 3)
      if payload is None:
        return None, None
      return opcode, payload

    hdr = self._recv_exact_stream(3)
    if not hdr:
      return None, None
    opcode = hdr[0]
    pkt_len = struct.unpack(">H", hdr[1:3])[0]
    if pkt_len < 3:
      return opcode, b""
    payload = self._recv_exact_stream(pkt_len - 3)
    if payload is None:
      return None, None
    return opcode, payload


def recv_obex_packet(sock_or_reader):
  if isinstance(sock_or_reader, ObexPacketReader):
    return sock_or_reader.recv_packet()
  return ObexPacketReader(sock_or_reader).recv_packet()


def _sock_peer_aborted(sock):
  try:
    rlist, _, _ = select.select([sock], [], [], 0.0)
    if sock in rlist:
      peek = sock.recv(1, socket.MSG_PEEK)
      if not peek or peek[0] in (0xFF, 0x7F):
        return True
  except BlockingIOError:
    return False
  except OSError:
    return True
  return False


def request_user_obex_confirmation(sock, sender_name, sender_mac, file_name,
                                   total_len, default_dir, timeout_sec=55.0):
  with OBEX_PROMPT_LOCK:
    ensure_obex_ipc_dir()
    for p in (OBEX_PROMPT_FILE, OBEX_DECISION_FILE):
      try:
        if os.path.exists(p):
          os.unlink(p)
      except OSError:
        pass

    req_id = f"{os.getpid()}_{int(time.monotonic() * 1000)}"
    s_label = str(sender_name or sender_mac or "Bluetooth Device").replace("\t", " ").replace("\n", " ").strip()
    s_mac = str(sender_mac or "").replace("\t", " ").replace("\n", " ").strip()
    f_label = str(file_name or "file.bin").replace("\t", " ").replace("\n", " ").strip()
    d_label = sanitize_obex_target_dir(default_dir).replace("\t", " ").replace("\n", " ").strip()

    tmp_prompt = OBEX_PROMPT_FILE + ".tmp"
    with open(tmp_prompt, "w", encoding="utf-8") as pf:
      pf.write(f"{req_id}\t{s_label}\t{s_mac}\t{f_label}\t{int(total_len or 0)}\t{d_label}\n")
    try:
      os.chmod(tmp_prompt, 0o644)
      os.chown(tmp_prompt, 10000, 10000)
    except OSError:
      pass
    os.replace(tmp_prompt, OBEX_PROMPT_FILE)

    sz_label = format_size(total_len) if total_len and total_len > 0 else "Unknown size"
    write_status(RX_STATUS_FILE, f"PENDING\t{f_label}\t{s_label}\t{sz_label}")

    wake_and_alert_ui(f"OBEX_PROMPT {req_id}\n", "obex-prompt")

    deadline = time.monotonic() + timeout_sec
    try:
      while time.monotonic() < deadline:
        if os.path.exists(OBEX_DECISION_FILE):
          try:
            with open(OBEX_DECISION_FILE, "r", encoding="utf-8", errors="replace") as df:
              line = df.readline().strip()
            parts = line.split("\t")
            if len(parts) >= 2 and parts[0] == req_id:
              accepted = (parts[1].strip().upper() == "ACCEPT")
              chosen = parts[2].strip() if len(parts) >= 3 and parts[2].strip() else d_label
              return accepted, sanitize_obex_target_dir(chosen), False
          except OSError:
            pass
        if sock is not None and _sock_peer_aborted(sock):
          return False, sanitize_obex_target_dir(d_label), True
        time.sleep(0.1)
      return False, sanitize_obex_target_dir(d_label), False
    finally:
      for p in (OBEX_PROMPT_FILE, OBEX_DECISION_FILE):
        try:
          if os.path.exists(p):
            os.unlink(p)
        except OSError:
          pass
      notify_networks_ui()


def handle_obex_rx_session(sock, sender_name="Bluetooth Device", sender_mac=""):
  sock.settimeout(65.0)
  reader = ObexPacketReader(sock)
  out_file = None
  out_path = None
  file_name = ""
  total_len = 0
  rx_bytes = 0
  last_ui_notify = 0.0
  awaiting_decision = True
  target_dir = get_configured_obex_dir()

  def reset_rx_file_state():
    nonlocal out_file, out_path, file_name, total_len, rx_bytes, awaiting_decision, target_dir
    if out_file:
      try:
        out_file.close()
      except Exception:
        pass
      out_file = None
    out_path = None
    file_name = ""
    total_len = 0
    rx_bytes = 0
    awaiting_decision = True
    target_dir = get_configured_obex_dir()

  try:
    while True:
      opcode, payload = recv_obex_packet(reader)
      if opcode is None:
        break

      op_base = opcode & 0x7F
      is_final = (opcode & 0x80) != 0

      if opcode == 0x80:  # CONNECT
        # OBEX CONNECT response: 0xA0 (OK), len 7, ver 0x10, flags 0, max_pkt 0x8000
        resp = struct.pack(">BHBBH", 0xA0, 7, 0x10, 0x00, 0x8000)
        sock.sendall(resp)

      elif opcode == 0x81:  # DISCONNECT
        sock.sendall(struct.pack(">BH", 0xA0, 3))
        break

      elif opcode in (0xFF, 0x7F):  # ABORT
        stale_path = out_path
        reset_rx_file_state()
        if stale_path and os.path.exists(stale_path):
          try:
            os.unlink(stale_path)
          except OSError:
            pass
        write_status(RX_STATUS_FILE, f"IDLE\tReady ({shorten_obex_dir(get_configured_obex_dir())})")
        notify_networks_ui()
        sock.sendall(struct.pack(">BH", 0xA0, 3))
        break

      elif op_base == 0x02:  # PUT / PUT-Final
        pos = 0
        plen = len(payload)
        body_chunks = []

        while pos < plen:
          hi = payload[pos]
          pos += 1
          h_encoding = hi & 0xC0

          if h_encoding in (0x00, 0x40):  # 2-byte length prefixed
            if pos + 2 > plen:
              break
            hlen = struct.unpack(">H", payload[pos:pos + 2])[0]
            if hlen < 3 or pos + hlen - 1 > plen:
              break
            hdata = payload[pos + 2:pos + hlen - 1]
            pos += hlen - 1

            if hi == 0x01:  # Name (UTF-16BE)
              try:
                decoded = hdata.decode("utf-16-be", errors="replace").rstrip("\x00")
              except Exception:
                decoded = "received_file"
              file_name = safe_filename(decoded)
            elif hi in (0x48, 0x49):  # Body / End-of-Body
              body_chunks.append(hdata)

          elif h_encoding == 0x80:  # 1-byte value
            pos += 1

          elif h_encoding == 0xC0:  # 4-byte value
            if pos + 4 > plen:
              break
            val = struct.unpack(">I", payload[pos:pos + 4])[0]
            pos += 4
            if hi == 0xC3:  # Length
              total_len = val

        if awaiting_decision and is_final and not body_chunks and not file_name and total_len == 0:
          sock.sendall(struct.pack(">BH", 0xC3, 3))  # Disallow empty Delete PUT
          reset_rx_file_state()
          continue

        if awaiting_decision:
          if not file_name:
            file_name = f"bt_rx_{int(time.time())}.bin"
          accepted, chosen_dir, remote_aborted = request_user_obex_confirmation(
            sock, sender_name, sender_mac, file_name, total_len, get_configured_obex_dir()
          )
          if remote_aborted:
            write_status(RX_STATUS_FILE, f"IDLE\tReady ({shorten_obex_dir(get_configured_obex_dir())})")
            notify_networks_ui()
            reset_rx_file_state()
            continue
          if not accepted:
            write_status(
              RX_STATUS_FILE,
              f"IDLE\tRejected {file_name} ({shorten_obex_dir(get_configured_obex_dir())})"
            )
            notify_networks_ui()
            sock.sendall(struct.pack(">BH", 0xC3, 3))  # Forbidden (Rejected)
            reset_rx_file_state()
            continue
          awaiting_decision = False
          target_dir = chosen_dir
          sock.settimeout(30.0)

        if out_file is None:
          if not file_name:
            file_name = f"bt_rx_{int(time.time())}.bin"
          out_path = unique_dest_path(target_dir, file_name)
          out_file = open(out_path, "wb")
          try:
            os.chown(out_path, 10000, 10000)
          except OSError:
            pass

        for chunk in body_chunks:
          if out_file:
            out_file.write(chunk)
            rx_bytes += len(chunk)

        now = time.time()
        if not is_final:
          if now - last_ui_notify >= 0.4 or rx_bytes == 0:
            pct = int((rx_bytes * 100) // total_len) if total_len > 0 else 0
            write_status(
              RX_STATUS_FILE,
              f"RECEIVING\t{file_name or '...'}\t{rx_bytes}\t{total_len}\t{pct}%"
            )
            notify_networks_ui()
            last_ui_notify = now
          sock.sendall(struct.pack(">BH", 0x90, 3))  # Continue
        else:
          saved_base = os.path.basename(out_path)
          saved_full = out_path
          saved_dir_short = shorten_obex_dir(target_dir)
          out_file.flush()
          out_file.close()
          out_file = None
          try:
            os.chown(saved_full, 10000, 10000)
            os.chmod(saved_full, 0o644)
          except OSError:
            pass
          sz_str = format_size(rx_bytes)
          write_status(
            RX_STATUS_FILE,
            f"RECEIVED\t{saved_base}\t{sz_str}\t{saved_full}"
          )
          notify_networks_ui()
          notify_user("Bluetooth File Received",
                      f"{saved_base} ({sz_str}) saved to {saved_dir_short}")
          sock.sendall(struct.pack(">BH", 0xA0, 3))  # Success
          reset_rx_file_state()

      elif op_base == 0x05:  # SETPATH
        sock.sendall(struct.pack(">BH", 0xA0, 3))

      else:
        sock.sendall(struct.pack(">BH", 0xD1, 3))  # Not Implemented
  except Exception:
    stale_path = out_path
    reset_rx_file_state()
    if stale_path and os.path.exists(stale_path):
      try:
        os.unlink(stale_path)
      except OSError:
        pass
  finally:
    if out_file:
      try:
        out_file.close()
      except Exception:
        pass
    try:
      sock.close()
    except Exception:
      pass


def open_input_inotify_fd():
  try:
    import ctypes
    libc = ctypes.CDLL(None, use_errno=True)
    libc.inotify_init.argtypes = []
    libc.inotify_init.restype = ctypes.c_int
    libc.inotify_add_watch.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.c_uint32]
    libc.inotify_add_watch.restype = ctypes.c_int
    fd = libc.inotify_init()
    if fd < 0:
      return -1
    os.set_inheritable(fd, False)
    os.set_blocking(fd, False)
    # IN_ATTRIB (0x04) | IN_MOVED_TO (0x80) | IN_CREATE (0x100) | IN_DELETE (0x200)
    if libc.inotify_add_watch(fd, b"/dev/input", 0x00000384) < 0:
      os.close(fd)
      return -1
    return fd
  except Exception:
    return -1


CLASSIC_AUDIO_UUID_PREFIXES = (
  "00001108-",  # Headset (HSP)
  "0000110b-",  # Audio Sink (A2DP)
  "0000111e-",  # Handsfree (HFP)
)


def is_phone_or_computer_props(props):
  if not isinstance(props, dict):
    return False
  icon = str(props.get("Icon") or "").strip().lower()
  if icon.startswith("phone") or icon.startswith("computer"):
    return True
  cod = props.get("Class")
  if isinstance(cod, int) and (cod & 0x1F00) in (0x0100, 0x0200):
    return True
  return False


def is_hog_device_props(props):
  if not isinstance(props, dict):
    return False
  uuids = [str(v).lower() for v in (props.get("UUIDs") or [])]
  return any(u.startswith("00001812-") for u in uuids)


def is_classic_audio_props(props):
  if not isinstance(props, dict) or is_hog_device_props(props) or is_phone_or_computer_props(props):
    return False
  uuids = [str(v).lower() for v in (props.get("UUIDs") or [])]
  if any(any(u.startswith(p) for p in CLASSIC_AUDIO_UUID_PREFIXES) for u in uuids):
    return True
  icon = str(props.get("Icon") or "").strip().lower()
  if icon.startswith("audio-"):
    return True
  cod = props.get("Class")
  if isinstance(cod, int) and (cod & 0x1F00) == 0x0400:
    return True
  return False


def avrcp_fifo_command_for_key(code):
  mapping = {
    164: "PLAYPAUSE",    # KEY_PLAYPAUSE
    200: "PLAY",         # KEY_PLAYCD
    207: "PLAY",         # KEY_PLAY
    201: "PAUSE",        # KEY_PAUSECD
    119: "PAUSE",        # KEY_PAUSE
    166: "STOP",         # KEY_STOPCD
    128: "STOP",         # KEY_STOP
    163: "NEXT",         # KEY_NEXTSONG
    165: "PREV",         # KEY_PREVIOUSSONG
  }
  return mapping.get(code)


def dispatch_avrcp_key(code):
  cmd = avrcp_fifo_command_for_key(code)
  if not cmd:
    return False
  if cmd != "PAUSE" and (
    os.path.exists("/tmp/sxmo_in_call") or
    os.path.exists("/tmp/sxmo_call_ringing")
  ):
    return False
  fifo = "/tmp/dwm_plugin_music.fifo"
  if os.path.exists(fifo):
    try:
      fd = os.open(fifo, os.O_WRONLY | os.O_NONBLOCK)
      os.write(fd, (cmd + "\n").encode("ascii"))
      os.close(fd)
      return True
    except OSError:
      pass
  if cmd == "PAUSE":
    try:
      env = os.environ.copy()
      env.setdefault("XDG_RUNTIME_DIR", "/run/user/10000")
      subprocess.Popen(["sxmo_playerctl.sh", "pause_all"],
                       env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    except Exception:
      pass
  return True


def run_gamepad_uinput_bridge(is_running, wake_r=-1):
  ev_fmt = "llHHi"
  ev_size = struct.calcsize(ev_fmt)
  ui_set_evbit = 0x40045564
  ui_set_keybit = 0x40045565
  ui_dev_create = 0x5501
  ui_dev_destroy = 0x5502
  eviocgbit_key = (2 << 30) | (96 << 16) | (0x45 << 8) | (0x20 + 0x01)

  # Map Linux gamepad button codes to Bananarchy keypad/navigation keys:
  # South(A)=Enter(OK), East(B)=8(GB B), West(X)=5(Fire/Turbo B), North(Y)=6(Turbo A)
  # Start=2(GB Start), Select=3(GB Select), L1=F1(LSK), R1=F2(RSK), L2=*, R2=0, Mode=Esc
  btn_map = {
    0x130: 28,   # BTN_SOUTH (A) -> KEY_ENTER
    0x131: 9,    # BTN_EAST (B) -> KEY_8
    0x132: 8,    # BTN_C -> KEY_7
    0x133: 6,    # BTN_WEST (X) -> KEY_5
    0x134: 7,    # BTN_NORTH (Y) -> KEY_6
    0x135: 10,   # BTN_Z -> KEY_9
    0x136: 59,   # BTN_TL (L1) -> KEY_F1 (Left Softkey)
    0x137: 60,   # BTN_TR (R1) -> KEY_F2 (Right Softkey)
    0x138: 55,   # BTN_TL2 (L2) -> KEY_KPASTERISK (*)
    0x139: 11,   # BTN_TR2 (R2) -> KEY_0
    0x13a: 4,    # BTN_SELECT -> KEY_3
    0x13b: 3,    # BTN_START -> KEY_2
    0x13c: 1,    # BTN_MODE -> KEY_ESC
    0x120: 28,   # BTN_TRIGGER -> KEY_ENTER
    0x121: 9,    # BTN_THUMB -> KEY_8
    0x220: 103,  # BTN_DPAD_UP -> KEY_UP
    0x221: 108,  # BTN_DPAD_DOWN -> KEY_DOWN
    0x222: 105,  # BTN_DPAD_LEFT -> KEY_LEFT
    0x223: 106,  # BTN_DPAD_RIGHT -> KEY_RIGHT
  }
  all_keys = sorted(set(btn_map.values()) | {103, 108, 105, 106})

  uinput_fd = None
  gamepads = {}  # path -> {"fd": int, "hat_x": 0, "hat_y": 0, "lx": 0, "ly": 0, "ax": {}}
  avrcp_devs = {}  # path -> fd
  last_scan = 0.0
  last_input_mtime = 0
  inotify_fd = open_input_inotify_fd()
  need_scan = True

  def ensure_uinput():
    nonlocal uinput_fd
    if uinput_fd is not None:
      return True
    try:
      subprocess.run(["modprobe", "-q", "uinput"],
                     stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
      fd = os.open("/dev/uinput", os.O_WRONLY | os.O_NONBLOCK)
      fcntl.ioctl(fd, ui_set_evbit, 0x00)  # EV_SYN
      fcntl.ioctl(fd, ui_set_evbit, 0x01)  # EV_KEY
      for k in all_keys:
        fcntl.ioctl(fd, ui_set_keybit, k)
      name = b"Bananarchy BT Gamepad Bridge"
      udev = struct.pack("80sHHHHi", name, 0x06, 0x1209, 0x8110, 1, 0) + (b"\x00" * (64 * 4 * 4))
      os.write(fd, udev)
      fcntl.ioctl(fd, ui_dev_create)
      uinput_fd = fd
      return True
    except Exception:
      return False

  def emit_key(code, val):
    if uinput_fd is None and not ensure_uinput():
      return
    try:
      os.write(uinput_fd, struct.pack(ev_fmt, 0, 0, 0x01, code, val))
      os.write(uinput_fd, struct.pack(ev_fmt, 0, 0, 0x00, 0, 0))
    except OSError:
      pass

  def get_axis_dir(fd, axis, val, cache):
    if axis not in cache:
      try:
        ioc = (2 << 30) | (24 << 16) | (0x45 << 8) | (0x40 + axis)
        buf = fcntl.ioctl(fd, ioc, b"\x00" * 24)
        _v, min_v, max_v, _fz, _fl, _rs = struct.unpack("6i", buf)
        if max_v > min_v:
          cache[axis] = (min_v, max_v)
        else:
          cache[axis] = (-32768, 32767)
      except Exception:
        cache[axis] = (-32768, 32767)
    min_v, max_v = cache[axis]
    mid = (min_v + max_v) / 2.0
    span = (max_v - min_v) / 2.0
    if span <= 0:
      return 0
    norm = (val - mid) / span
    if norm < -0.40:
      return -1
    if norm > 0.40:
      return 1
    return 0

  while is_running():
    now = time.monotonic()
    if need_scan or (inotify_fd < 0 and now - last_scan >= 2.0):
      need_scan = False
      last_scan = now
      try:
        st_in = os.stat("/dev/input")
        if last_input_mtime != 0 and st_in.st_mtime_ns != last_input_mtime:
          subprocess.Popen(
            ["sh", "-c", "DISPLAY=:0 xsetroot -name \"$(cat /tmp/sxmo_status_bar 2>/dev/null || printf 'Bananarchy')\" >/dev/null 2>&1 || sxmo_hook_statusbar.sh >/dev/null 2>&1"],
            stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
          )
        last_input_mtime = st_in.st_mtime_ns
      except OSError:
        pass
      try:
        for entry in os.listdir("/dev/input"):
          if not entry.startswith("event"):
            continue
          dev_path = f"/dev/input/{entry}"
          if dev_path in gamepads or dev_path in avrcp_devs:
            continue
          sys_name_path = f"/sys/class/input/{entry}/device/name"
          dname = ""
          try:
            with open(sys_name_path, "r", encoding="utf-8") as nf:
              dname = nf.read().strip()
            if "Bananarchy BT Gamepad Bridge" in dname:
              continue
          except OSError:
            pass
          try:
            fd = os.open(dev_path, os.O_RDONLY | os.O_NONBLOCK)
            buf = bytearray(96)
            fcntl.ioctl(fd, eviocgbit_key, buf, True)
            has_gamepad = bool((buf[0x130 // 8] >> (0x130 % 8)) & 1) or bool((buf[0x120 // 8] >> (0x120 % 8)) & 1)
            has_qwerty = bool((buf[16 // 8] >> (16 % 8)) & 1) and bool((buf[30 // 8] >> (30 % 8)) & 1)
            has_avrcp_keys = any(
              bool((buf[k // 8] >> (k % 8)) & 1)
              for k in (163, 164, 165, 166, 200, 201)
            )
            dlow = dname.lower()
            is_avrcp_dev = ("(avrcp)" in dlow) or (
              has_avrcp_keys and not has_qwerty and not has_gamepad and
              not any(w in dlow for w in ("gpio", "pm8941", "keypad", "pwrkey"))
            )
            if has_gamepad and not has_qwerty:
              ensure_uinput()
              gamepads[dev_path] = {
                "fd": fd, "hat_x": 0, "hat_y": 0, "lx": 0, "ly": 0, "ax": {}
              }
            elif is_avrcp_dev:
              avrcp_devs[dev_path] = fd
            else:
              os.close(fd)
          except Exception:
            pass
      except OSError:
        pass

    fd_map = {info["fd"]: (path, info) for path, info in list(gamepads.items())}
    avrcp_map = {fd: path for path, fd in list(avrcp_devs.items())}
    wait_fds = list(fd_map.keys()) + list(avrcp_map.keys())
    if inotify_fd >= 0:
      wait_fds.append(inotify_fd)
    if wake_r >= 0:
      wait_fds.append(wake_r)
    if not wait_fds:
      time.sleep(1.5)
      continue
    sel_timeout = None if (inotify_fd >= 0 and wake_r >= 0) else 2.0
    try:
      rlist, _, _ = select.select(wait_fds, [], [], sel_timeout)
    except Exception:
      if is_running():
        time.sleep(0.5)
      continue

    if not is_running():
      break

    if inotify_fd >= 0 and inotify_fd in rlist:
      while True:
        try:
          if not os.read(inotify_fd, 512):
            break
        except BlockingIOError:
          break
        except OSError:
          break
      need_scan = True

    for rfd in rlist:
      if rfd in avrcp_map:
        apath = avrcp_map[rfd]
        try:
          data = os.read(rfd, ev_size * 16)
          if not data:
            raise OSError("EOF")
        except OSError:
          try:
            os.close(rfd)
          except OSError:
            pass
          avrcp_devs.pop(apath, None)
          continue
        offset = 0
        while offset + ev_size <= len(data):
          _sec, _usec, ev_type, ev_code, ev_val = struct.unpack_from(ev_fmt, data, offset)
          offset += ev_size
          if ev_type == 0x01 and ev_val == 1:
            dispatch_avrcp_key(ev_code)
        continue
      path, info = fd_map.get(rfd, (None, None))
      if not path:
        continue
      try:
        data = os.read(rfd, ev_size * 16)
        if not data:
          raise OSError("EOF")
      except OSError:
        try:
          os.close(rfd)
        except OSError:
          pass
        gamepads.pop(path, None)
        continue

      offset = 0
      while offset + ev_size <= len(data):
        _sec, _usec, ev_type, ev_code, ev_val = struct.unpack_from(ev_fmt, data, offset)
        offset += ev_size
        if ev_type == 0x01 and ev_code in btn_map:
          if ev_val in (0, 1, 2):
            emit_key(btn_map[ev_code], ev_val)
        elif ev_type == 0x03:
          if ev_code == 0x10:  # ABS_HAT0X
            new_dir = -1 if ev_val < 0 else (1 if ev_val > 0 else 0)
            old_dir = info["hat_x"]
            if new_dir != old_dir:
              if old_dir == -1:
                emit_key(105, 0)
              elif old_dir == 1:
                emit_key(106, 0)
              if new_dir == -1:
                emit_key(105, 1)
              elif new_dir == 1:
                emit_key(106, 1)
              info["hat_x"] = new_dir
          elif ev_code == 0x11:  # ABS_HAT0Y
            new_dir = -1 if ev_val < 0 else (1 if ev_val > 0 else 0)
            old_dir = info["hat_y"]
            if new_dir != old_dir:
              if old_dir == -1:
                emit_key(103, 0)
              elif old_dir == 1:
                emit_key(108, 0)
              if new_dir == -1:
                emit_key(103, 1)
              elif new_dir == 1:
                emit_key(108, 1)
              info["hat_y"] = new_dir
          elif ev_code == 0x00:  # ABS_X (Left Stick X)
            new_dir = get_axis_dir(rfd, 0x00, ev_val, info["ax"])
            old_dir = info["lx"]
            if new_dir != old_dir:
              if old_dir == -1:
                emit_key(105, 0)
              elif old_dir == 1:
                emit_key(106, 0)
              if new_dir == -1:
                emit_key(105, 1)
              elif new_dir == 1:
                emit_key(106, 1)
              info["lx"] = new_dir
          elif ev_code == 0x01:  # ABS_Y (Left Stick Y)
            new_dir = get_axis_dir(rfd, 0x01, ev_val, info["ax"])
            old_dir = info["ly"]
            if new_dir != old_dir:
              if old_dir == -1:
                emit_key(103, 0)
              elif old_dir == 1:
                emit_key(108, 0)
              if new_dir == -1:
                emit_key(103, 1)
              elif new_dir == 1:
                emit_key(108, 1)
              info["ly"] = new_dir

  if inotify_fd >= 0:
    try:
      os.close(inotify_fd)
    except OSError:
      pass
  for info in gamepads.values():
    try:
      os.close(info["fd"])
    except OSError:
      pass
  for afd in avrcp_devs.values():
    try:
      os.close(afd)
    except OSError:
      pass
  if uinput_fd is not None:
    try:
      fcntl.ioctl(uinput_fd, ui_dev_destroy)
    except Exception:
      pass
    try:
      os.close(uinput_fd)
    except OSError:
      pass


def dbus_send_safe(conn, msg, serial=None):
  if conn is None:
    return
  with DBUS_SEND_LOCK:
    if serial is None:
      conn.send(msg)
    else:
      conn.send(msg, serial=serial)


def trust_device_path(conn, dev_path):
  if not isinstance(dev_path, str) or not dev_path.startswith("/org/bluez/"):
    return
  try:
    from jeepney import DBusAddress, new_method_call
    prop_addr = DBusAddress(dev_path, bus_name="org.bluez",
                            interface="org.freedesktop.DBus.Properties")
    dbus_send_safe(conn, new_method_call(prop_addr, "Set", "ssv",
                                         ("org.bluez.Device1", "Trusted", ("b", True))))
  except Exception:
    pass


def set_hog_preferred_bearer(conn, dev_path, props=None):
  """Force the LE bearer for HID-over-GATT devices before Pair/Connect."""
  if not isinstance(dev_path, str) or not dev_path.startswith("/org/bluez/"):
    return
  uuids = []
  if isinstance(props, dict):
    uuids = [str(v).lower() for v in (props.get("UUIDs") or [])]
  if not any(u.startswith("00001812-") for u in uuids):
    return
  try:
    from jeepney import DBusAddress, new_method_call
    prop_addr = DBusAddress(dev_path, bus_name="org.bluez",
                            interface="org.freedesktop.DBus.Properties")
    dbus_send_safe(conn, new_method_call(prop_addr, "Set", "ssv",
                                         ("org.bluez.Device1", "PreferredBearer",
                                          ("s", "le"))))
  except Exception:
    pass


def set_audio_preferred_bearer(conn, dev_path, props=None):
  """Force BR/EDR bearer for Classic A2DP/HFP audio headsets before Pair/Connect."""
  if not isinstance(dev_path, str) or not dev_path.startswith("/org/bluez/"):
    return
  if not is_classic_audio_props(props):
    return
  try:
    from jeepney import DBusAddress, new_method_call
    prop_addr = DBusAddress(dev_path, bus_name="org.bluez",
                            interface="org.freedesktop.DBus.Properties")
    dbus_send_safe(conn, new_method_call(prop_addr, "Set", "ssv",
                                         ("org.bluez.Device1", "PreferredBearer",
                                          ("s", "bredr"))))
  except Exception:
    pass


def set_preferred_bearer_for_device(conn, dev_path, props=None):
  """Prefer BR/EDR for phones, computers, audio headsets, and public BR/EDR devices."""
  if not isinstance(dev_path, str) or not dev_path.startswith("/org/bluez/"):
    return
  if is_hog_device_props(props):
    return
  addr_type = str((props or {}).get("AddressType") or "").strip().lower()
  if not (is_phone_or_computer_props(props) or is_classic_audio_props(props) or addr_type == "public"):
    return
  try:
    from jeepney import DBusAddress, new_method_call
    prop_addr = DBusAddress(dev_path, bus_name="org.bluez",
                            interface="org.freedesktop.DBus.Properties")
    dbus_send_safe(conn, new_method_call(prop_addr, "Set", "ssv",
                                         ("org.bluez.Device1", "PreferredBearer",
                                          ("s", "bredr"))))
  except Exception:
    pass


def _extract_dev_mac_from_path(dev_path):
  if isinstance(dev_path, str) and "dev_" in dev_path:
    return dev_path.split("dev_")[-1].replace("_", ":").upper()
  return ""


def read_cached_bt_device_info(dev_path, bt_root="/var/lib/bluetooth"):
  mac = _extract_dev_mac_from_path(dev_path)
  if not mac or not os.path.isdir(bt_root):
    return {}
  out = {}
  try:
    adapters = os.listdir(bt_root)
  except OSError:
    return out
  for adapter in adapters:
    for rel in (os.path.join(adapter, mac, "info"),
                os.path.join(adapter, "cache", mac)):
      info_path = os.path.join(bt_root, rel)
      if not os.path.isfile(info_path):
        continue
      try:
        in_general = False
        with open(info_path, "r", encoding="utf-8", errors="replace") as f:
          for ln in f:
            s = ln.strip()
            if not s or s.startswith("#"):
              continue
            if s.startswith("[") and s.endswith("]"):
              in_general = (s.lower() == "[general]")
              continue
            if not in_general or "=" not in s:
              continue
            k, v = s.split("=", 1)
            k = k.strip()
            v = v.strip()
            if k in ("Name", "Alias", "Icon") and v and k not in out:
              out[k] = v
            elif k == "Class" and v and "Class" not in out:
              try:
                out["Class"] = int(v, 0)
              except ValueError:
                pass
            elif k == "Services" and v and "UUIDs" not in out:
              out["UUIDs"] = [u.strip() for u in v.split(";") if u.strip()]
      except OSError:
        pass
  return out


def unwrap_dbus_variant(val):
  if isinstance(val, tuple) and len(val) == 2 and isinstance(val[0], str):
    return val[1]
  if (isinstance(val, list) and len(val) == 2 and isinstance(val[0], str) and
      len(val[0]) <= 8 and "-" not in val[0]):
    return val[1]
  return val


def unwrap_props_dict(raw):
  if not isinstance(raw, dict):
    return {}
  return {k: unwrap_dbus_variant(v) for k, v in raw.items()}


def format_managed_objects_tsv(objs):
  """Format BlueZ ObjectManager objects into a compact CTRL/DEV TSV snapshot."""
  if not isinstance(objs, dict):
    return ""

  adapter_props = None
  if isinstance(objs.get("/org/bluez/hci0"), dict):
    a = objs["/org/bluez/hci0"].get("org.bluez.Adapter1")
    if isinstance(a, dict):
      adapter_props = unwrap_props_dict(a)

  if adapter_props is None:
    for opath in sorted(objs.keys()):
      if not isinstance(opath, str) or not opath.startswith("/org/bluez/hci"):
        continue
      ifaces = objs.get(opath)
      if isinstance(ifaces, dict) and isinstance(ifaces.get("org.bluez.Adapter1"), dict):
        adapter_props = unwrap_props_dict(ifaces["org.bluez.Adapter1"])
        break

  if adapter_props is None:
    return ""

  powered = 1 if bool(adapter_props.get("Powered", False)) else 0
  disc = 1 if bool(adapter_props.get("Discoverable", False)) else 0
  alias = (
    str(adapter_props.get("Alias") or adapter_props.get("Name") or "")
    .replace("\t", " ").replace("\n", " ").replace("\r", " ").strip()
  )
  lines = [f"CTRL\t{powered}\t{disc}\t{alias}"]

  dev_rows = []
  for opath, ifaces in objs.items():
    if not isinstance(opath, str) or not opath.startswith("/org/bluez/hci") or "/dev_" not in opath:
      continue
    if not isinstance(ifaces, dict) or not isinstance(ifaces.get("org.bluez.Device1"), dict):
      continue
    dprops = unwrap_props_dict(ifaces["org.bluez.Device1"])
    mac = str(dprops.get("Address") or _extract_dev_mac_from_path(opath) or "").strip().upper()
    if not mac:
      continue
    name = (
      str(dprops.get("Alias") or dprops.get("Name") or mac)
      .replace("\t", " ").replace("\n", " ").replace("\r", " ").strip()
    ) or mac
    paired = 1 if (bool(dprops.get("Paired", False)) or bool(dprops.get("Bonded", False))) else 0
    connected = 1 if bool(dprops.get("Connected", False)) else 0
    icon = (
      str(dprops.get("Icon") or "")
      .replace("\t", " ").replace("\n", " ").replace("\r", " ").strip().lower()
    )
    cod = dprops.get("Class")
    class_hex = f"0x{cod:06x}" if (isinstance(cod, int) and not isinstance(cod, bool)) else ""
    batt_pct = -1
    b_raw = ifaces.get("org.bluez.Battery1")
    if isinstance(b_raw, dict):
      bprops = unwrap_props_dict(b_raw)
      pval = bprops.get("Percentage")
      if isinstance(pval, (int, float)) and not isinstance(pval, bool):
        batt_pct = max(0, min(100, int(pval)))
    raw_uuids = dprops.get("UUIDs") or []
    uuids = ";".join(
      str(u).replace("\t", "").replace("\n", "").replace("\r", "").strip().lower()
      for u in raw_uuids if str(u).strip()
    )
    dev_rows.append((
      mac,
      opath,
      f"DEV\t{mac}\t{name}\t{paired}\t{connected}\t{icon}\t{class_hex}\t{batt_pct}\t{uuids}"
    ))

  dev_rows.sort(key=lambda item: (item[0], item[1]))
  lines.extend(row[2] for row in dev_rows)
  return "\n".join(lines) + "\n"


def fetch_managed_objects(conn=None, agent_path="", timeout=2.5):
  if not os.environ.get("DBUS_SYSTEM_BUS_ADDRESS") and not os.path.exists("/run/dbus/system_bus_socket"):
    return None
  own_conn = None
  try:
    from jeepney import DBusAddress, MessageType, new_method_call
    from jeepney.io.blocking import open_dbus_connection
    c = conn
    if c is None:
      own_conn = open_dbus_connection(bus="SYSTEM")
      c = own_conn
    om_addr = DBusAddress("/", bus_name="org.bluez",
                          interface="org.freedesktop.DBus.ObjectManager")
    call = new_method_call(om_addr, "GetManagedObjects")
    if conn is not None and agent_path:
      rep = dbus_call_with_agent(c, call, agent_path, timeout=timeout)
    else:
      rep = c.send_and_get_reply(call, timeout=timeout)
    if rep is not None and rep.header.message_type == MessageType.method_return and rep.body:
      objs = rep.body[0]
      if isinstance(objs, dict):
        return objs
  except Exception:
    pass
  finally:
    if own_conn is not None:
      try:
        own_conn.close()
      except Exception:
        pass
  return None


def dump_bluez_state_tsv(conn=None, agent_path=""):
  objs = fetch_managed_objects(conn=conn, agent_path=agent_path)
  tsv = format_managed_objects_tsv(objs)
  if not tsv:
    return ""
  try:
    ensure_obex_ipc_dir()
    write_multiline_atomic(BT_STATE_FILE, tsv)
  except OSError:
    pass
  return tsv


def is_controller_powered_dbus(timeout=0.5):
  if not os.environ.get("DBUS_SYSTEM_BUS_ADDRESS") and not os.path.exists("/run/dbus/system_bus_socket"):
    return False
  c = None
  try:
    from jeepney import DBusAddress, MessageType, new_method_call
    from jeepney.io.blocking import open_dbus_connection
    c = open_dbus_connection(bus="SYSTEM")
    prop_addr = DBusAddress("/org/bluez/hci0", bus_name="org.bluez",
                            interface="org.freedesktop.DBus.Properties")
    rep = c.send_and_get_reply(
      new_method_call(prop_addr, "Get", "ss", ("org.bluez.Adapter1", "Powered")),
      timeout=timeout
    )
    if rep is not None and rep.header.message_type == MessageType.method_return and rep.body:
      return bool(unwrap_dbus_variant(rep.body[0]))
  except Exception:
    pass
  finally:
    if c is not None:
      try:
        c.close()
      except Exception:
        pass
  return False


def query_dev_props_fresh(dev_path, timeout=0.6):
  if not isinstance(dev_path, str) or not dev_path.startswith("/org/bluez/"):
    return {}
  if not os.environ.get("DBUS_SYSTEM_BUS_ADDRESS") and not os.path.exists("/run/dbus/system_bus_socket"):
    return {}
  c = None
  try:
    from jeepney import DBusAddress, MessageType, new_method_call
    from jeepney.io.blocking import open_dbus_connection
    c = open_dbus_connection(bus="SYSTEM")
    prop_addr = DBusAddress(dev_path, bus_name="org.bluez",
                            interface="org.freedesktop.DBus.Properties")
    rep = c.send_and_get_reply(
      new_method_call(prop_addr, "GetAll", "s", ("org.bluez.Device1",)),
      timeout=timeout
    )
    if rep is not None and rep.header.message_type == MessageType.method_return and rep.body:
      raw = rep.body[0]
      if isinstance(raw, dict):
        return unwrap_props_dict(raw)
  except Exception:
    pass
  finally:
    if c is not None:
      try:
        c.close()
      except Exception:
        pass
  return {}


def lookup_agent_device_info(dev_path, dev_props_cache=None):
  mac = _extract_dev_mac_from_path(dev_path)
  info = {}
  if isinstance(dev_props_cache, dict) and dev_path in dev_props_cache:
    cached = dev_props_cache.get(dev_path)
    if isinstance(cached, dict):
      info.update(cached)
  disk = read_cached_bt_device_info(dev_path)
  for k, v in disk.items():
    info.setdefault(k, v)
  if not info.get("Name") and not info.get("UUIDs"):
    fresh = query_dev_props_fresh(dev_path)
    if fresh:
      info.update(fresh)
      if isinstance(dev_props_cache, dict) and dev_path:
        dev_props_cache[dev_path] = dict(info)
  name = str(info.get("Alias") or info.get("Name") or mac or "Bluetooth Device").strip()
  return name, mac, info


def clear_pair_prompt_files(notify_cancel=False):
  for p in (PAIR_PROMPT_FILE, PAIR_DECISION_FILE):
    try:
      if os.path.exists(p):
        os.unlink(p)
    except OSError:
      pass
  if notify_cancel:
    notify_networks_ui("PAIR_CANCEL\n")


def write_pair_prompt_tsv(req_id, mode, dev_name, dev_mac, code="", entered=0):
  ensure_obex_ipc_dir()
  s_label = str(dev_name or dev_mac or "Bluetooth Device").replace("\t", " ").replace("\n", " ").strip()
  s_mac = str(dev_mac or "").replace("\t", " ").replace("\n", " ").strip()
  s_code = str(code or "").replace("\t", " ").replace("\n", " ").strip()
  tmp_prompt = f"{PAIR_PROMPT_FILE}.{os.getpid()}.tmp"
  with open(tmp_prompt, "w", encoding="utf-8") as pf:
    pf.write(f"{req_id}\t{mode}\t{s_label}\t{s_mac}\t{s_code}\t{int(entered or 0)}\n")
  try:
    os.chmod(tmp_prompt, 0o644)
    os.chown(tmp_prompt, 10000, 10000)
  except OSError:
    pass
  os.replace(tmp_prompt, PAIR_PROMPT_FILE)


def write_display_pair_prompt(dev_name, dev_mac, code, entered=0):
  s_mac = str(dev_mac or "unknown").replace(":", "").strip()
  req_id = f"display_{s_mac}_{code}"
  write_pair_prompt_tsv(req_id, "DISPLAY", dev_name, dev_mac, code, entered)
  wake_and_alert_ui(f"PAIR_PROMPT {req_id}\n", "pair-prompt")


def request_user_pairing_interaction(mode, dev_name, dev_mac, code="", timeout_sec=50.0):
  with PAIR_PROMPT_LOCK:
    PAIR_CANCEL_EVENT.clear()
    clear_pair_prompt_files(notify_cancel=False)
    req_id = f"{os.getpid()}_{int(time.monotonic() * 1000)}"
    write_pair_prompt_tsv(req_id, mode, dev_name, dev_mac, code, 0)
    wake_and_alert_ui(f"PAIR_PROMPT {req_id}\n", "pair-prompt")

    deadline = time.monotonic() + timeout_sec
    try:
      while time.monotonic() < deadline:
        if PAIR_CANCEL_EVENT.is_set():
          return False, "", True
        if os.path.exists(PAIR_DECISION_FILE):
          try:
            with open(PAIR_DECISION_FILE, "r", encoding="utf-8", errors="replace") as df:
              line = df.readline().rstrip("\r\n")
            parts = line.split("\t")
            if len(parts) >= 2 and parts[0] == req_id:
              accepted = (parts[1].strip().upper() == "ACCEPT")
              val = parts[2].strip() if len(parts) >= 3 else ""
              return accepted, val, False
          except OSError:
            pass
        PAIR_CANCEL_EVENT.wait(0.08)
      return False, "", False
    finally:
      clear_pair_prompt_files(notify_cancel=False)
      notify_networks_ui()


def handle_agent_method_call(conn, msg, agent_path, dev_props_cache=None):
  from jeepney import new_method_return, new_error, MessageType
  if msg is None or msg.header.message_type != MessageType.method_call:
    return False
  path = msg.header.fields.get(1)
  member = msg.header.fields.get(3)
  if path != agent_path:
    return False
  dev_path = msg.body[0] if (msg.body and len(msg.body) > 0) else None
  if member in ("RequestAuthorization", "AuthorizeService"):
    dbus_send_safe(conn, new_method_return(msg))
    trust_device_path(conn, dev_path)
    notify_networks_ui()
    return True
  if member in ("DisplayPinCode", "DisplayPasskey"):
    dbus_send_safe(conn, new_method_return(msg))
    trust_device_path(conn, dev_path)
    if member == "DisplayPinCode":
      code_str = str(msg.body[1]) if len(msg.body) >= 2 else ""
      entered = 0
    else:
      code_num = int(msg.body[1]) if len(msg.body) >= 2 else 0
      entered = int(msg.body[2]) if len(msg.body) >= 3 else 0
      code_str = f"{code_num:06d}"
    d_name, d_mac, _ = lookup_agent_device_info(dev_path, dev_props_cache)
    write_display_pair_prompt(d_name, d_mac, code_str, entered)
    notify_networks_ui()
    return True
  if member == "RequestConfirmation":
    passkey_num = int(msg.body[1]) if len(msg.body) >= 2 else 0
    code_str = f"{passkey_num:06d}"
    def _run_confirm():
      d_name, d_mac, d_info = lookup_agent_device_info(dev_path, dev_props_cache)
      if is_classic_audio_props(d_info):
        dbus_send_safe(conn, new_method_return(msg))
        trust_device_path(conn, dev_path)
        notify_networks_ui()
        return
      accepted, _val, cancelled = request_user_pairing_interaction("CONFIRM", d_name, d_mac, code_str)
      if cancelled:
        return
      if accepted:
        dbus_send_safe(conn, new_method_return(msg))
        trust_device_path(conn, dev_path)
      else:
        dbus_send_safe(conn, new_error(msg, "org.bluez.Error.Rejected", "s", ("Pairing rejected",)))
      notify_networks_ui()
    threading.Thread(target=_run_confirm, daemon=True).start()
    return True
  if member == "RequestPinCode":
    def _run_pin():
      d_name, d_mac, _ = lookup_agent_device_info(dev_path, dev_props_cache)
      accepted, val, cancelled = request_user_pairing_interaction("PIN", d_name, d_mac, "")
      if cancelled:
        return
      pin = (val or "").strip()
      if accepted and pin:
        dbus_send_safe(conn, new_method_return(msg, "s", (pin,)))
        trust_device_path(conn, dev_path)
      else:
        dbus_send_safe(conn, new_error(msg, "org.bluez.Error.Rejected", "s", ("PIN entry cancelled",)))
      notify_networks_ui()
    threading.Thread(target=_run_pin, daemon=True).start()
    return True
  if member == "RequestPasskey":
    def _run_passkey():
      d_name, d_mac, _ = lookup_agent_device_info(dev_path, dev_props_cache)
      accepted, val, cancelled = request_user_pairing_interaction("PASSKEY", d_name, d_mac, "")
      if cancelled:
        return
      raw = (val or "").strip()
      if accepted and raw.isdigit() and 0 <= int(raw) <= 999999:
        dbus_send_safe(conn, new_method_return(msg, "u", (int(raw),)))
        trust_device_path(conn, dev_path)
      else:
        dbus_send_safe(conn, new_error(msg, "org.bluez.Error.Rejected", "s", ("Passkey entry cancelled",)))
      notify_networks_ui()
    threading.Thread(target=_run_passkey, daemon=True).start()
    return True
  if member in ("Cancel", "Release"):
    dbus_send_safe(conn, new_method_return(msg))
    PAIR_CANCEL_EVENT.set()
    clear_pair_prompt_files(notify_cancel=True)
    return True
  dbus_send_safe(conn, new_method_return(msg))
  return True


def dbus_call_with_agent(conn, call_msg, agent_path, timeout=5.0):
  from jeepney import HeaderFields, MessageType
  serial = next(conn.outgoing_serial)
  dbus_send_safe(conn, call_msg, serial=serial)
  deadline = time.time() + timeout
  while time.time() < deadline:
    rem = max(0.05, deadline - time.time())
    try:
      msg = conn.receive(timeout=rem)
    except TimeoutError:
      return None
    if msg is None:
      continue
    if handle_agent_method_call(conn, msg, agent_path):
      continue
    if msg.header.message_type in (MessageType.method_return, MessageType.error):
      if msg.header.fields.get(HeaderFields.reply_serial, -1) == serial:
        return msg
  return None


def register_bluez_services(conn, profile_path, agent_path):
  from jeepney import DBusAddress, MessageType, new_method_call
  try:
    if os.path.exists(AGENT_READY_FILE):
      os.unlink(AGENT_READY_FILE)
  except OSError:
    pass
  try:
    aprop = DBusAddress("/org/bluez/hci0", bus_name="org.bluez",
                        interface="org.freedesktop.DBus.Properties")
    dbus_call_with_agent(
      conn,
      new_method_call(aprop, "Set", "ssv",
                      ("org.bluez.Adapter1", "PairableTimeout", ("u", 0))),
      agent_path,
      timeout=2.0
    )
    dbus_call_with_agent(
      conn,
      new_method_call(aprop, "Set", "ssv",
                      ("org.bluez.Adapter1", "Pairable", ("b", True))),
      agent_path,
      timeout=2.0
    )
  except Exception:
    pass
  agent_ok = False
  try:
    am = DBusAddress("/org/bluez", bus_name="org.bluez",
                     interface="org.bluez.AgentManager1")
    rep_reg = dbus_call_with_agent(
      conn,
      new_method_call(am, "RegisterAgent", "os",
                      (agent_path, "KeyboardDisplay")),
      agent_path,
      timeout=3.0
    )
    if rep_reg is not None:
      if rep_reg.header.message_type == MessageType.method_return:
        agent_ok = True
      else:
        err_s = " ".join(str(x) for x in (rep_reg.body or ())).lower()
        if "already" in err_s:
          agent_ok = True
    rep_def = dbus_call_with_agent(
      conn,
      new_method_call(am, "RequestDefaultAgent", "o", (agent_path,)),
      agent_path,
      timeout=3.0
    )
    if agent_ok and rep_def is not None and rep_def.header.message_type == MessageType.method_return:
      ensure_obex_ipc_dir()
      write_status(AGENT_READY_FILE, str(os.getpid()))
  except Exception:
    pass
  try:
    pm = DBusAddress("/org/bluez", bus_name="org.bluez",
                     interface="org.bluez.ProfileManager1")
    opts_v = {
      "Name": ("s", "OBEX Object Push"),
      "Role": ("s", "server"),
      "Channel": ("q", 9),
      "Version": ("q", 0x0102),
      "RequireAuthentication": ("b", False),
      "RequireAuthorization": ("b", False),
    }
    opts_basic = {
      "Name": ("s", "OBEX Object Push"),
      "Role": ("s", "server"),
      "Channel": ("q", 9),
      "RequireAuthentication": ("b", False),
      "RequireAuthorization": ("b", False),
    }
    for opts in (opts_v, opts_basic):
      rep = dbus_call_with_agent(
        conn,
        new_method_call(pm, "RegisterProfile", "osa{sv}",
                        (profile_path, OPP_UUID, opts)),
        agent_path,
        timeout=3.0
      )
      if rep is None:
        continue
      if rep.header.message_type == MessageType.method_return:
        return True
      err_str = " ".join(str(x) for x in (rep.body or ())).lower()
      if "already" in err_str:
        return True
  except Exception:
    pass
  return False


def lookup_bt_device_label(conn, dev_path, agent_path):
  mac = ""
  if isinstance(dev_path, str) and "dev_" in dev_path:
    mac = dev_path.split("dev_")[-1].replace("_", ":").upper()
  if conn is not None and isinstance(dev_path, str) and dev_path.startswith("/org/bluez/"):
    try:
      from jeepney import DBusAddress, MessageType, new_method_call
      prop_addr = DBusAddress(dev_path, bus_name="org.bluez",
                              interface="org.freedesktop.DBus.Properties")
      rep = dbus_call_with_agent(
        conn,
        new_method_call(prop_addr, "GetAll", "s", ("org.bluez.Device1",)),
        agent_path,
        timeout=0.8
      )
      if rep is not None and rep.header.message_type == MessageType.method_return and rep.body:
        raw = rep.body[0]
        if isinstance(raw, dict):
          for key in ("Alias", "Name"):
            val = raw.get(key)
            if isinstance(val, (tuple, list)) and len(val) == 2:
              val = val[1]
            if isinstance(val, str) and val.strip():
              return val.strip(), mac
    except Exception:
      pass
  return (mac or "Bluetooth Device"), mac


def run_daemon():
  from jeepney import DBusAddress, new_method_call, new_method_return, MessageType
  from jeepney.io.blocking import open_dbus_connection

  ensure_obex_ipc_dir()
  for p in (AGENT_READY_FILE, PAIR_PROMPT_FILE, PAIR_DECISION_FILE):
    try:
      if os.path.exists(p):
        os.unlink(p)
    except OSError:
      pass
  write_status(PID_FILE, str(os.getpid()))
  write_status(RX_STATUS_FILE, f"IDLE\tReady ({shorten_obex_dir(get_configured_obex_dir())})")
  notify_networks_ui()

  running = True
  wake_r, wake_w = os.pipe()
  os.set_inheritable(wake_r, False)
  os.set_inheritable(wake_w, False)
  os.set_blocking(wake_r, False)
  os.set_blocking(wake_w, False)

  def stop_handler(_signum, _frame):
    nonlocal running
    running = False
    PAIR_CANCEL_EVENT.set()
    try:
      os.write(wake_w, b"\x01")
    except OSError:
      pass

  signal.signal(signal.SIGTERM, stop_handler)
  signal.signal(signal.SIGINT, stop_handler)

  def bind_rfcomm_fallback():
    s = None
    try:
      s = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_STREAM, socket.BTPROTO_RFCOMM)
      s.bind(("00:00:00:00:00:00", 9))
      s.listen(2)
      s.setblocking(False)
      return s
    except OSError:
      if s:
        try:
          s.close()
        except OSError:
          pass
      return None

  profile_path = "/org/bananarchy/obex_opp"
  agent_path = "/org/bananarchy/bt_agent"
  conn = None
  opp_registered = False
  rfcomm_listener = None
  dev_props_cache = {}
  managed_objs = {}

  def write_state_from_cache():
    tsv = format_managed_objects_tsv(managed_objs)
    if tsv:
      ensure_obex_ipc_dir()
      write_multiline_atomic(BT_STATE_FILE, tsv)

  def apply_adapter_settings(dbus_c):
    bt_name = ""
    try:
      if os.path.exists("/home/user/.config/sxmo/bt_name"):
        with open("/home/user/.config/sxmo/bt_name", "r", encoding="utf-8") as nf:
          bt_name = nf.readline().strip()
    except OSError:
      pass
    if not bt_name:
      try:
        bt_name = socket.gethostname().strip()
      except Exception:
        bt_name = "Bananarchy"

    bt_disc = "0"
    try:
      if os.path.exists("/home/user/.config/sxmo/bt_discoverable"):
        with open("/home/user/.config/sxmo/bt_discoverable", "r", encoding="utf-8") as df:
          bt_disc = df.readline().strip() or "0"
    except OSError:
      pass
    disc_on = bt_disc.lower() not in ("0", "off", "no", "false")

    if dbus_c is not None:
      try:
        aprop = DBusAddress("/org/bluez/hci0", bus_name="org.bluez",
                            interface="org.freedesktop.DBus.Properties")
        if bt_name:
          dbus_call_with_agent(
            dbus_c,
            new_method_call(aprop, "Set", "ssv",
                            ("org.bluez.Adapter1", "Alias", ("s", bt_name))),
            agent_path,
            timeout=2.0
          )
        dbus_call_with_agent(
          dbus_c,
          new_method_call(aprop, "Set", "ssv",
                          ("org.bluez.Adapter1", "PairableTimeout", ("u", 0))),
          agent_path,
          timeout=2.0
        )
        dbus_call_with_agent(
          dbus_c,
          new_method_call(aprop, "Set", "ssv",
                          ("org.bluez.Adapter1", "Pairable", ("b", True))),
          agent_path,
          timeout=2.0
        )
        dbus_call_with_agent(
          dbus_c,
          new_method_call(aprop, "Set", "ssv",
                          ("org.bluez.Adapter1", "DiscoverableTimeout", ("u", 60))),
          agent_path,
          timeout=2.0
        )
        dbus_call_with_agent(
          dbus_c,
          new_method_call(aprop, "Set", "ssv",
                          ("org.bluez.Adapter1", "Discoverable", ("b", disc_on))),
          agent_path,
          timeout=2.0
        )
        return
      except Exception:
        pass

    if bt_name:
      subprocess.run(["timeout", "2", "bluetoothctl", "system-alias", bt_name],
                     stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    subprocess.run(["timeout", "2", "bluetoothctl", "pairable-timeout", "0"],
                   stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    subprocess.run(["timeout", "2", "bluetoothctl", "pairable", "on"],
                   stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    subprocess.run(["timeout", "2", "bluetoothctl", "discoverable-timeout", "60"],
                   stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    subprocess.run(["timeout", "2", "bluetoothctl", "discoverable", "on" if disc_on else "off"],
                   stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)

  def refresh_dev_props_cache(dbus_c):
    if dbus_c is None:
      return
    objs = fetch_managed_objects(conn=dbus_c, agent_path=agent_path, timeout=2.5)
    if not isinstance(objs, dict):
      return
    dev_props_cache.clear()
    managed_objs.clear()
    for opath, ifaces in objs.items():
      if not isinstance(opath, str) or not isinstance(ifaces, dict):
        continue
      mentry = {}
      for iname in ("org.bluez.Adapter1", "org.bluez.Device1", "org.bluez.Battery1"):
        raw = ifaces.get(iname)
        if isinstance(raw, dict):
          unwrapped = unwrap_props_dict(raw)
          mentry[iname] = unwrapped
          if iname == "org.bluez.Device1":
            dev_props_cache[opath] = dict(unwrapped)
      if mentry:
        managed_objs[opath] = mentry
    write_state_from_cache()

  try:
    conn = open_dbus_connection(bus="SYSTEM", enable_fds=True)
    dbus_bus = DBusAddress("/org/freedesktop/DBus",
                           bus_name="org.freedesktop.DBus",
                           interface="org.freedesktop.DBus")
    for match_rule in (
      "type='signal',sender='org.freedesktop.DBus',member='NameOwnerChanged',arg0='org.bluez'",
      "type='signal',interface='org.freedesktop.DBus.Properties',member='PropertiesChanged',arg0='org.bluez.Device1'",
      "type='signal',interface='org.freedesktop.DBus.Properties',member='PropertiesChanged',arg0='org.bluez.Adapter1'",
      "type='signal',interface='org.freedesktop.DBus.Properties',member='PropertiesChanged',arg0='org.bluez.Battery1'",
      "type='signal',interface='org.freedesktop.DBus.ObjectManager',member='InterfacesAdded'",
      "type='signal',interface='org.freedesktop.DBus.ObjectManager',member='InterfacesRemoved'",
    ):
      dbus_send_safe(conn, new_method_call(dbus_bus, "AddMatch", "s", (match_rule,)))
    for _attempt in range(10):
      if not running:
        break
      opp_registered = register_bluez_services(conn, profile_path, agent_path)
      if opp_registered or os.path.exists(AGENT_READY_FILE):
        if opp_registered:
          break
      time.sleep(0.3)
  except Exception:
    pass

  if running and not opp_registered:
    rfcomm_listener = bind_rfcomm_fallback()

  prepare_bt_controller()
  apply_adapter_settings(conn)
  refresh_dev_props_cache(conn)

  gp_thread = threading.Thread(target=run_gamepad_uinput_bridge,
                               args=(lambda: running, wake_r), daemon=True)
  gp_thread.start()

  while running:
    try:
      if conn is not None:
        while running:
          try:
            msg = conn.receive(timeout=0.0)
          except TimeoutError:
            msg = None
          except (EOFError, OSError):
            try:
              conn.close()
            except Exception:
              pass
            conn = None
            break
          if msg is None:
            break
          if handle_agent_method_call(conn, msg, agent_path, dev_props_cache=dev_props_cache):
            pass
          elif msg.header.message_type == MessageType.method_call:
            member = msg.header.fields.get(3)  # Member name
            path = msg.header.fields.get(1)    # Object path
            if path == profile_path and member == "NewConnection":
              # Args: (o device, h fd, a{sv} fd_properties)
              dev_path, fd_obj, _props = msg.body
              reply = new_method_return(msg)
              dbus_send_safe(conn, reply)
              raw_fd = os.dup(fd_obj.fileno())
              fd_obj.close()
              client_sock = socket.socket(fileno=raw_fd)
              s_name, s_mac, _ = lookup_agent_device_info(dev_path, dev_props_cache)
              t = threading.Thread(target=handle_obex_rx_session,
                                   args=(client_sock, s_name, s_mac), daemon=True)
              t.start()
            elif path == profile_path and member in ("RequestDisconnection", "Release"):
              reply = new_method_return(msg)
              dbus_send_safe(conn, reply)
          elif msg.header.message_type == MessageType.signal:
            member = msg.header.fields.get(3)
            if member == "NameOwnerChanged" and msg.body and len(msg.body) >= 3:
              name, _old_owner, new_owner = msg.body[0], msg.body[1], msg.body[2]
              if name == "org.bluez":
                dev_props_cache.clear()
                managed_objs.clear()
                if new_owner:
                  if rfcomm_listener is not None:
                    try:
                      rfcomm_listener.close()
                    except OSError:
                      pass
                    rfcomm_listener = None
                  opp_registered = register_bluez_services(conn, profile_path, agent_path)
                  if not opp_registered:
                    rfcomm_listener = bind_rfcomm_fallback()
                  apply_adapter_settings(conn)
                  refresh_dev_props_cache(conn)
                else:
                  for p in (AGENT_READY_FILE, BT_STATE_FILE, CTRL_READY_FILE):
                    try:
                      if os.path.exists(p):
                        os.unlink(p)
                    except OSError:
                      pass
            elif member == "InterfacesAdded" and msg.body and len(msg.body) >= 2:
              opath, ifaces = msg.body[0], msg.body[1]
              if isinstance(opath, str) and isinstance(ifaces, dict):
                touched = False
                for iname in ("org.bluez.Adapter1", "org.bluez.Device1", "org.bluez.Battery1"):
                  raw = ifaces.get(iname)
                  if isinstance(raw, dict):
                    unwrapped = unwrap_props_dict(raw)
                    managed_objs.setdefault(opath, {})[iname] = unwrapped
                    if iname == "org.bluez.Device1":
                      dev_props_cache[opath] = dict(unwrapped)
                    touched = True
                if touched:
                  write_state_from_cache()
            elif member == "InterfacesRemoved" and msg.body and len(msg.body) >= 2:
              opath, ifaces = msg.body[0], msg.body[1]
              if isinstance(opath, str) and isinstance(ifaces, (list, tuple)):
                touched = False
                entry = managed_objs.get(opath)
                if isinstance(entry, dict):
                  for iname in ifaces:
                    if iname in entry:
                      entry.pop(iname, None)
                      touched = True
                    if iname == "org.bluez.Device1" and opath in dev_props_cache:
                      dev_props_cache.pop(opath, None)
                      touched = True
                  if not entry:
                    managed_objs.pop(opath, None)
                if touched:
                  write_state_from_cache()
                  if "org.bluez.Device1" in ifaces or "org.bluez.Battery1" in ifaces:
                    notify_networks_ui()
            elif member == "PropertiesChanged" and msg.body and len(msg.body) >= 2:
              obj_path = msg.header.fields.get(1)
              iface, changed = msg.body[0], msg.body[1]
              invalidated = msg.body[2] if len(msg.body) >= 3 else ()
              if (isinstance(obj_path, str) and
                  iface in ("org.bluez.Adapter1", "org.bluez.Device1", "org.bluez.Battery1") and
                  isinstance(changed, dict)):
                mentry = managed_objs.setdefault(obj_path, {}).setdefault(iface, {})
                for k, v in changed.items():
                  mentry[k] = unwrap_dbus_variant(v)
                if isinstance(invalidated, (list, tuple)):
                  for ik in invalidated:
                    mentry.pop(ik, None)
                if iface == "org.bluez.Device1":
                  dentry = dev_props_cache.setdefault(obj_path, {})
                  for k, v in changed.items():
                    dentry[k] = unwrap_dbus_variant(v)
                  if isinstance(invalidated, (list, tuple)):
                    for ik in invalidated:
                      dentry.pop(ik, None)
                  if changed.get("Paired"):
                    try:
                      if os.path.exists(PAIR_PROMPT_FILE):
                        with open(PAIR_PROMPT_FILE, "r", encoding="utf-8", errors="replace") as pf:
                          pln = pf.readline()
                        if "\tDISPLAY\t" in pln:
                          clear_pair_prompt_files(notify_cancel=True)
                    except OSError:
                      pass
                  if any(k not in EPHEMERAL_DEV_PROPS for k in changed) or bool(invalidated):
                    write_state_from_cache()
                  if any(k in changed for k in ("Connected", "Paired", "Bonded")):
                    notify_networks_ui()
                else:
                  write_state_from_cache()
                  if iface == "org.bluez.Battery1" or (
                    iface == "org.bluez.Adapter1" and
                    any(k in changed for k in ("Powered", "Discoverable", "Alias"))
                  ):
                    notify_networks_ui()

      if rfcomm_listener is not None:
        while running:
          try:
            csock, addr = rfcomm_listener.accept()
            rmac = addr[0].upper() if isinstance(addr, (tuple, list)) and addr else ""
            dpath = ("/org/bluez/hci0/dev_" + rmac.replace(":", "_")) if rmac else ""
            s_name, s_mac, _ = lookup_agent_device_info(dpath, dev_props_cache)
            t = threading.Thread(target=handle_obex_rx_session,
                                 args=(csock, s_name, s_mac or rmac), daemon=True)
            t.start()
          except BlockingIOError:
            break

      if not running:
        break

      wait_fds = [wake_r]
      if conn is not None and getattr(conn, "sock", None) is not None:
        wait_fds.append(conn.sock)
      if rfcomm_listener is not None:
        wait_fds.append(rfcomm_listener)
      select.select(wait_fds, [], [], None if len(wait_fds) > 1 else 5.0)
    except Exception:
      if running:
        time.sleep(0.5)

  if rfcomm_listener is not None:
    try:
      rfcomm_listener.close()
    except OSError:
      pass
  for fd in (wake_r, wake_w):
    try:
      os.close(fd)
    except OSError:
      pass
  clear_pair_prompt_files(notify_cancel=True)
  for p in (PID_FILE, AGENT_READY_FILE, BT_STATE_FILE, CTRL_READY_FILE):
    try:
      if os.path.exists(p):
        os.unlink(p)
    except OSError:
      pass


def connect_opp_socket(mac):
  from jeepney import DBusAddress, new_method_call, new_method_return, MessageType
  from jeepney.io.blocking import open_dbus_connection

  mac = mac.strip().upper()
  dev_path = "/org/bluez/hci0/dev_" + mac.replace(":", "_")
  client_profile_path = f"/org/bananarchy/obex_client_{os.getpid()}"

  # Method 1: Use BlueZ ProfileManager1 client profile + Device1.ConnectProfile
  try:
    conn = open_dbus_connection(bus="SYSTEM", enable_fds=True)
    pm = DBusAddress("/org/bluez", bus_name="org.bluez",
                     interface="org.bluez.ProfileManager1")
    opts = {
      "Name": ("s", "OBEX Object Push Client"),
      "Role": ("s", "client"),
    }
    conn.send_and_get_reply(
      new_method_call(pm, "RegisterProfile", "osa{sv}",
                      (client_profile_path, OPP_UUID, opts)),
      timeout=4.0
    )
    dev_addr = DBusAddress(dev_path, bus_name="org.bluez",
                           interface="org.bluez.Device1")
    conn.send(new_method_call(dev_addr, "ConnectProfile", "s", (OPP_UUID,)))

    deadline = time.time() + 10.0
    while time.time() < deadline:
      rem = max(0.1, deadline - time.time())
      try:
        msg = conn.receive(timeout=rem)
      except TimeoutError:
        break
      if msg.header.message_type == MessageType.method_call:
        if msg.header.fields.get(1) == client_profile_path and \
           msg.header.fields.get(3) == "NewConnection":
          _dpath, fd_obj, _props = msg.body
          conn.send(new_method_return(msg))
          raw_fd = os.dup(fd_obj.fileno())
          fd_obj.close()
          return socket.socket(fileno=raw_fd), conn, client_profile_path
      elif msg.header.message_type == MessageType.error:
        break
    try:
      conn.send_and_get_reply(
        new_method_call(pm, "UnregisterProfile", "o", (client_profile_path,)),
        timeout=2.0
      )
      conn.close()
    except Exception:
      pass
  except Exception:
    pass

  # Method 2: Direct RFCOMM channel scan for common OPP channels
  for ch in (12, 9, 4, 10, 5, 6, 1, 2, 3, 7, 8, 11):
    s = None
    try:
      s = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_STREAM, socket.BTPROTO_RFCOMM)
      s.settimeout(2.5)
      s.connect((mac, ch))
      return s, None, None
    except OSError:
      if s:
        try:
          s.close()
        except Exception:
          pass

  return None, None, None


def send_file_obex(mac, filepath):
  if not os.path.isfile(filepath):
    write_status(TX_STATUS_FILE, "ERROR\tFile not found")
    return 1

  filename = os.path.basename(filepath)
  filesize = os.path.getsize(filepath)
  write_status(TX_STATUS_FILE, f"CONNECTING\t{filename}\t{mac}")

  sock, dbus_conn, prof_path = connect_opp_socket(mac)
  if sock is None:
    write_status(TX_STATUS_FILE, f"ERROR\tCould not connect to {mac}")
    notify_user("Bluetooth Send Failed", f"Could not connect to {mac}")
    return 1

  try:
    sock.settimeout(20.0)
    reader = ObexPacketReader(sock)
    # 1. OBEX CONNECT
    conn_pkt = struct.pack(">BHBBH", 0x80, 7, 0x10, 0x00, 0x8000)
    sock.sendall(conn_pkt)
    resp_op, resp_body = recv_obex_packet(reader)
    if resp_op != 0xA0 or resp_body is None or len(resp_body) < 4:
      write_status(TX_STATUS_FILE, "ERROR\tOBEX Connect rejected")
      notify_user("Bluetooth Send Failed", "Remote rejected OBEX connection")
      return 1

    remote_max_pkt = struct.unpack(">H", resp_body[2:4])[0]
    max_pkt = min(max(255, remote_max_pkt), 8192)

    # 2. Build Name header (0x01) + Length header (0xC3)
    name_utf16 = filename.encode("utf-16-be") + b"\x00\x00"
    name_hdr = struct.pack(">BH", 0x01, 3 + len(name_utf16)) + name_utf16
    len_hdr = struct.pack(">BI", 0xC3, filesize)
    first_headers = name_hdr + len_hdr

    sent_bytes = 0
    with open(filepath, "rb") as f:
      first = True
      while True:
        hdr_prefix = first_headers if first else b""
        first = False
        max_chunk = max_pkt - 3 - len(hdr_prefix) - 3
        if max_chunk < 64:
          max_chunk = 64
        chunk = f.read(max_chunk)
        eof = (len(chunk) == 0) or (sent_bytes + len(chunk) >= filesize)

        body_hi = 0x49 if eof else 0x48
        body_hdr = struct.pack(">BH", body_hi, 3 + len(chunk)) + chunk
        pkt_payload = hdr_prefix + body_hdr
        pkt_op = 0x82 if eof else 0x02
        pkt = struct.pack(">BH", pkt_op, 3 + len(pkt_payload)) + pkt_payload
        sock.sendall(pkt)

        sent_bytes += len(chunk)
        pct = int((sent_bytes * 100) // filesize) if filesize > 0 else 100
        write_status(TX_STATUS_FILE, f"SENDING\t{filename}\t{pct}%")

        r_op, _r_body = recv_obex_packet(reader)
        if eof:
          if r_op == 0xA0:
            write_status(TX_STATUS_FILE, f"SENT\t{filename}\t{format_size(filesize)}")
            notify_user("Bluetooth File Sent", f"Sent {filename} ({format_size(filesize)})")
            break
          else:
            write_status(TX_STATUS_FILE, f"ERROR\tTransfer rejected (0x{r_op or 0:02X})")
            notify_user("Bluetooth Send Failed", f"Transfer rejected by {mac}")
            return 1
        else:
          if r_op != 0x90:
            write_status(TX_STATUS_FILE, f"ERROR\tTransfer aborted (0x{r_op or 0:02X})")
            notify_user("Bluetooth Send Failed", f"Transfer interrupted ({pct}%)")
            return 1

    # 3. OBEX DISCONNECT
    try:
      sock.sendall(struct.pack(">BH", 0x81, 3))
      recv_obex_packet(reader)
    except Exception:
      pass
    return 0
  except Exception as e:
    write_status(TX_STATUS_FILE, f"ERROR\t{e}")
    notify_user("Bluetooth Send Failed", str(e))
    return 1
  finally:
    try:
      sock.close()
    except Exception:
      pass
    if dbus_conn and prof_path:
      try:
        from jeepney import DBusAddress, new_method_call
        pm = DBusAddress("/org/bluez", bus_name="org.bluez",
                         interface="org.bluez.ProfileManager1")
        dbus_conn.send_and_get_reply(
          new_method_call(pm, "UnregisterProfile", "o", (prof_path,)),
          timeout=2.0
        )
        dbus_conn.close()
      except Exception:
        pass


def is_daemon_pid_alive(pid):
  if pid <= 0 or pid == os.getpid():
    return False
  try:
    with open(f"/proc/{pid}/cmdline", "rb") as cf:
      cmd = cf.read().replace(b"\x00", b" ").decode("utf-8", "replace")
    return ("bananarchy-bt-obex" in cmd) and (" daemon" in cmd)
  except OSError:
    return False


def find_running_daemon_pids():
  pids = []
  try:
    for entry in os.listdir("/proc"):
      if entry.isdigit():
        pid = int(entry)
        if is_daemon_pid_alive(pid):
          pids.append(pid)
  except OSError:
    pass
  return pids


def ensure_daemon_running():
  if find_running_daemon_pids() and os.path.exists(AGENT_READY_FILE):
    return
  if not find_running_daemon_pids():
    try:
      if os.geteuid() != 0:
        subprocess.Popen(["doas", "-n", "/usr/bin/bananarchy-bt-obex", "daemon"],
                         stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
                         start_new_session=True)
      else:
        subprocess.Popen([sys.executable, __file__, "daemon"],
                         stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
                         start_new_session=True)
    except Exception:
      pass
  deadline = time.monotonic() + 1.5
  while time.monotonic() < deadline:
    if find_running_daemon_pids() and os.path.exists(AGENT_READY_FILE):
      return
    time.sleep(0.05)


def prepare_bt_controller(force=False):
  """Power the adapter and enable LE before DBus Pair/Connect calls."""
  if not force and os.path.exists(CTRL_READY_FILE) and is_controller_powered_dbus():
    return
  try:
    subprocess.run(["timeout", "3", "bluetoothctl", "power", "on"],
                   stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
                   timeout=4)
  except Exception:
    pass
  helper = "/usr/bin/bananarchy-bt-le-enable.sh"
  try:
    if os.geteuid() == 0:
      subprocess.run([helper], stdout=subprocess.DEVNULL,
                     stderr=subprocess.DEVNULL, timeout=4)
    else:
      subprocess.run(["doas", "-n", helper], stdout=subprocess.DEVNULL,
                     stderr=subprocess.DEVNULL, timeout=4)
  except Exception:
    pass
  try:
    ensure_obex_ipc_dir()
    write_status(CTRL_READY_FILE, "1")
  except OSError:
    pass


def clear_stale_linkkey(mac):
  mac = mac.strip().upper()
  if not mac:
    return False
  if os.geteuid() != 0:
    res = subprocess.run(
      ["doas", "-n", "/usr/bin/bananarchy-bt-obex", "clear-linkkey", mac],
      stdout=subprocess.DEVNULL,
      stderr=subprocess.DEVNULL
    )
    return res.returncode == 0

  bt_root = "/var/lib/bluetooth"
  changed = False
  if os.path.isdir(bt_root):
    for adapter in os.listdir(bt_root):
      info_path = os.path.join(bt_root, adapter, mac, "info")
      if not os.path.isfile(info_path):
        continue
      try:
        with open(info_path, "r", encoding="utf-8", errors="replace") as f:
          lines = f.readlines()
        out_lines = []
        skip_sec = False
        for ln in lines:
          s = ln.strip()
          if s.startswith("[") and s.endswith("]"):
            skip_sec = s.lower() in ("[linkkey]", "[longtermkey]", "[peripherallongtermkey]", "[slaveLongtermkey]")
          if not skip_sec:
            out_lines.append(ln)
        if len(out_lines) != len(lines):
          with open(info_path, "w", encoding="utf-8") as f:
            f.writelines(out_lines)
          changed = True
      except Exception:
        pass
  if changed:
    subprocess.run(["rc-service", "bluetooth", "restart"],
                   stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    time.sleep(0.8)
    subprocess.run(["bluetoothctl", "power", "on"],
                   stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    time.sleep(0.4)
  return changed


def connect_or_pair_bt_device(mac, dev_name="", do_pair=False):
  from jeepney import DBusAddress, new_method_call, MessageType
  from jeepney.io.blocking import open_dbus_connection

  ensure_daemon_running()
  prepare_bt_controller()
  mac = mac.strip().upper()
  if not mac:
    return 1

  dev_path = "/org/bluez/hci0/dev_" + mac.replace(":", "_")
  orig_path = dev_path
  cli_agent_path = f"/org/bananarchy/bt_cli_agent_{os.getpid()}"
  adapter_addr = DBusAddress("/org/bluez/hci0", bus_name="org.bluez",
                             interface="org.bluez.Adapter1")
  am_addr = DBusAddress("/org/bluez", bus_name="org.bluez",
                        interface="org.bluez.AgentManager1")
  om_addr = DBusAddress("/", bus_name="org.bluez",
                        interface="org.freedesktop.DBus.ObjectManager")

  conn = None
  nonlocal_conn = [None]
  cli_registered = False
  use_cli_agent = not (bool(find_running_daemon_pids()) and os.path.exists(AGENT_READY_FILE))
  try:
    conn = open_dbus_connection(bus="SYSTEM")
    nonlocal_conn[0] = conn
    aprop_addr = DBusAddress("/org/bluez/hci0", bus_name="org.bluez",
                             interface="org.freedesktop.DBus.Properties")
    dbus_call_with_agent(
      conn,
      new_method_call(aprop_addr, "Set", "ssv",
                      ("org.bluez.Adapter1", "PairableTimeout", ("u", 0))),
      cli_agent_path,
      timeout=2.0
    )
    dbus_call_with_agent(
      conn,
      new_method_call(aprop_addr, "Set", "ssv",
                      ("org.bluez.Adapter1", "Pairable", ("b", True))),
      cli_agent_path,
      timeout=2.0
    )
    if use_cli_agent:
      dbus_call_with_agent(
        conn,
        new_method_call(am_addr, "RegisterAgent", "os",
                        (cli_agent_path, "KeyboardDisplay")),
        cli_agent_path,
        timeout=2.5
      )
      cli_registered = True
      dbus_call_with_agent(
        conn,
        new_method_call(am_addr, "RequestDefaultAgent", "o", (cli_agent_path,)),
        cli_agent_path,
        timeout=2.5
      )

    def pump_agent(duration):
      end_t = time.time() + duration
      while time.time() < end_t:
        rem = max(0.05, min(0.25, end_t - time.time()))
        try:
          m = nonlocal_conn[0].receive(timeout=rem)
          if m is not None:
            handle_agent_method_call(nonlocal_conn[0], m, cli_agent_path)
        except TimeoutError:
          pass

    def get_dev_props(dpath):
      prop_addr = DBusAddress(dpath, bus_name="org.bluez",
                              interface="org.freedesktop.DBus.Properties")
      rep = dbus_call_with_agent(
        nonlocal_conn[0],
        new_method_call(prop_addr, "GetAll", "s", ("org.bluez.Device1",)),
        cli_agent_path,
        timeout=2.5
      )
      if rep is None or rep.header.message_type != MessageType.method_return or not rep.body:
        return None
      raw = rep.body[0]
      if not isinstance(raw, dict):
        return None
      out = {}
      for k, v in raw.items():
        out[k] = v[1] if (isinstance(v, (tuple, list)) and len(v) == 2) else v
      return out

    def find_matching_device(target_name, prefer_path=None):
      if not target_name:
        return None
      t_low = target_name.strip().lower()
      rep = dbus_call_with_agent(
        nonlocal_conn[0],
        new_method_call(om_addr, "GetManagedObjects"),
        cli_agent_path,
        timeout=3.0
      )
      if rep is None or rep.header.message_type != MessageType.method_return or not rep.body:
        return None
      objs = rep.body[0]
      if not isinstance(objs, dict):
        return None
      candidates = []
      for opath, ifaces in objs.items():
        if not isinstance(opath, str) or not opath.startswith("/org/bluez/hci0/dev_"):
          continue
        dprops_raw = ifaces.get("org.bluez.Device1") if isinstance(ifaces, dict) else None
        if not isinstance(dprops_raw, dict):
          continue
        dprops = {
          k: (v[1] if isinstance(v, (tuple, list)) and len(v) == 2 else v)
          for k, v in dprops_raw.items()
        }
        nm = str(dprops.get("Name") or dprops.get("Alias") or "").strip().lower()
        exact = (nm == t_low)
        le_alias = (nm == f"{t_low} le" or f"{nm} le" == t_low)
        if exact or le_alias:
          score = 0 if exact else -25
          addr_type = str(dprops.get("AddressType") or "").strip().lower()
          if dprops.get("Connected"):
            score += 100
          if is_classic_audio_props(dprops):
            score += 60
          elif is_phone_or_computer_props(dprops):
            score += 50
          if addr_type == "public":
            score += 40
          elif addr_type == "random" and not is_hog_device_props(dprops):
            score -= 40
          if "RSSI" in dprops and dprops.get("RSSI") is not None:
            score += 50
          if opath == prefer_path:
            score += 10
          candidates.append((score, opath))
      if not candidates:
        return None
      candidates.sort(key=lambda x: x[0], reverse=True)
      return candidates[0][1]

    def has_media_transport(dpath):
      rep = dbus_call_with_agent(
        nonlocal_conn[0],
        new_method_call(om_addr, "GetManagedObjects"),
        cli_agent_path,
        timeout=2.5
      )
      if rep is None or rep.header.message_type != MessageType.method_return or not rep.body:
        return False
      objs = rep.body[0]
      if not isinstance(objs, dict):
        return False
      prefix = dpath + "/"
      for opath, ifaces in objs.items():
        if isinstance(opath, str) and opath.startswith(prefix) and isinstance(ifaces, dict):
          if "org.bluez.MediaTransport1" in ifaces:
            return True
      return False

    def connect_classic_audio_profiles(dpath, props):
      if not is_classic_audio_props(props):
        return
      set_audio_preferred_bearer(nonlocal_conn[0], dpath, props)
      uuids = [str(v).lower() for v in (props.get("UUIDs") or [])]
      dev_addr = DBusAddress(dpath, bus_name="org.bluez",
                             interface="org.bluez.Device1")
      profiles = []
      if any(u.startswith("0000110b-") for u in uuids):
        profiles.append("0000110b-0000-1000-8000-00805f9b34fb")
      if any(u.startswith("0000111e-") for u in uuids):
        profiles.append("0000111e-0000-1000-8000-00805f9b34fb")
      if any(u.startswith("00001108-") for u in uuids):
        profiles.append("00001108-0000-1000-8000-00805f9b34fb")
      if not profiles:
        profiles = [
          "0000110b-0000-1000-8000-00805f9b34fb",
          "0000111e-0000-1000-8000-00805f9b34fb",
        ]
      for prof_uuid in profiles:
        dbus_call_with_agent(
          nonlocal_conn[0],
          new_method_call(dev_addr, "ConnectProfile", "s", (prof_uuid,)),
          cli_agent_path,
          timeout=6.0
        )

    def wait_for_bond_if_connected(dpath, max_wait=3.5):
      deadline = time.time() + max_wait
      while time.time() < deadline:
        pump_agent(0.25)
        p = get_dev_props(dpath)
        if not p or not p.get("Connected"):
          break
        if p.get("Paired") or p.get("Bonded"):
          return p
      return get_dev_props(dpath)

    def cancel_pending_connect(dpath):
      dev_addr = DBusAddress(dpath, bus_name="org.bluez",
                             interface="org.bluez.Device1")
      dbus_call_with_agent(
        nonlocal_conn[0], new_method_call(dev_addr, "Disconnect"), cli_agent_path, timeout=2.0
      )

    def attempt_connect_path(dpath, want_pair):
      p = get_dev_props(dpath)
      set_hog_preferred_bearer(nonlocal_conn[0], dpath, p)
      set_audio_preferred_bearer(nonlocal_conn[0], dpath, p)
      set_preferred_bearer_for_device(nonlocal_conn[0], dpath, p)
      trust_device_path(nonlocal_conn[0], dpath)
      if p is None:
        return False
      if p.get("Connected"):
        if is_classic_audio_props(p) and not has_media_transport(dpath):
          connect_classic_audio_profiles(dpath, p)
          pump_agent(0.4)
          p = get_dev_props(dpath) or p
        p = wait_for_bond_if_connected(dpath, 3.5) or p
        if p.get("Connected") and (not want_pair or p.get("Paired") or p.get("Bonded")):
          return True

      dev_addr = DBusAddress(dpath, bus_name="org.bluez",
                             interface="org.bluez.Device1")
      if want_pair and not (p.get("Paired") or p.get("Bonded")):
        rep = dbus_call_with_agent(
          nonlocal_conn[0], new_method_call(dev_addr, "Pair"), cli_agent_path, timeout=50.0
        )
        if rep is None:
          cancel_pending_connect(dpath)
        elif rep.header.message_type == MessageType.error:
          err_str = " ".join(str(x) for x in (rep.body or ())).lower()
          if "key-missing" in err_str:
            dev_mac = dpath.split("dev_")[-1].replace("_", ":")
            if clear_stale_linkkey(dev_mac):
              prepare_bt_controller(force=True)
              if not use_cli_agent:
                w_end = time.monotonic() + 2.0
                while time.monotonic() < w_end and not os.path.exists(AGENT_READY_FILE):
                  time.sleep(0.05)
              rep = dbus_call_with_agent(
                nonlocal_conn[0], new_method_call(dev_addr, "Pair"), cli_agent_path, timeout=50.0
              )
        p = get_dev_props(dpath) or {}
        set_hog_preferred_bearer(nonlocal_conn[0], dpath, p)
        set_audio_preferred_bearer(nonlocal_conn[0], dpath, p)
        set_preferred_bearer_for_device(nonlocal_conn[0], dpath, p)

      if is_phone_or_computer_props(p) and want_pair and (p.get("Paired") or p.get("Bonded")):
        trust_device_path(nonlocal_conn[0], dpath)
        return True

      if not p.get("Connected"):
        rep = dbus_call_with_agent(
          nonlocal_conn[0], new_method_call(dev_addr, "Connect"), cli_agent_path, timeout=12.0
        )
        if rep is None:
          cancel_pending_connect(dpath)
        elif rep.header.message_type == MessageType.error:
          err_str = " ".join(str(x) for x in (rep.body or ())).lower()
          if "key-missing" in err_str or ("authentication" in err_str and "rejected" not in err_str and "canceled" not in err_str):
            dev_mac = dpath.split("dev_")[-1].replace("_", ":")
            if clear_stale_linkkey(dev_mac):
              try:
                nonlocal_conn[0].close()
              except Exception:
                pass
              conn_new = open_dbus_connection(bus="SYSTEM")
              nonlocal_conn[0] = conn_new
              dbus_call_with_agent(
                conn_new,
                new_method_call(aprop_addr, "Set", "ssv",
                                ("org.bluez.Adapter1", "Pairable", ("b", True))),
                cli_agent_path,
                timeout=2.0
              )
              if use_cli_agent:
                dbus_call_with_agent(
                  conn_new,
                  new_method_call(am_addr, "RegisterAgent", "os",
                                  (cli_agent_path, "KeyboardDisplay")),
                  cli_agent_path,
                  timeout=2.5
                )
                dbus_call_with_agent(
                  conn_new,
                  new_method_call(am_addr, "RequestDefaultAgent", "o", (cli_agent_path,)),
                  cli_agent_path,
                  timeout=2.5
                )
              else:
                w_end = time.monotonic() + 2.0
                while time.monotonic() < w_end and not os.path.exists(AGENT_READY_FILE):
                  time.sleep(0.05)
              prepare_bt_controller(force=True)
              trust_device_path(conn_new, dpath)
              set_hog_preferred_bearer(conn_new, dpath, p)
              set_audio_preferred_bearer(conn_new, dpath, p)
              set_preferred_bearer_for_device(conn_new, dpath, p)
              dbus_call_with_agent(
                conn_new, new_method_call(dev_addr, "Pair"), cli_agent_path, timeout=50.0
              )
              p_after = get_dev_props(dpath) or p
              if not (is_phone_or_computer_props(p_after) and (p_after.get("Paired") or p_after.get("Bonded"))):
                dbus_call_with_agent(
                  conn_new, new_method_call(dev_addr, "Connect"), cli_agent_path, timeout=12.0
                )
        p = get_dev_props(dpath) or {}

      if is_classic_audio_props(p) and (not p.get("Connected") or not has_media_transport(dpath)):
        connect_classic_audio_profiles(dpath, p)
        pump_agent(0.4)
        p = get_dev_props(dpath) or p

      if p.get("Connected") and not (p.get("Paired") or p.get("Bonded")):
        p = wait_for_bond_if_connected(dpath, 4.0) or p

      if p.get("Connected"):
        return True
      if want_pair and (p.get("Paired") or p.get("Bonded")):
        return True
      return False

    def is_tentative_ble_non_hog(dprops):
      if not isinstance(dprops, dict):
        return False
      addr_type = str(dprops.get("AddressType") or "").strip().lower()
      return (
        addr_type == "random" and
        not is_hog_device_props(dprops) and
        not is_classic_audio_props(dprops) and
        not dprops.get("Paired") and
        not dprops.get("Bonded")
      )

    def scan_for_device(prefer_path, max_scan=15.0):
      dbus_call_with_agent(
        nonlocal_conn[0], new_method_call(adapter_addr, "StartDiscovery"), cli_agent_path, timeout=2.5
      )
      scan_start = time.time()
      scan_deadline = scan_start + max_scan
      discovered_path = prefer_path
      while time.time() < scan_deadline:
        pump_agent(0.35)
        elapsed = time.time() - scan_start
        p = get_dev_props(prefer_path)
        if p and p.get("Connected"):
          discovered_path = prefer_path
          break
        if dev_name:
          alt = find_matching_device(dev_name, prefer_path=prefer_path)
          if alt:
            ap = get_dev_props(alt)
            if ap and (ap.get("Connected") or ap.get("RSSI") is not None):
              discovered_path = alt
              trust_device_path(nonlocal_conn[0], discovered_path)
              min_wait = 3.5 if is_tentative_ble_non_hog(ap) else 0.8
              if ap.get("Connected") or elapsed >= min_wait:
                break
        if p and p.get("RSSI") is not None:
          min_wait = 3.5 if is_tentative_ble_non_hog(p) else 0.8
          if elapsed >= min_wait:
            discovered_path = prefer_path
            break
      dbus_call_with_agent(
        nonlocal_conn[0], new_method_call(adapter_addr, "StopDiscovery"), cli_agent_path, timeout=2.0
      )
      pump_agent(0.15)
      return discovered_path

    props = get_dev_props(dev_path)
    orig_unbonded = (props is None) or (not props.get("Paired") and not props.get("Bonded"))
    if not do_pair and orig_unbonded and (props is not None or dev_name):
      do_pair = True
    if props and not dev_name:
      dev_name = str(props.get("Name") or props.get("Alias") or "").strip()
    if props is None and dev_name:
      alt = find_matching_device(dev_name)
      if alt:
        dev_path = alt
        props = get_dev_props(dev_path)

    trust_device_path(nonlocal_conn[0], dev_path)

    # Try connecting directly first when BlueZ already knows the device (avoids
    # blocking 15s in StartDiscovery for paired BR/EDR headsets in Page Scan).
    if props is None:
      dev_path = scan_for_device(dev_path, max_scan=8.0)

    ok = attempt_connect_path(dev_path, do_pair)

    if not ok:
      discovered_path = scan_for_device(dev_path, max_scan=8.0)
      ok = attempt_connect_path(discovered_path, do_pair)
      if ok and discovered_path != orig_path and orig_unbonded:
        dbus_call_with_agent(
          nonlocal_conn[0],
          new_method_call(adapter_addr, "RemoveDevice", "o", (orig_path,)),
          cli_agent_path,
          timeout=2.0
        )

    notify_networks_ui()
    return 0 if ok else 1
  except Exception:
    return 1
  finally:
    c_final = nonlocal_conn[0]
    if c_final is not None:
      if cli_registered:
        try:
          dbus_call_with_agent(
            c_final,
            new_method_call(am_addr, "UnregisterAgent", "o", (cli_agent_path,)),
            cli_agent_path,
            timeout=1.5
          )
        except Exception:
          pass
      try:
        c_final.close()
      except Exception:
        pass


def stop_daemon():
  pids = set(find_running_daemon_pids())
  if os.path.exists(PID_FILE):
    try:
      with open(PID_FILE, "r", encoding="utf-8") as f:
        pid = int(f.read().strip())
      pids.add(pid)
    except Exception:
      pass
  for pid in pids:
    try:
      os.kill(pid, signal.SIGTERM)
    except OSError:
      pass
  clear_pair_prompt_files(notify_cancel=True)
  for p in (PID_FILE, AGENT_READY_FILE, BT_STATE_FILE, CTRL_READY_FILE):
    try:
      if os.path.exists(p):
        os.unlink(p)
    except OSError:
      pass


def main():
  args = sys.argv[1:]
  async_ui = False
  if "--async-ui" in args:
    async_ui = True
    args = [a for a in args if a != "--async-ui"]
  cmd = args[0] if len(args) > 0 else "status"
  if cmd == "daemon":
    run_daemon()
  elif cmd == "start":
    ensure_daemon_running()
    return 0
  elif cmd == "stop":
    stop_daemon()
    return 0
  elif cmd == "dump-state":
    tsv = dump_bluez_state_tsv()
    if tsv:
      sys.stdout.write(tsv)
      return 0
    return 1
  elif cmd in ("connect", "pair"):
    if len(args) < 2:
      print(f"Usage: bananarchy-bt-obex {cmd} <MAC> [name]", file=sys.stderr)
      return 1
    mac = args[1]
    nm = args[2] if len(args) >= 3 else ""
    rc = connect_or_pair_bt_device(mac, nm, do_pair=(cmd == "pair"))
    if async_ui:
      ensure_obex_ipc_dir()
      safe_nm = str(nm or mac).replace("\t", " ").replace("\n", " ").strip()
      write_status(OP_DONE_FILE, f"{rc}\t{cmd}\t{mac.strip().upper()}\t{safe_nm}")
      notify_networks_ui("BT_OP_DONE\n")
    return rc
  elif cmd == "clear-linkkey":
    if len(args) < 2:
      return 1
    return 0 if clear_stale_linkkey(args[1]) else 1
  elif cmd == "send":
    if len(args) < 3:
      print("Usage: bananarchy-bt-obex send <MAC> <filepath>", file=sys.stderr)
      return 1
    return send_file_obex(args[1], args[2])
  elif cmd == "status":
    if os.path.exists(RX_STATUS_FILE):
      with open(RX_STATUS_FILE, "r", encoding="utf-8") as f:
        print(f.read().strip())
    else:
      print("IDLE\tReady (~/Downloads)")
    return 0
  return 0


if __name__ == "__main__":
  sys.exit(main())
