#!/bin/zsh
# chrome-pin-window — pin a Chrome/Edge window (the one containing a tab matching
# the given URL substring) to known screen position + size, so subsequent
# clicker-vnc / cliclick screen-coord clicks land predictably.
#
# Usage:
#   chrome-pin-window --url-contains URL [--browser chrome|edge]
#                                        [--x X] [--y Y] [--w W] [--h H]
#                                        [--no-activate] [--bring-to-front]
#
# Why this exists:
#   Multiple Chrome windows + user dragging + macOS Dock + multi-monitor
#   rearrange browser window positions over a session. clicker-vnc clicks
#   computed against an old window position miss their target. Pinning
#   normalizes the layout *without bringing the browser to the foreground* by
#   default (uses browser Apple Events, not System Events AX).
#
# Defaults:
#   --x 0  --y 0  --w 1600  --h 1200  (top-left, big enough to fit forms)
#
# Output (one line):
#   {"window_id": <chrome-internal-id>,
#    "tab_index": N,
#    "bounds_after": [x, y, w, h]}
set -euo pipefail

usage() {
  awk 'NR == 1 { next } /^set -/ { exit } { sub(/^# ?/, ""); print }' "${(%):-%x}"
}

x=0; y=0; w=1600; h=1200
url=""
activate=0      # by default DO NOT activate the browser (background)
front=0         # by default DO NOT raise the window inside the browser's stack
browser="Google Chrome"

normalize_browser() {
  local raw="${1:-Google Chrome}"
  local key="${raw:l}"
  key="${key// /-}"
  key="${key//_/-}"
  case "$key" in
    chrome|google-chrome|googlechrome) echo "Google Chrome" ;;
    edge|microsoft-edge|microsoftedge|msedge) echo "Microsoft Edge" ;;
    *) echo "$raw" ;;
  esac
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    --browser)       browser="$(normalize_browser "$2")"; shift 2;;
    --url-contains)  url="$2"; shift 2;;
    --x)             x="$2"; shift 2;;
    --y)             y="$2"; shift 2;;
    --w)             w="$2"; shift 2;;
    --h)             h="$2"; shift 2;;
    --activate)      activate=1; shift;;
    --no-activate)   activate=0; shift;;
    --bring-to-front) front=1; shift;;
    -h|--help)
      usage; exit 0;;
    *) echo "chrome-pin-window: unknown arg: $1" >&2; exit 2;;
  esac
done

if [[ -z "$url" ]]; then
  echo 'chrome-pin-window: --url-contains is required' >&2
  exit 2
fi

# x2/y2 are the bottom-right (Chrome AppleScript bounds expect 4-int form).
x2=$((x + w))
y2=$((y + h))

OSA=$(/usr/bin/mktemp)
trap "rm -f $OSA" EXIT
cat > "$OSA" <<OSAEOF
on run argv
  set targetUrl to item 1 of argv
  tell application "$browser"
    if $activate is 1 then activate
    set tIdx to 0
    set wIdx to 0
    repeat with theWindow in windows
      set wIdx to wIdx + 1
      set tIdx to 0
      repeat with theTab in tabs of theWindow
        set tIdx to tIdx + 1
        if URL of theTab contains targetUrl then
          if $front is 1 then
            set index of theWindow to 1
            set active tab index of theWindow to tIdx
          end if
          set bounds of theWindow to {$x, $y, $x2, $y2}
          set finalBounds to bounds of theWindow
          return "{\"window_id\": " & (id of theWindow) & ", \"tab_index\": " & tIdx & ", \"bounds_after\": [" & (item 1 of finalBounds) & ", " & (item 2 of finalBounds) & ", " & ((item 3 of finalBounds) - (item 1 of finalBounds)) & ", " & ((item 4 of finalBounds) - (item 2 of finalBounds)) & "]}"
        end if
      end repeat
    end repeat
    return "{\"error\": \"no tab matched url-contains\"}"
  end tell
end run
OSAEOF

/usr/bin/osascript "$OSA" "$url"
