#!/usr/bin/env bash
set -euo pipefail

cd "$(dirname "$0")"
mkdir -p ouptsw

PID_FILE="ouptsw/realtime_stream.pid"
LOG_FILE="ouptsw/realtime_stream.log"

# Clean up stale FFmpeg capture children from a previously killed monitor.
pkill -f "avfoundation -framerate 2.0 -i 3:none" 2>/dev/null || true
pkill -f "ffplay .*WeChat Vision ONNX Preview" 2>/dev/null || true

if [[ -f "$PID_FILE" ]]; then
  OLD_PID="$(cat "$PID_FILE")"
  if [[ -n "$OLD_PID" ]] && kill -0 "$OLD_PID" 2>/dev/null; then
    printf 'Realtime stream is already running: pid=%s\n' "$OLD_PID"
    printf 'Open http://127.0.0.1:8765/\n'
    exit 0
  fi
fi

nohup ./venv/bin/python ffmpeg_realtime_detect.py \
  --input 3:none \
  --fps 2 \
  --confidence 0.05 \
  --target-class 0 \
  --display \
  > "$LOG_FILE" 2>&1 &

PID="$!"
printf '%s' "$PID" > "$PID_FILE"

printf 'Realtime stream started: pid=%s\n' "$PID"
printf 'An ffplay preview window should open automatically.\n'
printf 'Log: %s\n' "$LOG_FILE"
