#!/usr/bin/env bash

set -euo pipefail

fail() {
    printf 'overview live actions: %s\n' "$1" >&2
    exit 1
}

original_workspace="$(hyprctl -j activeworkspace | jq -r '.id')"
address=""

cleanup() {
    qs ipc call overview close >/dev/null 2>&1 || true
    if [[ -n "$address" ]] && hyprctl -j clients | jq -e --arg address "$address" '.[] | select(.address == $address)' >/dev/null; then
        hyprctl dispatch "hl.dsp.window.close({ window = \"address:$address\" })" >/dev/null 2>&1 || true
    fi
    hyprctl dispatch "hl.dsp.focus({ workspace = $original_workspace })" >/dev/null 2>&1 || true
}
trap cleanup EXIT

kitty --class panama-overview-contract --title "Panama Overview Contract" sh -c 'exec sleep 300' >/dev/null 2>&1 &

for _ in $(seq 1 40); do
    address="$(hyprctl -j clients | jq -r '.[] | select(.class == "panama-overview-contract") | .address' | head -1)"
    [[ -n "$address" ]] && break
    sleep 0.1
done
[[ -n "$address" ]] || fail 'disposable window did not appear'

target_workspace="$(hyprctl -j workspaces | jq -r --argjson current "$original_workspace" '[.[] | select(.id > 0 and .id != $current)][0].id // empty')"
if [[ -z "$target_workspace" ]]; then
    target_workspace=$((original_workspace + 1))
fi

qs ipc call overview-actions move "$address" "$target_workspace" >/dev/null
sleep 0.25
[[ "$(hyprctl -j clients | jq -r --arg address "$address" '.[] | select(.address == $address) | .workspace.name')" == "$target_workspace" ]] \
    || fail 'exact-address workspace move failed'

qs ipc call overview-actions move "$address" special:scratch >/dev/null
sleep 0.25
[[ "$(hyprctl -j clients | jq -r --arg address "$address" '.[] | select(.address == $address) | .workspace.name')" == "special:scratch" ]] \
    || fail 'exact-address scratchpad move failed'

qs ipc call overview open >/dev/null
sleep 0.2
qs ipc call overview-actions restore "$address" >/dev/null
sleep 0.3
[[ "$(hyprctl -j clients | jq -r --arg address "$address" '.[] | select(.address == $address) | .workspace.id')" == "$original_workspace" ]] \
    || fail 'scratchpad restore did not return to the selected workspace'

qs ipc call overview-actions close "$address" >/dev/null
for _ in $(seq 1 30); do
    if ! hyprctl -j clients | jq -e --arg address "$address" '.[] | select(.address == $address)' >/dev/null; then
        address=""
        trap - EXIT
        cleanup
        printf 'overview live actions: PASS\n'
        exit 0
    fi
    sleep 0.1
done

fail 'exact-address close did not close the disposable window'
