#!/bin/zsh
# gt-resolve <name-or-id> [--json]
# Resolves a terminal name to its stable terminal id. A UUID passes through
# unchanged without contacting Ghostty, so every gt-* script can resolve its
# id argument unconditionally. Match precedence: exact tab name, exact
# terminal name, then case-insensitive substring across those two. Window
# names are NEVER matched: a window's name mirrors its selected tab's title,
# so matching it would resolve to unrelated terminals in the same window.
# Exit 1 when nothing matches or the name is ambiguous.
set -euo pipefail

Q="" JSON=0
while [[ $# -gt 0 ]]; do
  case "$1" in
    --json) JSON=1; shift ;;
    -h|--help) sed -n '2,8p' "$0"; exit 0 ;;
    *) if [[ -z "$Q" ]]; then Q="$1"; else echo "gt-resolve: unknown arg '$1'" >&2; exit 2; fi; shift ;;
  esac
done
[[ -n "$Q" ]] || { echo "usage: gt-resolve <name-or-id> [--json]" >&2; exit 2; }

json_escape() {
  local s="${1-}"
  s="${s//\\/\\\\}"
  s="${s//\"/\\\"}"
  s="${s//$'\n'/\\n}"
  s="${s//$'\r'/\\r}"
  s="${s//$'\t'/\\t}"
  printf '%s' "$s"
}

emit() {  # $1 = id, $2 = matched_by
  if [[ "$JSON" == "1" ]]; then
    printf '{"backend":"applescript","query":"%s","id":"%s","matched_by":"%s"}\n' \
      "$(json_escape "$Q")" "$(json_escape "$1")" "$2"
  else
    printf '%s\n' "$1"
  fi
}

if [[ "$Q" =~ '^[0-9A-Fa-f]{8}(-[0-9A-Fa-f]{4}){3}-[0-9A-Fa-f]{12}$' ]]; then
  emit "$Q" "uuid"
  exit 0
fi

ROWS=$(osascript <<'EOF'
on clean(s)
    set s to s as text
    set oldDelims to AppleScript's text item delimiters
    set AppleScript's text item delimiters to {tab, linefeed, return}
    set parts to text items of s
    set AppleScript's text item delimiters to " "
    set cleaned to parts as text
    set AppleScript's text item delimiters to oldDelims
    return cleaned
end clean

tell application "Ghostty"
    set out to ""
    set d to character id 9
    repeat with w in windows
        try
            set wname to my clean(name of w)
        on error
            set wname to ""
        end try
        repeat with tb in tabs of w
            try
                set tbname to my clean(name of tb)
            on error
                set tbname to ""
            end try
            repeat with t in terminals of tb
                set tid to id of t as text
                try
                    set tname to my clean(name of t)
                on error
                    set tname to ""
                end try
                set out to out & tid & d & tbname & d & tname & d & wname & linefeed
            end repeat
        end repeat
    end repeat
    return out
end tell
EOF
) || { echo "gt-resolve: Ghostty scripting failed" >&2; exit 1; }

typeset -a exact_tab exact_term substr labels
QL="${(L)Q}"
while IFS=$'\t' read -r TID TBNAME TNAME WNAME; do
  [[ -n "${TID:-}" ]] || continue
  NAME="$TBNAME"; [[ -n "$NAME" ]] || NAME="$TNAME"
  if [[ "$TBNAME" == "$Q" ]]; then
    exact_tab+=("$TID"); labels+=("$TID  $NAME")
  elif [[ "$TNAME" == "$Q" ]]; then
    exact_term+=("$TID"); labels+=("$TID  $NAME")
  elif [[ "${(L)TBNAME}" == *"$QL"* || "${(L)TNAME}" == *"$QL"* ]]; then
    substr+=("$TID"); labels+=("$TID  $NAME")
  fi
done <<< "$ROWS"

typeset -a hits
MATCHED_BY=""
if (( ${#exact_tab} > 0 )); then hits=("${exact_tab[@]}"); MATCHED_BY="exact-tab"
elif (( ${#exact_term} > 0 )); then hits=("${exact_term[@]}"); MATCHED_BY="exact-terminal"
elif (( ${#substr} > 0 )); then hits=("${substr[@]}"); MATCHED_BY="substring"
fi

if (( ${#hits} == 0 )); then
  echo "gt-resolve: no terminal matches '$Q' (run gt-list)" >&2
  exit 1
elif (( ${#hits} > 1 )); then
  echo "gt-resolve: '$Q' is ambiguous:" >&2
  for label in "${labels[@]}"; do
    for h in "${hits[@]}"; do
      [[ "$label" == "$h  "* ]] && { echo "  $label" >&2; break; }
    done
  done
  exit 1
fi

emit "${hits[1]}" "$MATCHED_BY"
