"""Bluetooth via bluetoothctl (BlueZ). UI-frei.

Power an/aus, Geräte (paired/connected/discovered), connect/disconnect, scan.
bluetoothctl-Einzelkommandos laufen one-shot. Für den aktiven User ohne root.
Schreib-Aktionen liefern argv (Aufrufer führt via ProcessRunner aus).
"""
from __future__ import annotations

import subprocess
from dataclasses import dataclass


def _run(args: list[str], timeout: int = 6) -> str:
    try:
        r = subprocess.run(["bluetoothctl", *args], capture_output=True,
                           text=True, check=False, timeout=timeout)
        return r.stdout if r.returncode == 0 else r.stdout
    except (FileNotFoundError, subprocess.TimeoutExpired):
        return ""


def available() -> bool:
    return bool(_run(["show"]))


def powered() -> bool:
    for line in _run(["show"]).splitlines():
        if "Powered:" in line:
            return line.split(":", 1)[1].strip() == "yes"
    return False


def set_power_argv(on: bool) -> list[str]:
    return ["bluetoothctl", "power", "on" if on else "off"]


def scan_argv(seconds: int = 8) -> list[str]:
    return ["bluetoothctl", "--timeout", str(seconds), "scan", "on"]


@dataclass
class BtDevice:
    mac: str
    name: str
    paired: bool
    connected: bool
    trusted: bool = False


def _macs(args: list[str]) -> set[str]:
    macs: set[str] = set()
    for line in _run(args).splitlines():
        parts = line.split()
        if len(parts) >= 2 and parts[0] == "Device":
            macs.add(parts[1])
    return macs


def devices() -> list[BtDevice]:
    paired = _macs(["devices", "Paired"])
    connected = _macs(["devices", "Connected"])
    trusted = _macs(["devices", "Trusted"])
    out: list[BtDevice] = []
    seen: set[str] = set()
    for line in _run(["devices"]).splitlines():
        parts = line.split(maxsplit=2)
        if len(parts) >= 2 and parts[0] == "Device":
            mac = parts[1]
            if mac in seen:
                continue
            seen.add(mac)
            name = parts[2] if len(parts) > 2 else mac
            out.append(BtDevice(
                mac=mac, name=name,
                paired=mac in paired, connected=mac in connected,
                trusted=mac in trusted,
            ))
    # Verbundene/gepairte zuerst
    return sorted(out, key=lambda d: (not d.connected, not d.paired, d.name.lower()))


def connect_argv(mac: str) -> list[str]:
    return ["bluetoothctl", "connect", mac]


def disconnect_argv(mac: str) -> list[str]:
    return ["bluetoothctl", "disconnect", mac]


def pair_argv(mac: str) -> list[str]:
    return ["bluetoothctl", "pair", mac]


def trust_argv(mac: str) -> list[str]:
    return ["bluetoothctl", "trust", mac]


def remove_argv(mac: str) -> list[str]:
    return ["bluetoothctl", "remove", mac]
