#!/usr/bin/env bash
# One-action Slack sync:
# 1) fetch Slack data into SQLite
# 2) keep running indexing until pending rows become 0 (or max rounds reached)

set -uo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
LOG_DIR="$ROOT/logs"
LOG_FILE="$LOG_DIR/slack-sync-all.log"

find_python() {
  if command -v python3 >/dev/null 2>&1; then
    command -v python3
    return 0
  fi
  if command -v python >/dev/null 2>&1; then
    command -v python
    return 0
  fi
  if command -v py >/dev/null 2>&1; then
    command -v py
    return 0
  fi
  local candidates=(
    /usr/bin/python3
    /usr/local/bin/python3
    /opt/homebrew/bin/python3
  )
  local c
  for c in "${candidates[@]}"; do
    if [ -x "$c" ]; then
      echo "$c"
      return 0
    fi
  done
  return 1
}

counts_from_db() {
  "$PYTHON_BIN" - <<'PY'
import sqlite3
import os

db = os.environ.get('SLACK_SQLITE_DB', 'tools/slack_data.db')
con = sqlite3.connect(db)
total = con.execute('select count(*) from slack_documents').fetchone()[0]
indexed = con.execute('select count(*) from slack_documents where indexed=1').fetchone()[0]
pending = con.execute('select count(*) from slack_documents where indexed=0').fetchone()[0]
print(f"{total} {indexed} {pending}")
con.close()
PY
}

mkdir -p "$LOG_DIR"
cd "$ROOT" || exit 1

PYTHON_BIN="$(find_python || true)"
if [ -z "${PYTHON_BIN:-}" ]; then
  echo "[slack-sync-all] FATAL: python3/python/py not found"
  exit 127
fi

# Defaults (override via environment before running the script).
export SLACK_SWEEP_DAYS="${SLACK_SWEEP_DAYS:-15}"
export SLACK_SQLITE_DB="${SLACK_SQLITE_DB:-tools/slack_data.db}"
export SLACK_SWEEP_REPO_ID="${SLACK_SWEEP_REPO_ID:-slack-${SLACK_USER_ID:-user}}"
export SLACK_SWEEP_SNAPSHOT_ID="${SLACK_SWEEP_SNAPSHOT_ID:-snap-$(date -u +%Y-%m-%d)}"
export EMBEDDING_ENGINE_URL="${EMBEDDING_ENGINE_URL:-http://localhost:8000}"

FULL_SWEEP="${FULL_SWEEP:-1}"
RESET_SWEEP="${RESET_SWEEP:-0}"
MAX_INDEX_ROUNDS="${MAX_INDEX_ROUNDS:-30}"
INDEX_RETRY_SLEEP_SEC="${INDEX_RETRY_SLEEP_SEC:-20}"

{
  echo "===== $(date '+%Y-%m-%d %H:%M:%S %Z') slack-sync-all start ====="
  echo "root=$ROOT"
  echo "python=$PYTHON_BIN ($("$PYTHON_BIN" --version 2>/dev/null || true))"
  echo "SLACK_SWEEP_DAYS=$SLACK_SWEEP_DAYS"
  echo "SLACK_SQLITE_DB=$SLACK_SQLITE_DB"
  echo "SLACK_SWEEP_REPO_ID=$SLACK_SWEEP_REPO_ID"
  echo "SLACK_SWEEP_SNAPSHOT_ID=$SLACK_SWEEP_SNAPSHOT_ID"
  echo "EMBEDDING_ENGINE_URL=$EMBEDDING_ENGINE_URL"

  # Step 1: fetch Slack data into SQLite
  fetch_cmd=("$PYTHON_BIN" tools/fetch_slack.py)
  if [ "$FULL_SWEEP" = "1" ]; then
    fetch_cmd+=(--full)
  fi
  if [ "$RESET_SWEEP" = "1" ]; then
    fetch_cmd+=(--reset)
  fi

  echo "[fetch] running: ${fetch_cmd[*]}"
  set +e
  "${fetch_cmd[@]}"
  fetch_status=$?
  set -e
  if [ $fetch_status -ne 0 ]; then
    echo "[slack-sync-all] fetch failed with exit $fetch_status"
    echo "===== $(date '+%Y-%m-%d %H:%M:%S %Z') slack-sync-all end (exit $fetch_status) ====="
    exit $fetch_status
  fi

  # Step 2: keep indexing until pending rows are 0 or rounds are exhausted
  prev_pending=-1
  stall_rounds=0

  round=1
  while [ "$round" -le "$MAX_INDEX_ROUNDS" ]; do
    echo "[index] round $round/$MAX_INDEX_ROUNDS"

    set +e
    "$PYTHON_BIN" tools/index_slack.py
    index_status=$?
    set -e

    read -r total indexed pending < <(counts_from_db)
    echo "[index] status=$index_status total=$total indexed=$indexed pending=$pending"

    if [ "$pending" -eq 0 ]; then
      echo "[slack-sync-all] completed: all rows indexed"
      echo "===== $(date '+%Y-%m-%d %H:%M:%S %Z') slack-sync-all end (exit 0) ====="
      exit 0
    fi

    if [ "$pending" -eq "$prev_pending" ]; then
      stall_rounds=$((stall_rounds + 1))
    else
      stall_rounds=0
    fi
    prev_pending="$pending"

    if [ "$stall_rounds" -ge 3 ]; then
      echo "[slack-sync-all] no indexing progress for 3 rounds; stopping"
      echo "===== $(date '+%Y-%m-%d %H:%M:%S %Z') slack-sync-all end (exit 2) ====="
      exit 2
    fi

    round=$((round + 1))
    sleep "$INDEX_RETRY_SLEEP_SEC"
  done

  echo "[slack-sync-all] reached max index rounds with pending rows remaining"
  read -r total indexed pending < <(counts_from_db)
  echo "[slack-sync-all] final counts total=$total indexed=$indexed pending=$pending"
  echo "===== $(date '+%Y-%m-%d %H:%M:%S %Z') slack-sync-all end (exit 3) ====="
  exit 3
} | tee -a "$LOG_FILE"