#!/usr/bin/env bash
# Moda shadow workspace hook for coding agents.
# Triggered by Claude Code, Codex, and Cursor lifecycle/tool matchers.
#
# Claude Code passes hook context as a JSON object on stdin (per the Claude
# Code hooks reference): session_id, tool_use_id, prompt, hook_event_name,
# etc. We forward that stdin straight through to `moda workspace snapshot
# --hook-stdin`, which parses it server-side so the CLI sees the same
# correlation keys (session_id, tool_use_id, prompt_sha) the ingest worker
# will later join on. The previous version read $CLAUDE_SESSION_ID and
# $CLAUDE_PROMPT_HASH env vars, but Claude never sets those — so session_id
# and prompt-level joins were unrecoverable. Reading stdin fixes that.
#
# Runs `moda workspace snapshot` in the background so the hook never blocks
# Claude; redirects all output to /dev/null so user-visible output stays
# clean; always exits 0 so a transient failure can't break the user session.

set +e
case "${1:-}" in
  claude|claude_code|codex|cursor)
    PROVIDER="$1"
    EVENT="${2:-UserPromptSubmit}"
    ;;
  *)
    PROVIDER="claude_code"
    EVENT="${1:-UserPromptSubmit}"
    ;;
esac
MODA_SNAPSHOT_BIN="${MODA_BIN:-moda}"

# Buffer the hook JSON once so the background subshell sees it after this
# script's stdin is closed by Claude.
PAYLOAD="$(cat)"

(
  printf '%s' "$PAYLOAD" \
    | "$MODA_SNAPSHOT_BIN" workspace snapshot --provider "$PROVIDER" --event "$EVENT" --json --hook-stdin \
    > /dev/null 2>&1
) &

exit 0
