#!/usr/bin/env bash
# Wrapper for ui-query scripts with proper nix dependencies
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# Detect which script to run
CMD="${1:-list-windows}"
shift || true

case "$CMD" in
    list-windows|list|ls)
        SCRIPT="list-windows.py"
        ;;
    get-text|text)
        SCRIPT="get-text.py"
        ;;
    find-element|find|search)
        SCRIPT="find-element.py"
        ;;
    query-state|state)
        SCRIPT="query-state.py"
        ;;
    *)
        echo "Usage: ui-query <command> [options]"
        echo ""
        echo "Commands:"
        echo "  list-windows   List all AT-SPI accessible windows"
        echo "  get-text       Extract text content from a window"
        echo "  find-element   Find elements by role or name"
        echo "  query-state    Query element states in detail"
        echo ""
        echo "Options are passed through to the underlying script."
        exit 1
        ;;
esac

# Quote arguments properly for passing through --run
QUOTED_ARGS=""
for arg in "$@"; do
    printf -v ESCAPED '%q' "$arg"
    QUOTED_ARGS="$QUOTED_ARGS $ESCAPED"
done

exec nix-shell -p "python3.withPackages (ps: [ ps.pyatspi ps.pygobject3 ])" \
    at-spi2-core gobject-introspection \
    --run "python3 '$SCRIPT_DIR/$SCRIPT'$QUOTED_ARGS"
