#!/usr/bin/env python3
"""List and activate regular X11 windows. The desktop session itself isn't an app tab."""
import subprocess
import sys


def windows():
    try:
        result = subprocess.run(['wmctrl', '-l'], capture_output=True, text=True, check=True)
    except (OSError, subprocess.CalledProcessError):
        return []
    items = []
    for line in result.stdout.splitlines():
        parts = line.split(None, 3)
        if len(parts) < 4:
            continue
        wid, desktop, host, title = parts
        if title == 'AppendHub Desktop' or title.startswith('AppendHub Desktop —'):
            continue
        if desktop == '-1' and not title:
            continue
        items.append((wid, title))
    return items


def main():
    args = sys.argv[1:]
    items = windows()
    if not args or args == ['list']:
        if not items:
            print('No graphical app windows open.')
        for i, (_, title) in enumerate(items, 1):
            print(f'  [{i}] {title}')
        return 0
    if args == ['compact']:
        if items:
            print('  APPS  ' + '  |  '.join(f'[{i}] {t[:32]}' for i, (_, t) in enumerate(items, 1)))
        return 0
    if len(args) == 2 and args[0] == 'switch':
        try:
            num = int(args[1])
            wid = items[num - 1][0] if 1 <= num <= len(items) else None
        except ValueError:
            wid = None
        if wid is None:
            print('Use brack-tabs to see valid app numbers.', file=sys.stderr)
            return 2
        result = subprocess.run(['wmctrl', '-ia', wid], check=False)
        return result.returncode
    print('Usage: brack-tabs | brack-switch NUMBER', file=sys.stderr)
    return 2


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