# Otty bash integration — payload (sourced from ~/.bashrc managed block)
#
# Idempotent: re-sourcing in the same shell is a no-op.
[[ -n "$__otty_loaded" ]] && return
__otty_loaded=1

# Guard: only for interactive shells.
[[ "$-" == *i* ]] || return 0

# ── Bundled `otty` on PATH ──
# Otty ships a CLI binary inside the .app bundle. If "Install CLI" has not
# been run (no /usr/local/bin/otty symlink), point shells at our per-process
# bin dir so `otty …` still works without polluting the user's system. The
# guard avoids appending the same dir twice across nested shells.
if [[ -n "$OTTY_BIN_DIR" && -d "$OTTY_BIN_DIR" ]]; then
    case ":$PATH:" in
        *":$OTTY_BIN_DIR:"*) ;;
        *) export PATH="$OTTY_BIN_DIR:$PATH" ;;
    esac
fi

# ── OSC 133 FTCS markers ──
__otty_cmd_executed=""
__otty_last_exit=0
__otty_progress_active=""

# Match the just-about-to-run command against $OTTY_PROGRESS_COMMANDS
# (pipe-separated list of whitespace-delimited prefixes, e.g. "git push").
__otty_progress_match() {
    local cmd="$1"
    [[ -z "$OTTY_PROGRESS_COMMANDS" ]] && return 1
    # Strip leading `NAME=value` env assignments.
    while [[ "$cmd" =~ ^[A-Za-z_][A-Za-z0-9_]*= ]]; do
        cmd="${cmd#* }"
    done
    local IFS='|'
    local p
    for p in $OTTY_PROGRESS_COMMANDS; do
        [[ -z "$p" ]] && continue
        if [[ "$cmd" == "$p" || "$cmd" == "$p "* ]]; then
            return 0
        fi
    done
    return 1
}

__otty_prompt_command() {
    __otty_last_exit=$?
    # D mark from previous command (skip first prompt).
    if [[ -n "$__otty_cmd_executed" ]]; then
        printf '\e]133;D;%d\a' "$__otty_last_exit"
    fi
    # OSC 9;4 completion for auto-progress commands.
    if [[ -n "$__otty_progress_active" ]]; then
        if (( __otty_last_exit == 0 )); then
            printf '\e]9;4;5;0\a'
        else
            printf '\e]9;4;2\a'
        fi
        __otty_progress_active=""
    fi
    # A mark — prompt start.
    printf '\e]133;A\a'
    __otty_cmd_executed=""
}

# B mark — appended to PS1 so it fires after prompt is rendered.
__otty_install_ps1() {
    if [[ "$PS1" != *'133;B'* ]]; then
        PS1="${PS1}\[\e]133;B\a\]"
    fi
}

__otty_debug_trap() {
    # Only emit C for real commands, not PROMPT_COMMAND itself.
    if [[ -n "$COMP_LINE" ]]; then
        return
    fi
    if [[ "$BASH_COMMAND" == __otty_* ]]; then
        return
    fi
    if [[ -z "$__otty_cmd_executed" ]]; then
        printf '\e]133;C\a'
        __otty_cmd_executed=1
        # OSC 9;4 indeterminate progress for matched commands.
        if __otty_progress_match "$BASH_COMMAND"; then
            printf '\e]9;4;3\a'
            __otty_progress_active=1
        fi
    fi
}

# ── OSC 7 CWD reporting ──
__otty_last_reported_cwd=""
__otty_report_cwd() {
    if [[ "$PWD" != "$__otty_last_reported_cwd" ]]; then
        __otty_last_reported_cwd="$PWD"
        printf '\e]7;file://%s%s\a' "$HOSTNAME" "$PWD"
    fi
}
# Emit initial CWD.
__otty_report_cwd

# ── Dump resolved $PATH for the autocomplete engine ──
# The app process inherits only the bare launchd PATH (/usr/bin:/bin:…);
# the completion engine reads this dump to scan the user's real PATH
# (Homebrew/cargo/mise/…) for command-name completion. Once-only — PATH is
# captured after .bashrc has finished setting it up.
__otty_path_dumped=""
__otty_dump_path() {
    [[ -n "$__otty_path_dumped" ]] && return
    __otty_path_dumped=1
    # >| (explicit clobber) so the fixed-path cache write still succeeds under
    # `set -o noclobber`; a plain > errors with "cannot overwrite" each shell.
    printf '%s' "$PATH" >| "${TMPDIR:-/tmp}/otty-path-${EUID}" 2>/dev/null
}

# ── Omit `otty` prefix (live-toggleable) ──
# Install `edit`/`view`/`watch`/`jump`/`learn` wrappers ONCE; each one stat()s the
# omit_prefix sentinel under $OTTY_FLAGS_DIR at call time so the Settings
# toggle takes effect immediately, without waiting for the next
# PROMPT_COMMAND cycle. Sentinel absent → fall through to `command <name>`
# so PATH lookup behaves exactly as if the wrapper weren't there (system
# `watch` on Linux still works). By default, names already defined as user
# functions/aliases are left untouched; the `allow_overwrite` sentinel
# (evaluated at shell init — restart the shell for the toggle to take
# effect) opts into replacing them.
__otty_should_wrap() {
    if [[ -n "$OTTY_FLAGS_DIR" && -f "$OTTY_FLAGS_DIR/allow_overwrite" ]]; then
        # An alias outranks a function at command lookup, so a leftover one
        # would shadow the wrapper we are about to install. Drop it here so
        # our wrapper actually wins.
        alias "$1" >/dev/null 2>&1 && unalias "$1"
        return 0
    fi
    declare -F "$1" >/dev/null 2>&1 && return 1
    alias "$1" >/dev/null 2>&1 && return 1
    return 0
}

# The wrappers below use the `function NAME { … }` keyword form, NOT the
# `NAME() { … }` form. Aliases are expanded at PARSE time, so for a user with
# e.g. `alias view='vim -R'` in an rc file sourced ahead of us, the parser
# rewrites `view()` into `vim -R()` and the whole script dies on a syntax error
# — taking OSC markers, CWD reporting and SSH integration down with it. The
# `__otty_should_wrap view &&` guard on the same line cannot save us: the entire
# `A && B` list is parsed before any of it runs. The keyword form suppresses
# alias expansion of the name, so the definition parses no matter what the user
# has aliased. Don't "simplify" it back to `view() {`.
__otty_should_wrap edit && function edit {
    if [[ -n "$OTTY_FLAGS_DIR" && -f "$OTTY_FLAGS_DIR/omit_prefix" ]]; then
        command otty edit "$@"
    else
        command edit "$@"
    fi
}
__otty_should_wrap view && function view {
    if [[ -n "$OTTY_FLAGS_DIR" && -f "$OTTY_FLAGS_DIR/omit_prefix" ]]; then
        command otty view "$@"
    else
        command view "$@"
    fi
}
__otty_should_wrap watch && function watch {
    if [[ -n "$OTTY_FLAGS_DIR" && -f "$OTTY_FLAGS_DIR/omit_prefix" ]]; then
        command otty watch "$@"
    else
        command watch "$@"
    fi
}
__otty_should_wrap jump && function jump {
    if [[ -n "$OTTY_FLAGS_DIR" && -f "$OTTY_FLAGS_DIR/omit_prefix" ]]; then
        # Zoxide-style: resolve only, then `builtin cd` locally — keeps the
        # transcript silent (no echoed `cd '<path>'` from line-discipline,
        # no duplicate prompt after CLI exits).
        if (( $# == 0 )); then
            # No-args: toggle between $HOME and the last jump-source dir.
            # Local-only state ($OTTY_JUMP_PREV) so up-arrow still recalls
            # the user's literal `jump` invocation, not an injected `cd`.
            if [[ "$PWD" == "$HOME" && -n "$OTTY_JUMP_PREV" ]]; then
                local _otty_dest="$OTTY_JUMP_PREV"
                OTTY_JUMP_PREV="$PWD"
                builtin cd -- "$_otty_dest"
            else
                OTTY_JUMP_PREV="$PWD"
                builtin cd -- "$HOME"
            fi
            return
        fi
        local _otty_p
        _otty_p=$(command otty jump --no-cd "$@") || return
        if [[ -n "$_otty_p" ]]; then
            OTTY_JUMP_PREV="$PWD"
            builtin cd -- "$_otty_p"
        fi
    else
        command jump "$@"
    fi
}
__otty_should_wrap learn && function learn {
    if [[ -n "$OTTY_FLAGS_DIR" && -f "$OTTY_FLAGS_DIR/omit_prefix" ]]; then
        command otty learn "$@"
    else
        command learn "$@"
    fi
}
# `watch:<agent>` — wait for a Claude/Codex/OpenCode session to reach
# idle. The colon is part of the command name as far as the shell is
# concerned, so the bare `watch` wrapper above never catches it; install
# one wrapper per agent. Keep in sync with WATCH_AGENTS in cli/src/main.rs.
for __otty_a in claude codex opencode; do
    __otty_should_wrap "watch:$__otty_a" && eval "watch:$__otty_a() {
        if [[ -n \"\$OTTY_FLAGS_DIR\" && -f \"\$OTTY_FLAGS_DIR/omit_prefix\" ]]; then
            command otty watch:$__otty_a \"\$@\"
        else
            command watch:$__otty_a \"\$@\"
        fi
    }"
done
unset __otty_a

# ── Custom CLI aliases ($OTTY_CLI_ALIASES = "name=cmd|name=cmd|…") ──
if [[ -n "$OTTY_CLI_ALIASES" ]]; then
    __otty_install_aliases() {
        local IFS='|'
        local pair name cmd
        for pair in $OTTY_CLI_ALIASES; do
            [[ -z "$pair" ]] && continue
            name="${pair%%=*}"
            cmd="${pair#*=}"
            [[ -z "$name" || -z "$cmd" || "$name" == "$pair" ]] && continue
            [[ "$name" =~ ^[A-Za-z_][A-Za-z0-9_]*$ ]] || continue
            [[ "$cmd"  =~ ^[A-Za-z_][A-Za-z0-9_]*$ ]] || continue
            __otty_should_wrap "$name" || continue
            # When the alias maps to a wrapped command (jump/edit/view/watch/
            # learn), delegate to the wrapper function so its `--no-cd` /
            # builtin-cd logic still runs. Calling `command otty $cmd`
            # directly would bypass the wrapper and re-introduce the visible
            # `cd '<path>'` echo plus a spurious shell-history entry.
            case "$cmd" in
                jump|edit|view|watch|learn)
                    eval "$name() { $cmd \"\$@\"; }"
                    ;;
                *)
                    eval "$name() { command otty $cmd \"\$@\"; }"
                    ;;
            esac
        done
    }
    __otty_install_aliases
    unset -f __otty_install_aliases
fi

unset -f __otty_should_wrap

# Install hooks.
if [[ -z "$PROMPT_COMMAND" ]]; then
    PROMPT_COMMAND="__otty_prompt_command; __otty_install_ps1; __otty_report_cwd; __otty_dump_path"
else
    PROMPT_COMMAND="__otty_prompt_command; __otty_install_ps1; __otty_report_cwd; __otty_dump_path; $PROMPT_COMMAND"
fi
trap '__otty_debug_trap' DEBUG

# ── SSH Integration ──
if [[ "${OTTY_SSH_INTEGRATION:-}" == "1" ]]; then
    ssh() {
        local _otty_term="xterm-256color"
        local -a _otty_opts=(
            -o "SetEnv=COLORTERM=truecolor TERM_PROGRAM=otty"
            -o "SendEnv=COLORTERM TERM_PROGRAM TERM_PROGRAM_VERSION"
        )

        # ── Resolve hostname via ssh -G ──
        local _otty_user="" _otty_hostname=""
        while IFS=' ' read -r _k _v; do
            case "$_k" in
                user) _otty_user="$_v" ;;
                hostname) _otty_hostname="$_v" ;;
            esac
            [[ -n "$_otty_user" && -n "$_otty_hostname" ]] && break
        done < <(command ssh -G "$@" 2>/dev/null)

        local _otty_target="${_otty_user}@${_otty_hostname}"
        local _otty_meta_file="${TMPDIR:-/tmp}/otty-ssh-shell-$$.meta"
        local _otty_ctl_path=""
        local _otty_ctl_dir=""

        if [[ -n "$_otty_hostname" ]]; then
            # Set up a ControlMaster socket so the main connection can be reused
            # for SFTP/exec by the file/git panels.
            #
            # If the caller already passed an explicit ControlPath, honor it and
            # don't mint a competing master. Otty's split-pane "inherit SSH"
            # passes `-o ControlPath=<socket>` to ride the existing master — no
            # re-auth, no proxy/alias re-resolution.
            local _otty_arg
            for _otty_arg in "$@"; do
                case "$_otty_arg" in
                    ControlPath=*) _otty_ctl_path="${_otty_arg#ControlPath=}" ;;
                esac
            done
            if [[ -z "$_otty_ctl_path" ]]; then
                # ControlPath must stay short: macOS caps Unix-domain socket
                # paths at 104 bytes and $TMPDIR (/var/folders/...) already eats
                # ~49 of them, so the socket goes directly under /tmp instead.
                # mktemp -d yields a fresh 0700 dir, keeping this race-free.
                _otty_ctl_dir="$(mktemp -d /tmp/otty-ssh.XXXXXX 2>/dev/null)" || _otty_ctl_dir="/tmp/otty-ssh.$$"
                _otty_ctl_path="$_otty_ctl_dir/socket"
                _otty_opts+=(
                    -o "ControlMaster=auto"
                    -o "ControlPath=$_otty_ctl_path"
                    -o "ControlPersist=60"
                )
            fi

            # Terminfo install (cached per user@host)
            local _otty_cache_dir="${TMPDIR:-/tmp}/otty-terminfo-cache"
            command mkdir -p "$_otty_cache_dir" 2>/dev/null
            local _otty_cache_file="$_otty_cache_dir/$_otty_target"

            if [[ -f "$_otty_cache_file" ]]; then
                _otty_term="${TERM:-xterm-256color}"
            elif command -v infocmp >/dev/null 2>&1; then
                local _otty_terminfo
                _otty_terminfo="$(infocmp -0 -x 2>/dev/null)"

                if [[ -n "$_otty_terminfo" ]]; then
                    # Deliberately NOT sharing $_otty_ctl_path here. This probe
                    # used to run with ControlMaster=yes and hand its master to
                    # the interactive ssh below, saving one auth round-trip. But
                    # that demoted the interactive connection to a mux *client*,
                    # and a client's interactive session can hang with no output
                    # at all — no banner, no prompt, nothing — which reads as
                    # "ssh froze". It only bit on the first connection to a host
                    # (later ones hit the terminfo cache and skipped this probe
                    # entirely), which is what made it look intermittent.
                    # ControlPath=none keeps the probe off the socket so the
                    # interactive ssh below stays the master.
                    # Remote command (TERM injected via the leading assignment):
                    #   1. If the remote already resolves this TERM (system DB or
                    #      a user entry), do nothing — never shadow a standard
                    #      name like xterm-256color with our copy.
                    #   2. Otherwise install via `tic`, then verify the fresh
                    #      entry actually has `clear=`; a truncated transfer can
                    #      compile a stub that lacks clear/cup and breaks tput &
                    #      tmux. If incomplete, remove it and fail so we fall back
                    #      to the system database instead of a broken shadow.
                    if echo "$_otty_terminfo" | command ssh \
                        -o "ControlMaster=no" \
                        -o "ControlPath=none" \
                        "$@" \
                        "otty_term=${TERM:-xterm-256color}; "'command -v infocmp >/dev/null 2>&1 && infocmp "$otty_term" >/dev/null 2>&1 && exit 0; command -v tic >/dev/null 2>&1 || exit 1; mkdir -p ~/.terminfo 2>/dev/null; tic -x - >/dev/null 2>&1 || exit 1; command -v infocmp >/dev/null 2>&1 && { infocmp -1 "$otty_term" 2>/dev/null | grep -q "clear=" || { rm -f ~/.terminfo/?/"$otty_term" ~/.terminfo/??/"$otty_term" 2>/dev/null; exit 1; }; }; exit 0' \
                        2>/dev/null; then
                        _otty_term="${TERM:-xterm-256color}"
                        command touch "$_otty_cache_file"
                    fi
                fi
            fi

            # Write metadata file so Otty's Swift side can find the resolved
            # session info (user, hostname, socket) even when ~/.ssh/config
            # aliases the user or hostname.
            {
                echo "user=${_otty_user}"
                echo "hostname=${_otty_hostname}"
                echo "socket=${_otty_ctl_path}"
            } > "$_otty_meta_file" 2>/dev/null
        fi

        # Notify Otty we're entering an SSH session.
        printf '\e]7;ssh://%s\a' "${_otty_hostname:-unknown}"

        TERM="$_otty_term" command ssh "${_otty_opts[@]}" "$@"
        local _ret=$?

        command rm -f "$_otty_meta_file" 2>/dev/null

        # Retire the ControlMaster we minted above. Only ours — a ControlPath the
        # caller passed in belongs to whoever created it, hence the _otty_ctl_dir
        # guard. Without this the master lingers for the whole ControlPersist
        # window and its mktemp'd directory was never removed at all, so every
        # ssh invocation leaked one empty /tmp/otty-ssh.XXXXXX forever.
        if [[ -n "$_otty_ctl_dir" ]]; then
            command ssh -o "ControlPath=$_otty_ctl_path" -O exit "$@" >/dev/null 2>&1
            command rm -rf "$_otty_ctl_dir" 2>/dev/null
        fi
        # Sweep dirs orphaned by earlier crashes. -empty means a live master's
        # dir (it still holds its socket) is never touched. The trailing slash on
        # /tmp/ is load-bearing: on macOS /tmp is a symlink to private/tmp and
        # find won't descend into it without one, silently matching nothing.
        command find /tmp/ -maxdepth 1 -type d -name 'otty-ssh.*' -empty -delete 2>/dev/null

        # Restore local CWD reporting.
        printf '\e]7;file://%s%s\a' "$HOSTNAME" "$PWD"
        return $_ret
    }
fi
