#!/bin/zsh
# ax-file-picker — click a target to open NSOpenPanel, then navigate the
# file picker dialog via AX (System Events) to select a file.
#
# Usage:
#   ax-file-picker --app "Google Chrome" --click-x X --click-y Y --path /path/to/file
#
# Prerequisites: osascript must have Accessibility permission (System Settings → Accessibility).
#
# Flow:
#   1. Activate the target app + click at (X, Y) to trigger file picker
#   2. Wait up to 5s for an NSOpenPanel sheet to appear (AXSheet role)
#   3. Type Cmd+Shift+G to open "Go to Folder" dialog
#   4. Type the folder path + filename
#   5. Press Enter to navigate, then Enter to select
set -euo pipefail

app=""
click_x=""
click_y=""
file_path=""

while [[ $# -gt 0 ]]; do
  case "$1" in
    --app)     app="$2"; shift 2;;
    --click-x) click_x="$2"; shift 2;;
    --click-y) click_y="$2"; shift 2;;
    --path)    file_path="$2"; shift 2;;
    -h|--help) sed -n '2,15p' "$0"; exit 0;;
    *) echo "ax-file-picker: unknown arg: $1" >&2; exit 2;;
  esac
done

if [[ -z "$app" || -z "$click_x" || -z "$click_y" || -z "$file_path" ]]; then
  echo 'ax-file-picker: --app, --click-x, --click-y, --path are all required' >&2
  exit 2
fi

if [[ ! -f "$file_path" ]]; then
  echo "ax-file-picker: file not found: $file_path" >&2
  exit 2
fi

ABS_PATH=$(/usr/bin/python3 -c "import os,sys; print(os.path.abspath(sys.argv[1]))" "$file_path")

echo "[ax-file-picker] clicking ($click_x, $click_y) on $app to open file picker"

/usr/bin/osascript <<OSA
tell application "System Events"
  tell process "$app"
    set frontmost to true
    delay 0.5
    click at {$click_x, $click_y}
  end tell
end tell
OSA

echo "[ax-file-picker] waiting for file picker sheet..."
/bin/sleep 2

# Copy file path to clipboard
echo -n "$ABS_PATH" | /usr/bin/pbcopy

echo "[ax-file-picker] driving Go to Folder: $ABS_PATH"

/usr/bin/osascript <<OSA
tell application "System Events"
  tell process "$app"
    -- Cmd+Shift+G to open Go to Folder
    keystroke "g" using {command down, shift down}
    delay 1.5
    -- Cmd+A to select all existing text
    keystroke "a" using {command down}
    delay 0.3
    -- Cmd+V to paste path
    keystroke "v" using {command down}
    delay 1
    -- Enter to navigate to the file
    key code 36
    delay 2
    -- Enter to select the file
    key code 36
  end tell
end tell
OSA

echo "[ax-file-picker] done"
