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

CALL_ID="${TUPLE_TRIGGER_CALL_ID:?call-summary-chatgpt-desktop requires TUPLE_TRIGGER_CALL_ID}"
RECORDING_ID="${TUPLE_TRIGGER_RECORDING_ID:?call-summary-chatgpt-desktop requires TUPLE_TRIGGER_RECORDING_ID}"

# TUPLE_BIN="$HOME/bin/tuple"
# TUPLE_DESKTOP_WORKSPACE_ROOT="$HOME/Developer/tuple-calls"
if [ -n "${TUPLE_DESKTOP_WORKSPACE_ROOT:-}" ]; then
    WORKDIR="${TUPLE_DESKTOP_WORKSPACE_ROOT}"
else
    WORKDIR="${HOME}/.tuple/tuple-calls"
fi

printf -v TUPLE_COMMAND '%q' "${TUPLE_BIN:-tuple}"

urlencode() {
    local LC_ALL=C
    local string="${1}"
    local encoded=""
    local pos char byte

    for ((pos = 0; pos < ${#string}; pos++)); do
        char="${string:${pos}:1}"
        case "${char}" in
            [a-zA-Z0-9.~_-]) encoded+="${char}" ;;
            *)
                printf -v byte '%d' "'${char}"
                printf -v encoded '%s%%%02X' "${encoded}" "$((byte & 255))"
                ;;
        esac
    done

    printf '%s' "${encoded}"
}

PROMPT=$(cat <<'PROMPT'
A Tuple pair-programming call just finished, and you have been asked to summarize it.

## Use the triggering Capture session
PROMPT
)
# shellcheck disable=SC2016
PROMPT+=$(printf '\nCall ID: `%s`\nRecording ID: `%s`\n\nDo not discover another call or recording.\n' "${CALL_ID}" "${RECORDING_ID}")
PROMPT+=$(cat <<'PROMPT'

## Read it

Read only speech and chat from that recording:
PROMPT
)
PROMPT+=$(printf '\n\n    %s capture show --recording <recording-id-above> --exclude events,content\n' "${TUPLE_COMMAND}")
PROMPT+=$(cat <<'PROMPT'

## Summarize

Produce:
- A concise executive summary
- Key decisions
- Action items, with owners when stated
- Open questions or loose ends
- Any useful follow-up message draft

Do not invent owners, decisions, or commitments. Use direct quotes only when they materially clarify the summary.

## Write it back to the call

Record the summary in Tuple Call History:
PROMPT
)
PROMPT+=$(printf '\n\n    %s call edit <call-id-above> --title "<a short, specific title for the whole call>" --summary "<your summary>"\n' "${TUPLE_COMMAND}")

mkdir -p "${WORKDIR}"

DEEPLINK="codex://threads/new?mode=work&path=$(urlencode "${WORKDIR}")&prompt=$(urlencode "${PROMPT}")"

if [ "${CALL_SUMMARY_CHATGPT_DESKTOP_DRY_RUN:-}" = "1" ]; then
    echo "call-summary-chatgpt-desktop: dry run — would open ${DEEPLINK}"
    exit 0
fi

echo "call-summary-chatgpt-desktop: opening ChatGPT Desktop"
open -a "ChatGPT" "${DEEPLINK}"
