# 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
    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
        # bash expands aliases at parse time (interactive shells), so a
        # leftover alias would shadow the function 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
}
__otty_should_wrap edit && edit() {
    if [[ -n "$OTTY_FLAGS_DIR" && -f "$OTTY_FLAGS_DIR/omit_prefix" ]]; then
        command otty edit "$@"
    else
        command edit "$@"
    fi
}
__otty_should_wrap view && view() {
    if [[ -n "$OTTY_FLAGS_DIR" && -f "$OTTY_FLAGS_DIR/omit_prefix" ]]; then
        command otty view "$@"
    else
        command view "$@"
    fi
}
__otty_should_wrap watch && watch() {
    if [[ -n "$OTTY_FLAGS_DIR" && -f "$OTTY_FLAGS_DIR/omit_prefix" ]]; then
        command otty watch "$@"
    else
        command watch "$@"
    fi
}
__otty_should_wrap jump && 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 && 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=""

        if [[ -n "$_otty_hostname" ]]; then
            # Always set up a ControlMaster socket so the main connection
            # can be reused for SFTP/exec by the file/git panels.
            local _otty_ctl_dir
            _otty_ctl_dir="$(mktemp -d "${TMPDIR:-/tmp}/otty-ssh-${_otty_user}.XXXXXX" 2>/dev/null)" || _otty_ctl_dir="${TMPDIR:-/tmp}/otty-ssh-${_otty_user}.$$"
            _otty_ctl_path="$_otty_ctl_dir/socket"
            _otty_opts+=(
                -o "ControlMaster=auto"
                -o "ControlPath=$_otty_ctl_path"
                -o "ControlPersist=60"
            )

            # 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
                    # Use ControlMaster=yes so this first connection becomes
                    # the master — the subsequent main connection reuses it.
                    if echo "$_otty_terminfo" | command ssh \
                        -o "ControlMaster=yes" \
                        -o "ControlPath=$_otty_ctl_path" \
                        -o "ControlPersist=60" \
                        "$@" \
                        'command -v tic >/dev/null 2>&1 || exit 1; mkdir -p ~/.terminfo 2>/dev/null; tic -x - 2>/dev/null && exit 0; exit 1' \
                        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

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