#!/bin/zsh
# Select an AirPlay target for the currently playing Safari HTML video.
# Usage: safari-airplay [exact device name]
set -euo pipefail
TARGET="${1:-43in MAGNAVOX Roku TV}"
for attempt in 1 2 3 4 5; do
  if result=$(/usr/bin/osascript - "$TARGET" 2>&1 <<'APPLESCRIPT'
on run argv
  set targetName to item 1 of argv
  tell application "Safari"
    if (count of windows) = 0 then error "Safari has no open windows"
    activate
    set resultText to do JavaScript "(()=>{let v=[...document.querySelectorAll('video')].find(x=>!x.paused)||document.querySelector('video');if(!v)return 'NO_VIDEO';if(typeof v.webkitShowPlaybackTargetPicker!=='function')return 'NO_AIRPLAY';v.webkitShowPlaybackTargetPicker();return 'PICKER_REQUESTED'})()" in current tab of front window
    if resultText is not "PICKER_REQUESTED" then error resultText
  end tell
  tell application "System Events"
    tell process "Safari"
      set matched to false
      repeat 35 times
        try
          set deviceRows to rows of table 1 of scroll area 1 of pop over 1 of window 1
          repeat with deviceRow in deviceRows
            try
              set itemName to value of static text 1 of UI element 1 of deviceRow
              if itemName is targetName then
                set selectedBox to checkbox 1 of UI element 1 of deviceRow
                if (value of selectedBox as integer) is not 1 then click selectedBox
                set matched to true
                exit repeat
              end if
            end try
          end repeat
          if matched then exit repeat
        end try
        delay 0.2
      end repeat
      if not matched then error "AirPlay target not found: " & targetName
    end tell
  end tell
  repeat 20 times
    delay 0.5
    tell application "Safari"
      set wireless to do JavaScript "String([...document.querySelectorAll('video')].some(v=>!v.paused&&v.webkitCurrentPlaybackTargetIsWireless))" in current tab of front window
    end tell
    if wireless is "true" then return "CONNECTED: " & targetName
  end repeat
  error "Selected target but wireless playback not confirmed: " & targetName
end run
APPLESCRIPT
  ); then
    print -r -- "$result"
    exit 0
  fi
  print -u2 -- "AirPlay attempt $attempt failed: $result"
  sleep 2
done
exit 1
