#!/usr/bin/env bash
# Usage: play-hook-sound.sh <hook-type>
# hook-type: PermissionRequest | SessionStart | TaskCreated | TastCompleted

SOUNDS_DIR="$(dirname "$0")"
HOOK_TYPE="${1:-}"

if [[ -z "$HOOK_TYPE" ]]; then
    echo "Usage: $0 <hook-type>" >&2
    exit 1
fi

FOLDER="$SOUNDS_DIR/$HOOK_TYPE"

if [[ ! -d "$FOLDER" ]]; then
    echo "Unknown hook type: $HOOK_TYPE" >&2
    exit 1
fi

# Pick a random mp3 from the folder
mapfile -t FILES < <(ls "$FOLDER"/*.mp3 2>/dev/null)

if [[ ${#FILES[@]} -eq 0 ]]; then
    echo "No sounds found in $FOLDER" >&2
    exit 1
fi

SOUND="${FILES[RANDOM % ${#FILES[@]}]}"

# Play using whatever is available
if command -v mpv &>/dev/null; then
    mpv --no-terminal "$SOUND" &
elif command -v paplay &>/dev/null; then
    paplay "$SOUND" &
elif command -v aplay &>/dev/null; then
    aplay "$SOUND" &
elif command -v ffplay &>/dev/null; then
    ffplay -nodisp -autoexit "$SOUND" &>/dev/null &
else
    echo "No audio player found (mpv, paplay, aplay, ffplay)" >&2
    exit 1
fi
