import shutil
import subprocess


def lsusb_lines():
    lsusb_bin = shutil.which("lsusb")
    if not lsusb_bin:
        return []
    try:
        proc = subprocess.run(
            [lsusb_bin], capture_output=True, text=True, timeout=15
        )
    except (OSError, subprocess.TimeoutExpired):
        return []
    if proc.returncode != 0 or not proc.stdout:
        return []
    return proc.stdout.splitlines()


def lsusb_new_devices(before_lines, after_lines):
    """Lines present in after but not before, excluding Acroname hub vendor lines."""
    before = set(before_lines)
    out = []
    for ln in after_lines:
        if ln in before:
            continue
        if "24ff:" in ln.lower():
            continue
        out.append(ln)
    return out


def lsusb_acroname_lines():
    try:
        lsusb_bin = shutil.which("lsusb")
        if not lsusb_bin:
            return []
        out = subprocess.run(
            [lsusb_bin],
            capture_output=True,
            text=True,
            timeout=5,
        )
        if out.returncode != 0 or not out.stdout:
            return []
        return [
            ln
            for ln in out.stdout.splitlines()
            if "24ff:" in ln.lower() or " acroname" in ln.lower()
        ]
    except (OSError, subprocess.TimeoutExpired):
        return []
