#!/bin/bash
# Usage: FLEA_BIN=target/release/flea dbus-run-session -- tools/flea-live-ops, which drives this run's own GPUI window.
set -u
# This tool parses machine output, so it runs whole in the C locale the locale audit accepts.
export LC_ALL=C.UTF-8
unset LANGUAGE
REPO=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
# Hard rule 9's guard, which owns FIXTURE_ROOT and every create and delete below.
. "$REPO/tools/flea-sandbox-guard"
. "$REPO/tools/flea-ipc"
. "$REPO/tests/lib/flea-transport.sh"
export FLEA_BIN=${FLEA_BIN:-$REPO/target/release/flea}
export FLEA_GUI_BIN=${FLEA_GUI_BIN:-${FLEA_BIN%/*}/flea-gui}
export FLEA_TEST_FRONTEND=gpui
# Teardown stops every window under this root, so one inherited from a caller is never trusted.
unset FLEA_TEST_WINDOWS_ROOT
export PATH="$HOME/.local/bin:$PATH"
fail=0
die() { printf 'flea-live-ops: %s\n' "$*" >&2; exit 2; }

[ -x "$FLEA_BIN" ] && [ -x "$FLEA_GUI_BIN" ] || die "build flea and flea-gui first: $FLEA_BIN $FLEA_GUI_BIN"
FLEA_BIN=$(realpath -e "$FLEA_BIN") || die "candidate backend cannot be resolved"
FLEA_GUI_BIN=$(realpath -e "$FLEA_GUI_BIN") || die "candidate GUI cannot be resolved"
flea_ipc_init "$FLEA_BIN" gpui
# Delete moves to Trash, which must land in this run's own data home on its own session bus.
case "${DBUS_SESSION_BUS_ADDRESS:-}" in
  ''|*"/run/user/$(id -u)/bus"*) die "run under dbus-run-session, so the Trash this battery fills is a private one" ;;
esac

RUN="$FIXTURE_ROOT/flea-live-ops"
SB="$RUN/fixture"
FLEA_PID=""
WINDOW=""
q() { LC_ALL=C.UTF-8 LANGUAGE= flea_ipc_call --pid "$FLEA_PID" call flea "$@" 2>/dev/null; }

# Pressing Return on a row hands the file to the default handler, and that handler outlives this
# script: three xdg-open and nvim pairs were still resident seventeen hours later, holding the load
# average up high enough to refuse a field run. A test that leaves a process behind is a test that
# changes the box it measures.
#
# Matched on the whole command line rather than by a pattern, and every process this script descends
# from is excluded first, so it can never reap its own caller.
reap_handlers() {
  local pid rest p ancestors=" $$ "
  p=$$
  while [ "${p:-1}" -gt 1 ]; do
    p=$(LC_ALL=C.UTF-8 LANGUAGE= grep '^PPid:' "/proc/$p/status" 2>/dev/null | LC_ALL=C.UTF-8 LANGUAGE= tr -d ' \t' | cut -d: -f2)
    [ -n "$p" ] || break
    ancestors="$ancestors$p "
  done
  while read -r pid rest; do
    case "$ancestors" in *" $pid "*) continue ;; esac
    case "$rest" in
      *" $SB/"*) kill "$pid" 2>/dev/null ;;
    esac
  done < <(LC_ALL=C.UTF-8 LANGUAGE= ps -eo pid=,args=)
}

check() {
  local label="$1" expected="$2" actual="$3"
  if [ "$expected" != "$actual" ]; then
    echo "FAIL $label"
    echo "  expected: $expected"
    echo "  actual:   $actual"
    fail=1
  else
    echo "ok   $label"
  fi
}

# The one compositor client this run's pid owns; two Flea windows share a class, so the pid is the identity.
window_of_pid() {
  hyprctl clients -j 2>/dev/null | jq -er --argjson pid "$FLEA_PID" \
    '[.[] | select(.class == "com.thisisgm.flea" and .pid == $pid)] | select(length == 1) | .[0].address'
}

# Every key goes to this run's own window address, so a second Flea on the box never receives one.
press() { LC_ALL=C.UTF-8 LANGUAGE= omarchy-drive key --window "$WINDOW" -k "$1" >/dev/null 2>&1 || die "key delivery failed: $1"; sleep 0.5; }
typek() { LC_ALL=C.UTF-8 LANGUAGE= omarchy-drive key --window "$WINDOW" "$1" >/dev/null 2>&1 || die "text delivery failed"; sleep 0.4; }
listing() { LC_ALL=C.UTF-8 LANGUAGE= ls "$SB" | LC_ALL=C.UTF-8 LANGUAGE= tr '\n' ' '; }

# rowCentre answers in window coordinates, and a Wayland client is never told where its surface is,
# so the window origin is added here exactly as tests/ui.sh's own click_row does.
click_row() {
  local index="$1" button="$2" cx cy wx wy
  read -r cx cy <<< "$(q rowCentre "$index")"
  read -r wx wy <<< "$(hyprctl clients -j | jq -r --arg a "$WINDOW" '.[] | select(.address == $a) | "\(.at[0]) \(.at[1])"')"
  [[ "$cx $cy" =~ ^[0-9]+\ [0-9]+$ && "$wx $wy" =~ ^-?[0-9]+\ -?[0-9]+$ ]] || die "owned row click has no measured target"
  LC_ALL=C.UTF-8 LANGUAGE= omarchy-drive click "$((cx + wx))" "$((cy + wy))" "$button" >/dev/null 2>&1 || die "owned row click failed"
}

# The cursor goes to the top first and then walks down, because a row the sort puts above the cursor
# is otherwise unreachable and the check that follows would pass vacuously against an untouched file.
seek_row() {
  local want="$1" i
  press g
  for i in $(seq 1 30); do
    case "$(q rowAt "$(q cursor)")" in "$want|"*) return 0 ;; esac
    press j
  done
  echo "  could not reach row: $want"
  return 1
}

# The status line takes a moment after the key, so a receipt is read when it arrives or when the wait ends.
message() {
  local want="$1" seen i
  for i in $(seq 1 40); do
    seen=$(q lastMessage)
    [ "$seen" = "$want" ] && break
    sleep 0.1
  done
  printf '%s' "$seen"
}

teardown() {
  local status=$?
  trap - EXIT
  if [ -n "${FLEA_TEST_WINDOWS_ROOT:-}" ]; then
    flea_test_stop_all >/dev/null 2>&1 || status=1
    python3 -B "$REPO/tests/lib/flea_live_ops_cleanup.py" "$RUN" "$FLEA_BIN" || status=1
  fi
  reap_handlers
  exit "$status"
}
trap teardown EXIT

sandbox_make "$RUN"
sandbox_scratch "$SB"
mkdir -p "$SB/dest" "$SB/subdir" || exit 1
printf 'alpha body' > "$SB/alpha.txt"
printf 'beta body'  > "$SB/beta.txt"
printf 'gamma body' > "$SB/gamma.txt"
printf 'inside'     > "$SB/subdir/inner.txt"
# Settings, Trash and the undo journal all stay inside the run, never the operator's own.
export XDG_STATE_HOME="$RUN/state" XDG_DATA_HOME="$RUN/data" XDG_CACHE_HOME="$RUN/cache" XDG_CONFIG_HOME="$RUN/config" FLEA_UNDO_DIR="$RUN/undo"
mkdir -p "$XDG_STATE_HOME" "$XDG_DATA_HOME" "$XDG_CACHE_HOME" "$XDG_CONFIG_HOME" || exit 1
mkdir -m 700 "$FLEA_UNDO_DIR" || exit 1
export FLEA_TEST_WINDOWS_ROOT="$RUN/windows"
mkdir -m 700 "$FLEA_TEST_WINDOWS_ROOT" || exit 1
: > "$FLEA_TEST_WINDOWS_ROOT/$SANDBOX_MARKER"
echo "binaries: $(sha256sum "$FLEA_BIN" | cut -c1-12) flea, $(sha256sum "$FLEA_GUI_BIN" | cut -c1-12) flea-gui"

flea_test_launch "$SB" "$RUN/flea.log" --binary "$FLEA_BIN" || die "owned window launch failed"
FLEA_PID=$FLEA_TEST_PID
flea_ipc_wait --pid "$FLEA_PID" flea ready true --timeout 20 || die "the window never answered ready"
for i in $(seq 1 100); do WINDOW=$(window_of_pid) && break; sleep 0.1; done
[ -n "$WINDOW" ] || die "pid $FLEA_PID never mapped one window"
LC_ALL=C.UTF-8 LANGUAGE= omarchy-drive focus "$WINDOW" >/dev/null 2>&1; sleep 0.5
check "the app came up on the fixture" "$SB" "$(q path)"

echo "--- rename through r, and z puts it back ---"
seek_row "alpha.txt" || fail=1
press r
typek "renamed"
press Return
sleep 0.8
check "the new name is on disk" "yes" "$([ -f "$SB/renamed.txt" ] && echo yes || echo no)"
check "the old name is gone" "no" "$([ -e "$SB/alpha.txt" ] && echo yes || echo no)"
check "the bytes survived the rename" "alpha body" "$(cat "$SB/renamed.txt")"
check "committing the rename did not also open the row" "" "$(q lastMessage)"
check "the cursor followed the renamed row" "renamed.txt" "$(q rowAt "$(q cursor)" | cut -d'|' -f1)"
press z
sleep 0.8
check "z undid the rename" "yes" "$([ -f "$SB/alpha.txt" ] && echo yes || echo no)"
check "and took the new name away" "no" "$([ -e "$SB/renamed.txt" ] && echo yes || echo no)"
check "the bar said what it reversed" "Undid the rename" "$(message "Undid the rename")"

echo "--- trash through Delete, with no confirmation, and z restores ---"
seek_row "gamma.txt" || fail=1
press Delete
sleep 1.2
check "the row left the directory" "no" "$([ -e "$SB/gamma.txt" ] && echo yes || echo no)"
check "the item is in this run's own Trash" "gamma body" "$(cat "$XDG_DATA_HOME/Trash/files/gamma.txt" 2>/dev/null)"
check "the bar named the reversal" "Moved 1 item to Trash · z undoes" "$(message "Moved 1 item to Trash · z undoes")"
press z
sleep 1.5
check "z restored it from the trash" "gamma body" "$(cat "$SB/gamma.txt" 2>/dev/null)"
check "the bar said so" "Put it back from Trash." "$(message "Put it back from Trash.")"

echo "--- cut with x, paste with p in another directory, and z moves it back ---"
seek_row "beta.txt" || fail=1
press x
sleep 0.8
check "the clipboard reports what it took" "Cut 1 item · p pastes" "$(message "Cut 1 item · p pastes")"
seek_row "dest" || fail=1
press Return
sleep 1.0
check "the pane is in the destination" "$SB/dest" "$(q path)"
press p
sleep 1.5
check "the file landed in the destination" "beta body" "$(cat "$SB/dest/beta.txt" 2>/dev/null)"
check "and left its old directory" "no" "$([ -e "$SB/beta.txt" ] && echo yes || echo no)"
# The verb comes off the wire now. Reading it from the clipboard reported every move as a copy,
# because paste spends a cut before transferstarted arrives.
check "the bar called it a move, not a copy" "Moved 1 item · z undoes" "$(message "Moved 1 item · z undoes")"
check "and the sticky slot is clear once the operation ends" "" "$(q stickyMessage)"
press z
sleep 1.2
check "z moved it back where it came from" "beta body" "$(cat "$SB/beta.txt" 2>/dev/null)"
check "and took it out of the destination" "no" "$([ -e "$SB/dest/beta.txt" ] && echo yes || echo no)"

echo "--- copy with y, paste with p, and the same slot says copy ---"
# The cut case above left the pane inside dest, so this one climbs out before it looks for a row.
press BackSpace
sleep 1.2
check "the copy case starts in the parent directory" "$SB" "$(q path)"
seek_row "gamma.txt" || fail=1
press y
sleep 0.8
check "the clipboard reports a copy" "Copied 1 item · p pastes" "$(message "Copied 1 item · p pastes")"
seek_row "dest" || fail=1
press Return
sleep 1.0
press p
sleep 1.5
check "the copy landed in the destination" "gamma body" "$(cat "$SB/dest/gamma.txt" 2>/dev/null)"
check "and the source is still there" "gamma body" "$(cat "$SB/gamma.txt" 2>/dev/null)"
check "the bar called it a copy" "Copied 1 item · z undoes" "$(message "Copied 1 item · z undoes")"
press z
sleep 1.2
check "z removed only the copy" "no" "$([ -e "$SB/dest/gamma.txt" ] && echo yes || echo no)"

echo "--- duplicate through the context menu, and z removes only the copy ---"
press BackSpace
sleep 1.2
check "backspace returned to the parent directory" "$SB" "$(q path)"
seek_row "beta.txt" || fail=1
check "the cursor is on the row the menu will open on" "beta.txt" "$(q rowAt "$(q cursor)" | cut -d'|' -f1)"
# Right click the row, then pick the entry: this is the only path in the battery that goes through
# the menu rather than a key, because Duplicate is deliberately not bound to one.
LC_ALL=C.UTF-8 LANGUAGE= omarchy-drive focus "$WINDOW" >/dev/null 2>&1
sleep 0.5
click_row "$(q cursor)" right
sleep 1.0
check "the menu opened on the row" "true" "$(q contextMenuVisible)"
# Installed plugins determine optional rows; the HIG still fixes Open and the destructive tail.
entries=$(q contextMenuEntries)
check "the menu opens with Open and ends with Move to Trash" "Open ... Move to Trash" "${entries%%|*} ... ${entries##*|}"
IFS='|' read -r -a menu_entries <<< "$entries"
IFS='|' read -r -a menu_glyphs <<< "$(q contextMenuGlyphs)"
check "every menu row has one glyph slot" "${#menu_entries[@]}" "${#menu_glyphs[@]}"
for i in "${!menu_entries[@]}"; do
  if [[ "${menu_entries[$i]}" == - ]]; then
    check "separator $i has no action glyph" - "${menu_glyphs[$i]:-}"
  elif [[ -z "${menu_glyphs[$i]:-}" || "${menu_glyphs[$i]}" == - ]]; then
    check "action row $i carries a glyph" present missing
  fi
done
duplicate=$(tr '|' '\n' <<< "$entries" | grep -nx 'Duplicate' | cut -d: -f1)
check "the menu offers Duplicate once" "1" "$(tr '|' '\n' <<< "$entries" | grep -cx 'Duplicate')"
[[ "$duplicate" =~ ^[0-9]+$ ]] || die "Duplicate is missing or ambiguous"
check "the menu opens on its first real row" "0" "$(q contextMenuCursor)"
for i in $(seq 1 20); do
  [ "$(q contextMenuCursor)" = "$((duplicate - 1))" ] && break
  press Down
done
check "down walked to Duplicate" "$((duplicate - 1))" "$(q contextMenuCursor)"
press Return
sleep 1.5
check "the menu closed when the entry was chosen" "false" "$(q contextMenuVisible)"
check "the bar named the copy and its reversal" "Duplicated to beta copy.txt · z undoes" "$(message "Duplicated to beta copy.txt · z undoes")"
check "the copy is on disk under the design's own name" "beta body" "$(cat "$SB/beta copy.txt" 2>/dev/null)"
press z
sleep 1.0
check "z removed the copy" "no" "$([ -e "$SB/beta copy.txt" ] && echo yes || echo no)"
check "and left the original" "beta body" "$(cat "$SB/beta.txt" 2>/dev/null)"

echo "--- undo with an empty journal is a message, not a crash ---"
for i in $(seq 1 6); do press z; done
sleep 0.6
check "the app is still answering" "true" "$(q ready)"
check "and says there is nothing left" "There is nothing to undo." "$(message "There is nothing to undo.")"

# Before the last assertion, so a handler that is still holding the file cannot affect it.
reap_handlers

echo "--- the directory is back to where it started ---"
check "every fixture file is present and nothing extra" "alpha.txt beta.txt dest gamma.txt subdir " "$(listing)"

echo
if [ "$fail" = 0 ]; then echo "flea-live-ops: all checks passed"; else echo "flea-live-ops: FAILURES above"; fi
exit "$fail"
