#!/usr/bin/env bash
set -u

SITE="https://download.scartlead.tv"
EXPECTED_VERSION="1.3.0-r6"
LOG_DIR="$HOME/.local/share/video-downloader/logs"
LAUNCH_LOG="$LOG_DIR/launcher.log"
mkdir -p "$LOG_DIR"

audit() {
  printf '[%s] %s\n' "$(date '+%Y-%m-%d %H:%M:%S')" "$*" >>"$LAUNCH_LOG"
}

health_version() {
  python3 - <<'PY' 2>/dev/null
import json, urllib.request
try:
    with urllib.request.urlopen('http://127.0.0.1:5055/api/health', timeout=.6) as r:
        data = json.load(r)
    if data.get('ok'):
        print(data.get('version', ''))
except Exception:
    pass
PY
}

# IMPORTANT: do this before probing port 5055. The v1.2.x app also answered
# localhost requests, which allowed the launcher to mistake it for the agent.
if pgrep -f '/opt/video-downloader/app.py' >/dev/null 2>&1; then
  audit "Retiring legacy /opt/video-downloader/app.py process"
  pkill -f '/opt/video-downloader/app.py' >/dev/null 2>&1 || true
  for _ in $(seq 1 20); do
    pgrep -f '/opt/video-downloader/app.py' >/dev/null 2>&1 || break
    sleep .1
  done
fi

CURRENT_VERSION="$(health_version)"

# If an older 1.3.x agent survived a package upgrade, restart only that known
# agent process so the newly installed code becomes active. A current r5 agent
# is left untouched, so reopening the app does not interrupt downloads.
if [ -n "$CURRENT_VERSION" ] && [ "$CURRENT_VERSION" != "$EXPECTED_VERSION" ]; then
  if pgrep -f '/opt/video-downloader-agent/agent.py' >/dev/null 2>&1; then
    audit "Restarting older agent version ${CURRENT_VERSION} -> ${EXPECTED_VERSION}"
    pkill -f '/opt/video-downloader-agent/agent.py' >/dev/null 2>&1 || true
    for _ in $(seq 1 30); do
      pgrep -f '/opt/video-downloader-agent/agent.py' >/dev/null 2>&1 || break
      sleep .1
    done
  fi
  CURRENT_VERSION=""
fi

if [ "$CURRENT_VERSION" != "$EXPECTED_VERSION" ]; then
  audit "Starting SCARTLEAD Video Downloader Agent ${EXPECTED_VERSION}"
  nohup /usr/bin/video-downloader-agent >>"$LAUNCH_LOG" 2>&1 &
fi

# First launch can take a while while yt-dlp/BgUtils/Deno dependencies are
# prepared. Poll health rather than assuming the agent is ready after 0.7 sec.
READY=0
for _ in $(seq 1 180); do
  CURRENT_VERSION="$(health_version)"
  if [ "$CURRENT_VERSION" = "$EXPECTED_VERSION" ]; then
    READY=1
    break
  fi
  sleep 1
done

if [ "$READY" -eq 1 ]; then
  audit "Agent healthy: ${EXPECTED_VERSION}"
else
  audit "Agent did not become healthy within 180 seconds; opening site for diagnostics"
fi

if command -v xdg-open >/dev/null 2>&1; then
  xdg-open "$SITE" >/dev/null 2>&1 &
else
  printf '%s\n' "$SITE"
fi
