#!/usr/bin/env bash
# Pueue-friendly backfill wrapper for a single (symbol, year, threshold) job.
# Version-gated: auto-detects and fixes version drift before processing.
#
# Usage (via pueue):
#   pueue add --group btc500 --label "BTCUSDT@500_2023" -- \
#       bash scripts/pueue_backfill.sh BTCUSDT 2023 500
#
# Issue #254: version gate prevents running stale binaries that OOM.
set -euo pipefail
cd /home/tca/opendeviationbar-py
source deploy/opendeviationbar.local.env 2>/dev/null || true
export OPENDEVIATIONBAR_CH_HOSTS=localhost
export OPENDEVIATIONBAR_MODE=local

SYMBOL="${1:?Usage: pueue_backfill.sh SYMBOL YEAR THRESHOLD}"
YEAR="${2:?Usage: pueue_backfill.sh SYMBOL YEAR THRESHOLD}"
THRESHOLD="${3:?Usage: pueue_backfill.sh SYMBOL YEAR THRESHOLD}"

# Telegram notification on ANY failure (trap runs on non-zero exit)
_notify_failure() {
    local exit_code=$?
    if [ $exit_code -ne 0 ]; then
        local installed
        installed=$(.venv/bin/python3 -c 'import opendeviationbar; print(opendeviationbar.__version__)' 2>/dev/null || echo 'unknown')
        local msg="❌ <b>Backfill FAILED</b>: ${SYMBOL}@${THRESHOLD} (${YEAR})"
        msg+="\nExit code: ${exit_code}"
        msg+="\nVersion: v${installed}"
        msg+="\nHost: $(hostname)"
        local token="${OPENDEVIATIONBAR_TELEGRAM_TOKEN:-}"
        local chat_id="${OPENDEVIATIONBAR_TELEGRAM_CHAT_ID:-90417581}"
        if [ -n "$token" ]; then
            curl -sf -X POST "https://api.telegram.org/bot${token}/sendMessage" \
                -d chat_id="$chat_id" \
                -d parse_mode=HTML \
                -d "text=${msg}" >/dev/null 2>&1 || true
        fi
    fi
}
trap _notify_failure EXIT

# --- Version Gate (Issue #254) ---
# Prevents running stale code (v13.0.x OOM'd on high-volume days; v13.1+ streams).
INSTALLED=$(.venv/bin/python3 -c 'import opendeviationbar; print(opendeviationbar.__version__)' 2>/dev/null || echo 'unknown')
GITHUB_TAG=$(gh api repos/terrylica/opendeviationbar-py/releases/latest --jq '.tag_name' 2>/dev/null | sed 's/^v//' || echo 'unknown')

if [ "$INSTALLED" != "$GITHUB_TAG" ] && [ "$GITHUB_TAG" != "unknown" ] && [ "$INSTALLED" != "unknown" ]; then
    echo "VERSION DRIFT: installed=v${INSTALLED} github=v${GITHUB_TAG}"
    echo "Auto-fixing: uv pip uninstall + install from PyPI..."
    uv pip uninstall --python .venv/bin/python3 opendeviationbar 2>/dev/null || true
    uv pip install --python .venv/bin/python3 "opendeviationbar==${GITHUB_TAG}"
    INSTALLED=$(.venv/bin/python3 -c 'import opendeviationbar; print(opendeviationbar.__version__)' 2>/dev/null || echo 'unknown')
    echo "Fixed: now running v${INSTALLED}"
fi

# --- .pth Guard (Issue #254) ---
# Editable install .pth files shadow the PyPI wheel — nuke them.
SITE_PKG=$(.venv/bin/python3 -c 'import site; print(site.getsitepackages()[0])' 2>/dev/null)
if [ -f "${SITE_PKG}/opendeviationbar.pth" ]; then
    echo ".pth SHADOW detected — forcing clean reinstall"
    uv pip uninstall --python .venv/bin/python3 opendeviationbar 2>/dev/null || true
    uv pip install --python .venv/bin/python3 "opendeviationbar==${GITHUB_TAG:-${INSTALLED}}"
    INSTALLED=$(.venv/bin/python3 -c 'import opendeviationbar; print(opendeviationbar.__version__)' 2>/dev/null || echo 'unknown')
fi

echo "Starting backfill: ${SYMBOL}@${THRESHOLD} (${YEAR}) with opendeviationbar v${INSTALLED}"

.venv/bin/python3 -c "
from opendeviationbar import populate_cache_resumable
populate_cache_resumable(
    symbol='${SYMBOL}',
    start_date='${YEAR}-01-01',
    end_date='${YEAR}-12-31',
    threshold_decimal_bps=${THRESHOLD},
    include_microstructure=True,
    notify=True,
    verbose=True,
)
"

echo "Completed: ${SYMBOL}@${THRESHOLD} (${YEAR}) with opendeviationbar v${INSTALLED}"
