#!/usr/bin/env python3
# summary: Read and manage Bluetooth devices.
"""Bluetooth actions shared by Settings and Quick settings; JSON lines report progress and errors."""
import contextlib
import fcntl
import json
import os
import pty
import re
import select
import signal
import subprocess
import sys
import time
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
from starchaser_cli import safe_streams

safe_streams()

ADAPTER = "org.bluez.Adapter1"
DEVICE = "org.bluez.Device1"


class BluetoothError(Exception):
    pass


class Canceled(Exception):
    pass


def report(**fields):
    print(json.dumps(fields), flush=True)


def bus(*args, timeout=15):
    try:
        result = subprocess.run(["busctl", "--system", f"--timeout={timeout}", *args],
                                capture_output=True, text=True, timeout=timeout + 2)
    except subprocess.TimeoutExpired as e:
        raise BluetoothError("Timed out") from e
    if result.returncode:
        raise BluetoothError(result.stderr.strip())
    return result.stdout.strip()


def get(path, interface, prop):
    return bus("get-property", "org.bluez", path, interface, prop) == "b true"


def set_pairable(adapter, value):
    bus("set-property", "org.bluez", adapter, ADAPTER, "Pairable", "b", str(value).lower())


def call(path, method, timeout=15):
    return bus("call", "org.bluez", path, DEVICE, method, timeout=timeout)


@contextlib.contextmanager
def pairing_guard(adapter, path, original):
    # Quickshell kills a Process when its page is destroyed. A small child holds the same adapter lock and
    # watches this pipe, so even SIGKILL cannot skip CancelPairing and leave Pairable enabled.
    reader, writer = os.pipe()
    pid = os.fork()
    if pid == 0:
        os.close(writer)
        signal.signal(signal.SIGTERM, signal.SIG_IGN)
        signal.signal(signal.SIGINT, signal.SIG_IGN)
        try:
            if os.read(reader, 1) != b"1":
                try:
                    call(path, "CancelPairing")
                except BluetoothError:
                    pass
                if not original:
                    set_pairable(adapter, False)
        except (BluetoothError, OSError):
            pass  # the adapter may have been unplugged along with the closing page
        finally:
            os._exit(0)
    os.close(reader)
    try:
        yield
    finally:
        os.write(writer, b"1")
        os.close(writer)
        os.waitpid(pid, 0)


def connect(path, progress=report):
    # Speakers often drop the temporary pairing connection before accepting A2DP. A successful Connect reply
    # alone is not enough: allow that drop to arrive, then check the device and retry once.
    for attempt in range(2):
        progress(status="Connecting…" if attempt == 0 else "Trying again…")
        try:
            call(path, "Connect", timeout=30)
            time.sleep(1)
            if get(path, DEVICE, "Connected"):
                return
            raise BluetoothError("Disconnected")
        except BluetoothError:
            if attempt:
                raise
            time.sleep(1)


def agent_question(text, complete=True):
    # PTY reads can end anywhere, including halfway through the code. Interactive prompts have no newline;
    # their closing colon (or a full six-digit display passkey) tells us when the last line is ready.
    if not complete and not re.search(
            r"\(yes/no\):\s*$|(?:Enter|Request) (?:PIN code|passkey)(?: \([^\n)]*\))?:\s*$"
            r"|Passkey:\s*\d{6}\s*$", text):
        return None
    code = re.search(r"(?:Confirm passkey|Passkey:|PIN code:)\s*(\d{4,16})", text, re.I)
    if "Confirm passkey" in text and code:
        return {"kind": "confirm", "text": "Does your device show this code?", "code": code.group(1)}
    if re.search(r"(?:Passkey:|PIN code:)", text, re.I) and code:
        return {"kind": "display", "text": "Type " + code.group(1) + " on your Bluetooth keyboard, then press Enter."}
    if "Enter PIN code" in text or "Request PIN code" in text:
        return {"kind": "pin", "text": "Enter the code shown on your Bluetooth device."}
    if "Enter passkey" in text or "Request passkey" in text:
        return {"kind": "passkey", "text": "Enter the code shown on your Bluetooth device."}
    if "(yes/no)" in text and ("Authorize" in text or "Confirm" in text):
        return {"kind": "confirm", "text": "Allow this Bluetooth pairing?"}
    return None


def pair_with_agent(path, progress=report):
    """Pair on the same BlueZ connection that exports the agent; no terminal or globally replaced default agent."""
    address = path.rsplit('/dev_', 1)[1].replace('_', ':')
    raw_address = bus('get-property', 'org.bluez', path.rsplit('/', 1)[0], ADAPTER, 'Address')
    controller = re.search(r'"((?:[0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2})"', raw_address)
    if not controller:
        raise BluetoothError('Adapter not available')
    adapter = controller.group(1)
    master, slave = pty.openpty()
    process = subprocess.Popen(['bluetoothctl', '--agent', 'KeyboardDisplay'], stdin=slave, stdout=slave, stderr=slave)
    os.close(slave)
    started, buffer, question, deadline = False, '', None, time.monotonic() + 90
    try:
        while time.monotonic() < deadline:
            readers = [master] + ([sys.stdin] if question and question['kind'] != 'display' else [])
            ready, _, _ = select.select(readers, [], [], 1)
            if sys.stdin in ready:
                answer = sys.stdin.readline().strip()
                if question['kind'] == 'confirm':
                    if answer not in ('yes', 'no'):
                        raise Canceled()
                elif not re.fullmatch(r'[0-9]{1,6}' if question['kind'] == 'passkey' else r'[ -~]{1,16}', answer):
                    raise Canceled()
                os.write(master, (answer + '\n').encode())
                if answer == 'no':
                    raise Canceled()
                question = None
                progress(challenge=None)
            if master not in ready:
                if process.poll() is not None:
                    raise BluetoothError('Agent stopped')
                continue
            try:
                data = os.read(master, 65536).decode(errors='replace')
            except OSError as error:
                raise BluetoothError('Agent stopped') from error
            buffer += data
            buffer = re.sub(r'\x1b\[[0-?]*[ -/]*[@-~]', '', buffer).replace('\r', '\n')
            if not started and 'Agent registered' in buffer:
                os.write(master, ('select ' + adapter + '\npair ' + address + '\n').encode())
                started = True
                buffer = ''
            if 'Pairing successful' in buffer:
                progress(challenge=None)
                return
            if 'Failed to pair' in buffer or 'AuthenticationFailed' in buffer:
                raise BluetoothError('Authentication failed')
            lines = buffer.split('\n')
            latest = next((q for i in range(len(lines) - 1, -1, -1)
                           if (q := agent_question(lines[i], complete=i < len(lines) - 1))), None)
            if latest and latest != question:
                question = latest
                progress(challenge=question)
                buffer = ''
            if len(buffer) > 16384:
                buffer = buffer[-4096:]
        raise BluetoothError('Pairing timed out')
    finally:
        progress(challenge=None)
        process.terminate()
        try:
            process.wait(timeout=3)
        except subprocess.TimeoutExpired:
            process.kill()
            process.wait()
        os.close(master)


def operate(action, path, progress=report):
    adapter = path.rsplit("/", 1)[0]
    if not get(adapter, ADAPTER, "Powered"):
        raise BluetoothError("NotReady")
    if action == "pair":
        original = get(adapter, ADAPTER, "Pairable")
        with pairing_guard(adapter, path, original):
            pairing = False
            try:
                progress(status="Pairing…")
                if not original:
                    set_pairable(adapter, True)
                pairing = True
                try:
                    pair_with_agent(path, progress)
                except BluetoothError:
                    # Some speakers finish bonding but disconnect before Pair's reply reaches us.
                    if not get(path, DEVICE, "Paired"):
                        raise
                pairing = False
            finally:
                # Finish cleanup even if Cancel is pressed twice or the page closes during cancellation.
                old = signal.signal(signal.SIGTERM, signal.SIG_IGN)
                try:
                    if pairing:
                        try:
                            call(path, "CancelPairing")
                        except BluetoothError:
                            pass
                    if not original:
                        try:
                            set_pairable(adapter, False)
                        except BluetoothError as e:
                            raise BluetoothError("RestorePairable") from e
                finally:
                    signal.signal(signal.SIGTERM, old)
        progress(status="Trusting…")
        bus("set-property", "org.bluez", path, DEVICE, "Trusted", "b", "true")
        connect(path, progress)
    elif action == "connect":
        connect(path, progress)
    elif action == "disconnect":
        progress(status="Disconnecting…")
        call(path, "Disconnect")
    else:
        progress(status="Forgetting…")
        bus("call", "org.bluez", adapter, ADAPTER, "RemoveDevice", "o", path)


def explanation(error, action, status):
    text = str(error).lower()
    if "restorepairable" in text:
        return "Couldn't restore Bluetooth pairing settings. Turn Bluetooth off and back on."
    if "notready" in text or "not ready" in text:
        return "Bluetooth is off. Turn it on and try again."
    if "notauthorized" in text or "access denied" in text or "not authorized" in text:
        return "Bluetooth permission was denied. Sign out and back in, then try again."
    if "rejected" in text or "refused" in text or "authentication" in text:
        return "The device refused the connection. Put it in pairing mode and try again."
    if action == "pair" and status == "Pairing…":
        return "Couldn't pair. Put the device in pairing mode and try again."
    if status == "Trusting…":
        return "Paired, but couldn't allow this device to reconnect. Forget it, then pair again."
    if action in ("pair", "connect"):
        return "Couldn't connect. Make sure the device is on and nearby. If another device is using it, disconnect it there or put it in pairing mode."
    return "Couldn't disconnect the device. Try again." if action == "disconnect" else "Couldn't forget the device. Try again."


def main():
    sys.path.insert(0, str(Path(__file__).resolve().parent))
    from starchaser_cli import CommandParser  # the shared "Usage:" heading and help style
    parser = CommandParser(description=__doc__, epilog=
        "For normal pairing, open Settings > Bluetooth and choose your device by name. "
        "This helper accepts a system device path, not a device name or address. "
        "To find paths for advanced use, run 'busctl --system tree org.bluez'. "
        "Example: starchaser bluetooth connect /org/bluez/hci0/dev_11_22_33_44_55_66")
    parser.add_argument("command", choices=("pair", "connect", "disconnect", "forget"))
    parser.add_argument("device", help="system device path (see the example below)")
    args = parser.parse_args()
    if not re.fullmatch(r"/org/bluez/hci[0-9]+/dev_(?:[0-9A-Fa-f]{2}_){5}[0-9A-Fa-f]{2}", args.device):
        parser.error("invalid Bluetooth device path")

    def cancel(*_):
        raise Canceled()

    signal.signal(signal.SIGTERM, cancel)
    signal.signal(signal.SIGINT, cancel)
    # Serialize per adapter across both UIs: one attempt must not restore Pairable under another.
    runtime = Path(os.environ.get("XDG_RUNTIME_DIR", f"/run/user/{os.getuid()}"))
    status = ""

    def progress(**fields):
        nonlocal status
        status = fields.get("status", status)
        report(**fields)

    try:
        with (runtime / f"starchaser-bluetooth-{args.device.split('/')[3]}.lock").open("w") as lock:
            try:
                fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
            except BlockingIOError:
                report(error="Another Bluetooth action is in progress. Wait for it to finish.", done=True)
                return 1
            operate(args.command, args.device, progress)
        report(status="Forgotten" if args.command == "forget" else "Disconnected" if args.command == "disconnect" else "Connected", done=True)
        return 0
    except Canceled:
        report(status="Canceled", done=True)
        return 0
    except (BluetoothError, OSError) as e:
        report(error=explanation(e, args.command, status), done=True)
        return 1


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