#!/bin/sh
set -eu

cmd="${SNAP}/bin/godex"
if [ "$#" -gt 0 ]; then
  cmd="$1"
  shift
fi

if [ -t 0 ] || [ -t 1 ]; then
  exec "$cmd" "$@"
fi

if command -v xdg-terminal-exec >/dev/null 2>&1; then
  exec xdg-terminal-exec -- "$cmd" "$@"
fi

if command -v x-terminal-emulator >/dev/null 2>&1; then
  exec x-terminal-emulator -e "$cmd" "$@"
fi

if command -v kgx >/dev/null 2>&1; then
  exec kgx -- "$cmd" "$@"
fi

if command -v gnome-console >/dev/null 2>&1; then
  exec gnome-console -- "$cmd" "$@"
fi

if command -v gnome-terminal >/dev/null 2>&1; then
  exec gnome-terminal -- "$cmd" "$@"
fi

if command -v konsole >/dev/null 2>&1; then
  exec konsole -e "$cmd" "$@"
fi

if command -v xfce4-terminal >/dev/null 2>&1; then
  exec xfce4-terminal -e "$cmd" "$@"
fi

if command -v mate-terminal >/dev/null 2>&1; then
  exec mate-terminal -e "$cmd" "$@"
fi

if command -v tilix >/dev/null 2>&1; then
  exec tilix -e "$cmd" "$@"
fi

if command -v lxterminal >/dev/null 2>&1; then
  exec lxterminal -e "$cmd" "$@"
fi

if command -v qterminal >/dev/null 2>&1; then
  exec qterminal -e "$cmd" "$@"
fi

if command -v xterm >/dev/null 2>&1; then
  exec xterm -e "$cmd" "$@"
fi

if command -v alacritty >/dev/null 2>&1; then
  exec alacritty -e "$cmd" "$@"
fi

if command -v kitty >/dev/null 2>&1; then
  exec kitty -e "$cmd" "$@"
fi

fallback_cmd="godex-ai-agent.godex-terminal"

msg_file="${SNAP_USER_COMMON:-$HOME}/godex-open-in-terminal.txt"
mkdir -p "$(dirname "$msg_file")"
cat >"$msg_file" <<EOF
Godex could not find a terminal emulator when launched from this context.

Run this command in a terminal:
$fallback_cmd
EOF

if command -v xdg-open >/dev/null 2>&1; then
  xdg-open "$msg_file" >/dev/null 2>&1 || true
elif command -v gio >/dev/null 2>&1; then
  gio open "$msg_file" >/dev/null 2>&1 || true
fi

echo "No terminal emulator found. Run: $fallback_cmd" >&2
exit 1
