#!/bin/zsh
# gt-split <id|name> right|left|up|down [--cwd DIR] [--cmd CMD] [--title TITLE] [--focus] [--json]
# Splits a terminal and prints the new terminal id. The split is created
# without focusing it or activating Ghostty; pass --focus to focus the new
# split (which brings Ghostty forward).
set -euo pipefail
HERE="${0:A:h}"

TID="" DIR="" CWD="" CMD="" TITLE="" JSON=0 FOCUS=0
while [[ $# -gt 0 ]]; do
  case "$1" in
    --cwd) CWD="$2"; shift 2 ;;
    --cmd) CMD="$2"; shift 2 ;;
    --title|--name) TITLE="$2"; shift 2 ;;
    --focus) FOCUS=1; shift ;;
    --json) JSON=1; shift ;;
    -h|--help) sed -n '2,6p' "$0"; exit 0 ;;
    *)
      if [[ -z "$TID" ]]; then
        TID="$1"
      elif [[ -z "$DIR" ]]; then
        DIR="$1"
      else
        echo "gt-split: unknown arg '$1'" >&2; exit 2
      fi
      shift
      ;;
  esac
done

[[ -n "$TID" && -n "$DIR" ]] || { echo "usage: gt-split <id|name> right|left|up|down [--cwd DIR] [--cmd CMD] [--title TITLE] [--json]" >&2; exit 2; }
case "$DIR" in
  right|left|up|down) ;;
  *) echo "gt-split: direction must be right, left, up, or down" >&2; exit 2 ;;
esac
TID=$("$HERE/gt-resolve" "$TID")

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

NEW_ID=$(osascript - "$TID" "$DIR" "$CWD" "$CMD" "$TITLE" "$FOCUS" <<'EOF'
on run argv
    set tid to item 1 of argv
    set dirName to item 2 of argv
    set cwd to item 3 of argv
    set cmd to item 4 of argv
    set titleName to item 5 of argv
    set wantFocus to item 6 of argv
    tell application "Ghostty"
        set t to terminal id tid
        -- find the tab containing t and snapshot its terminal ids, so the new
        -- split is identified by diff instead of focus (no focus stealing)
        set homeTab to missing value
        repeat with w in windows
            repeat with tb in tabs of w
                repeat with cand in terminals of tb
                    if id of cand is tid then
                        set homeTab to tb
                        exit repeat
                    end if
                end repeat
                if homeTab is not missing value then exit repeat
            end repeat
            if homeTab is not missing value then exit repeat
        end repeat
        if homeTab is missing value then error "terminal not found: " & tid
        set beforeIds to {}
        repeat with cand in terminals of homeTab
            set end of beforeIds to (id of cand as text)
        end repeat

        set conf to new surface configuration
        if cwd is not "" then set initial working directory of conf to cwd
        if cmd is not "" then set initial input of conf to (cmd & linefeed)

        if dirName is "right" then
            split t direction right with configuration conf
        else if dirName is "left" then
            split t direction left with configuration conf
        else if dirName is "up" then
            split t direction up with configuration conf
        else
            split t direction down with configuration conf
        end if

        delay 0.5
        set newTerm to missing value
        repeat with cand in terminals of homeTab
            if beforeIds does not contain (id of cand as text) then
                set newTerm to cand
                exit repeat
            end if
        end repeat
        if newTerm is missing value then error "split surface did not appear"
        if titleName is not "" then perform action ("set_surface_title:" & titleName) on newTerm
        if wantFocus is "1" then focus newTerm
        return id of newTerm
    end tell
end run
EOF
) || { echo "gt-split: failed to split $TID" >&2; exit 1; }

if [[ "$JSON" == "1" ]]; then
  CMD_PRESENT=false; [[ -n "$CMD" ]] && CMD_PRESENT=true
  printf '{"backend":"applescript","id":"%s","parent_id":"%s","direction":"%s","cwd":"%s","title":"%s","command_present":%s}\n' \
    "$(json_escape "$NEW_ID")" "$(json_escape "$TID")" "$(json_escape "$DIR")" "$(json_escape "$CWD")" "$(json_escape "$TITLE")" "$CMD_PRESENT"
else
  echo "$NEW_ID"
fi
