#!/usr/bin/env bash
set -euo pipefail

# sidekick-pi: when Tuple transcription starts, launch Pi as a live-call sidekick.
#
# Joining call state and building the context prompt are delegated to
# `tuple connect --harness pi`. On top of that, this trigger ships a small Pi
# extension (`tuple-call-sidekick.ts`) into a working directory, where Pi auto-loads
# it: the extension follows the live transcript in the background (via
# `tuple transcription show`), surfaces the watch state on Pi's toolbar, and adds a
# set_watch_mode tool.
#
# The transcription triggers receive no call-specific args, so the working
# directory is created under the temp dir, unique per transcription-start
# (timestamp + this trigger's PID). A fresh directory each time means stopping and
# restarting transcription in one call spawns a new sidekick while older ones keep
# running and stay queryable — no dedup. The extension resolves the current call
# from the daemon, so the trigger itself needs no call id.

# Set your preferred terminal here, or leave empty to use your default handler
# for .command files. One of: ghostty | iterm | alacritty | terminal
PREFERRED_TERM="${PREFERRED_TERM:-}"

TMP="${TMPDIR:-/tmp}"
WORKDIR="${TMP%/}/tuple-pi-sidekick/$(date +%Y%m%dT%H%M%S)-$$"
LAUNCHER_FILE="${WORKDIR}/launch-pi-sidekick.command"

# Ship the sidekick extension into `.pi/extensions/`, where Pi loads it
# automatically at startup.
EXTENSION_DIR="${WORKDIR}/.pi/extensions"
mkdir -p "${EXTENSION_DIR}"

TRIGGER_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)"
EXTENSION_SRC="${TRIGGER_DIR}/tuple-call-sidekick.ts"
if [ -f "${EXTENSION_SRC}" ]; then
    cp "${EXTENSION_SRC}" "${EXTENSION_DIR}/tuple-call-sidekick.ts"
else
    echo "sidekick-pi: extension not found at ${EXTENSION_SRC}; Pi will run without it" >&2
fi

# The launcher runs as a login-interactive zsh so `tuple` and `pi` resolve from the
# same PATH you get in a fresh terminal.
cat > "${LAUNCHER_FILE}" <<'SCRIPT'
#!/bin/zsh -li
printf '\e]0;Tuple Pi Sidekick\a'
clear
echo 'Connecting Pi to the call...'
echo

SCRIPT_DIR="${0:A:h}"
PID_FILE="${SCRIPT_DIR}/pi-sidekick.pid"

echo $$ > "${PID_FILE}"
cd "${SCRIPT_DIR}" || exit 1

if ! command -v tuple >/dev/null 2>&1; then
    echo "tuple was not found on your interactive shell PATH."
    echo "Make sure 'tuple' works in a new terminal, then run the trigger again."
    echo
    read '?Press return to close.'
    exit 127
fi

exec tuple connect --harness pi
SCRIPT

chmod 0755 "${LAUNCHER_FILE}"

# --- launch_in_terminal: open the .command launcher in the user's terminal ---
# Uses LaunchServices (`open`) only — no direct binary exec and no AppleScript,
# so it triggers no macOS accessibility prompt and no stray empty windows.
# With PREFERRED_TERM empty, the launcher opens in your default handler for
# .command files (change it in Finder: right-click a .command > Open With >
# your terminal > Change All). Set PREFERRED_TERM to force one for this trigger.
# Ghostty, iTerm, and Terminal run an opened .command directly; Alacritty has no
# document handler, so it is launched with `open -na ... --args -e`.
launch_in_terminal() {
    local file="$1"
    case "${PREFERRED_TERM:-}" in
    "") open "$file" ;;
    ghostty) open -a "Ghostty" "$file" 2>/dev/null || open "$file" ;;
    iterm) open -a "iTerm" "$file" 2>/dev/null || open "$file" ;;
    terminal) open -a "Terminal" "$file" 2>/dev/null || open "$file" ;;
    alacritty) open -na "Alacritty" --args -e "$file" 2>/dev/null || open "$file" ;;
    *) echo "launch_in_terminal: unknown PREFERRED_TERM='${PREFERRED_TERM}'; using default handler" >&2; open "$file" ;;
    esac
}

if [ "${SIDEKICK_PI_DRY_RUN:-}" = "1" ]; then
    echo "sidekick-pi: dry run generated ${LAUNCHER_FILE}"
    exit 0
fi

launch_in_terminal "${LAUNCHER_FILE}"
