#!/bin/bash
# 유튜브 재생 (자비스 메인 프로세스 밖 — fork 데드락 방지)
# 사용: jarvis_yt_play.sh "검색어" ["https://youtube.com/watch?v=..."]
set -euo pipefail

QUERY="${1:-}"
WATCH_URL="${2:-}"
BASE="/home/hoon/projects/jarvis"
YT="${BASE}/jarvis_env/bin/yt-dlp"
LOG="${BASE}/jarvis_logs/yt.log"
PIDFILE="${BASE}/jarvis_logs/media.pid"

log() { echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*" >>"$LOG"; }

if [[ -z "$QUERY" ]]; then
  log "빈 검색어"
  exit 1
fi

if [[ -f "$PIDFILE" ]]; then
  old_pid="$(cat "$PIDFILE" 2>/dev/null || true)"
  if [[ -n "$old_pid" ]]; then
    kill "$old_pid" 2>/dev/null || true
    sleep 0.2
    kill -9 "$old_pid" 2>/dev/null || true
  fi
  rm -f "$PIDFILE"
fi

log "검색: $QUERY"

URL=""
if [[ -x "$YT" ]]; then
  if [[ -n "$WATCH_URL" && "$WATCH_URL" =~ ^https?:// ]]; then
    log "API/사전확정 URL: $WATCH_URL"
    URL="$("$YT" -f bestaudio/best --no-playlist -g "$WATCH_URL" 2>>"$LOG" | head -1 || true)"
  else
    URL="$("$YT" -f bestaudio/best --no-playlist -g "ytsearch1:${QUERY}" 2>>"$LOG" | head -1 || true)"
  fi
fi

if [[ ! "$URL" =~ ^https?:// ]]; then
  log "URL 실패: $QUERY"
  exit 1
fi

log "재생 시작: $QUERY"

cvlc --play-and-exit --no-video --quiet --no-repeat "$URL" &
echo $! >"$PIDFILE"
wait
rm -f "$PIDFILE"
log "재생 종료: $QUERY"
