#!/usr/bin/env bash
set -u
APP_DIR="/opt/video-downloader-agent"
USER_DIR="$HOME/.local/share/video-downloader"
VENV="$USER_DIR/venv"
RUNTIME_BIN="$USER_DIR/runtime/bin"
LOG_DIR="$USER_DIR/logs"
LOG_FILE="$LOG_DIR/agent.log"
MARKER="$USER_DIR/.setup-complete-1.3.0-r6"
POT_DIR="$USER_DIR/bgutil-ytdlp-pot-provider"
mkdir -p "$LOG_DIR" "$RUNTIME_BIN"

# Retire the legacy v1.2.x app before any potentially long first-run setup.
# This guarantees port 5055 is free by the time the new agent is ready.
if pgrep -f '/opt/video-downloader/app.py' >/dev/null 2>&1; then
  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

message() {
  local kind="$1" text="$2"
  if command -v zenity >/dev/null 2>&1; then
    case "$kind" in
      error) zenity --error --title="SCARTLEAD Video Downloader" --width=580 --text="$text" ;;
      warning) zenity --warning --title="SCARTLEAD Video Downloader" --width=560 --text="$text" ;;
    esac
  else
    printf '%b\n' "$text" >&2
  fi
}

setup_failure() {
  local reason="$1"
  message error "We couldn't finish preparing SCARTLEAD Video Downloader.\n\n$reason\n\nDetails: $LOG_FILE"
  exit 1
}

setup_agent() {
  rm -f "$POT_DIR/.scartlead-ready-1.3.1" 2>/dev/null || true
  if ! command -v python3 >/dev/null 2>&1; then
    setup_failure "Python 3 is not installed. Install python3 and python3-venv first."
  fi
  if [ ! -d "$VENV" ]; then
    python3 -m venv "$VENV" >>"$LOG_FILE" 2>&1 || setup_failure "The private Python environment could not be created."
  fi
  local PYTHON="$VENV/bin/python3"
  "$PYTHON" -m pip install --disable-pip-version-check --upgrade pip >>"$LOG_FILE" 2>&1 || true
  "$PYTHON" -m pip install --disable-pip-version-check --upgrade -r "$APP_DIR/requirements.txt" >>"$LOG_FILE" 2>&1 || setup_failure "The download engine could not be installed."

  local DENO="$RUNTIME_BIN/deno"
  if ! command -v deno >/dev/null 2>&1 && [ ! -x "$DENO" ]; then
    local ARCH DENO_ARCH ZIP URL
    ARCH="$(uname -m)"
    case "$ARCH" in
      x86_64|amd64) DENO_ARCH="x86_64-unknown-linux-gnu" ;;
      aarch64|arm64) DENO_ARCH="aarch64-unknown-linux-gnu" ;;
      *) DENO_ARCH="" ;;
    esac
    if [ -n "$DENO_ARCH" ]; then
      ZIP="$USER_DIR/deno.zip"
      URL="https://github.com/denoland/deno/releases/download/v2.9.1/deno-${DENO_ARCH}.zip"
      if command -v curl >/dev/null 2>&1; then
        curl -L --fail --retry 3 -o "$ZIP" "$URL" >>"$LOG_FILE" 2>&1 || setup_failure "The YouTube compatibility runtime could not be downloaded."
      else
        wget -O "$ZIP" "$URL" >>"$LOG_FILE" 2>&1 || setup_failure "The YouTube compatibility runtime could not be downloaded."
      fi
      "$PYTHON" - "$ZIP" "$RUNTIME_BIN" >>"$LOG_FILE" 2>&1 <<'PY' || setup_failure "The YouTube compatibility runtime could not be unpacked."
import sys, zipfile
archive, destination = sys.argv[1:]
with zipfile.ZipFile(archive) as package:
    package.extractall(destination)
PY
      chmod +x "$DENO" 2>/dev/null || true
      rm -f "$ZIP"
    fi
  fi
  # Prepare the local BgUtils PO-token provider. This is used only as a
  # recovery path when YouTube rejects the normal download clients.
  if [ ! -f "$POT_DIR/.scartlead-ready-1.3.2" ]; then
    TMP_ARCHIVE="$USER_DIR/bgutil-ytdlp-pot-provider-1.3.2.tar.gz"
    TMP_EXTRACT="$USER_DIR/.bgutil-extract"
    rm -rf "$TMP_EXTRACT"
    mkdir -p "$TMP_EXTRACT"
    POT_URL="https://github.com/Brainicism/bgutil-ytdlp-pot-provider/archive/refs/tags/1.3.2.tar.gz"
    if command -v curl >/dev/null 2>&1; then
      curl -L --fail --retry 3 -o "$TMP_ARCHIVE" "$POT_URL" >>"$LOG_FILE" 2>&1 || true
    elif command -v wget >/dev/null 2>&1; then
      wget -O "$TMP_ARCHIVE" "$POT_URL" >>"$LOG_FILE" 2>&1 || true
    fi
    if [ -s "$TMP_ARCHIVE" ]; then
      tar -xzf "$TMP_ARCHIVE" -C "$TMP_EXTRACT" >>"$LOG_FILE" 2>&1 || true
      FOUND_DIR="$(find "$TMP_EXTRACT" -mindepth 1 -maxdepth 1 -type d -name 'bgutil-ytdlp-pot-provider-*' | head -n1)"
      if [ -n "$FOUND_DIR" ]; then
        rm -rf "$POT_DIR"
        mv "$FOUND_DIR" "$POT_DIR"
        DENO_CMD=""
        if [ -x "$RUNTIME_BIN/deno" ]; then
          DENO_CMD="$RUNTIME_BIN/deno"
        elif command -v deno >/dev/null 2>&1; then
          DENO_CMD="$(command -v deno)"
        fi
        if [ -n "$DENO_CMD" ] && (cd "$POT_DIR/server" && "$DENO_CMD" install --allow-scripts=npm:canvas --frozen) >>"$LOG_FILE" 2>&1; then
          touch "$POT_DIR/.scartlead-ready-1.3.2"
        else
          echo "BgUtils provider preparation was incomplete; normal and web_safari fallbacks remain available." >>"$LOG_FILE"
        fi
      fi
    fi
    rm -rf "$TMP_EXTRACT" "$TMP_ARCHIVE"
  fi

  touch "$MARKER"
}

if [ ! -f "$MARKER" ]; then setup_agent; fi
PYTHON="$VENV/bin/python3"
if [ ! -x "$PYTHON" ] || ! "$PYTHON" -c 'import flask, yt_dlp' >>"$LOG_FILE" 2>&1; then
  rm -f "$MARKER"
  setup_agent
fi
export PATH="$RUNTIME_BIN:$PATH"
exec "$PYTHON" "$APP_DIR/agent.py" >>"$LOG_FILE" 2>&1
