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

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

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

if [[ -f "$PID_FILE" ]]; then
  OLD_PID="$(cat "$PID_FILE")"
  if [[ -n "$OLD_PID" ]] && kill -0 "$OLD_PID" 2>/dev/null; then
    printf 'WeChat algorithm live monitor 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 wechat_algorithm_live.py \
  --fps 30 \
  --host 127.0.0.1 \
  --port 8765 \
  --click-on-badge \
  --llm-on-click \
  --llm-on-chat-change \
  --reply-on-chat-change \
  --send-reply \
  --typing-chunk-size 2 \
  --typing-delay 0.08 \
  > "$LOG_FILE" 2>&1 &

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

printf 'WeChat algorithm live monitor started: pid=%s\n' "$PID"
printf 'Open http://127.0.0.1:8765/\n'
printf 'Log: %s\n' "$LOG_FILE"
