#!/bin/bash
set -euo pipefail

# Patchcord SessionStart hook for Kimi CLI — auto-starts background listener.
# Runs when a Kimi session starts or resumes. Idempotent: the subscribe script
# has a pidfile guard that prevents duplicate instances.

KIMI_SUB="${KIMI_CODE_HOME:-${HOME}/.kimi-code}/patchcord-subscribe.sh"
if [ ! -f "$KIMI_SUB" ]; then
  exit 0
fi

# Kimi sends hook metadata on stdin. Use its cwd when present so the
# subscribe script resolves the right per-project .kimi-code/mcp.json.
if [ -t 0 ]; then
  INPUT=""
else
  INPUT=$(cat || true)
fi
if command -v jq >/dev/null 2>&1; then
  CWD=$(printf '%s' "$INPUT" | jq -r '.cwd // empty' 2>/dev/null || true)
  if [ -n "${CWD:-}" ] && [ -d "$CWD" ]; then
    cd "$CWD"
  fi
fi

# kimi-subscribe.sh always replaces any existing listener for this project,
# so SessionStart starts a fresh listener even if a previous Kimi session
# left one running.
nohup bash "$KIMI_SUB" 5 >/dev/null 2>&1 &
exit 0
