#!/bin/bash
# Claude Code / Codex 共用 iVox 播报 Hook
# 用法: bash hook-speak.sh <source> < payload.json
[[ "${IVOX_SKIP:-}" == "1" ]] && exit 0

SOURCE="${1:-claude}"
SOCK="$HOME/.config/ivox/ivox.sock"
LOG="$HOME/.config/ivox/hook.log"
JS="$HOME/.config/ivox/hook-speak.js"
if [[ ! -f "$JS" ]]; then
  JS="$(cd "$(dirname "$0")" && pwd)/hook-speak.js"
fi
mkdir -p "$(dirname "$LOG")"

if [[ $# -ge 2 ]]; then
  result=$(printf "%s" "$2" | node "$JS" "$SOURCE" 2>>"$LOG")
else
  result=$(node "$JS" "$SOURCE" 2>>"$LOG")
fi

if [[ "${IVOX_HOOK_PRINT_TEXT:-}" == "1" ]]; then
  printf "%s" "$result"
  exit 0
fi

if [[ -z "$result" ]]; then
  exit 0
fi

if ! command -v nc &>/dev/null; then
  echo "$(date): nc (netcat) 未安装" >> "$LOG"
  exit 1
fi

if [[ ! -S "$SOCK" ]]; then
  echo "$(date): iVox socket 不存在: $SOCK" >> "$LOG"
  exit 1
fi

printf "{source:%s}%s" "$SOURCE" "$result" | nc -U -w5 "$SOCK" 2>>"$LOG"
