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

BASE="/mnt/bigstor/www/usecases"
ENV_FILE="$BASE/.env"
VENV="$BASE/.venv"
LOG_DIR="$BASE/logs"
LOCK_FILE="/tmp/ncrc-daily.lock"
DAILY="$BASE/collect_daily_status.sh"

mkdir -p "$LOG_DIR"

exec >>"$LOG_DIR/daily.log" 2>&1

echo
echo "============================================================"
echo "NCRC daily cron started: $(date --iso-8601=seconds)"
echo "============================================================"

cd "$BASE"

# Prevent simultaneous daily runs.
if ! command -v flock >/dev/null 2>&1; then
    echo "ERROR: flock not found"
    exit 1
fi

exec 9>"$LOCK_FILE"
if ! flock -n 9; then
    echo "SKIP: another NCRC daily run is already active"
    exit 0
fi

# Load secrets/API configuration.
if [[ ! -r "$ENV_FILE" ]]; then
    echo "ERROR: cannot read $ENV_FILE"
    exit 1
fi

set -a
# shellcheck disable=SC1090
source "$ENV_FILE"
set +a

# Validate required environment variables WITHOUT printing secrets.
required=(
    GITHUB_TOKEN
    OPENALEX_API_KEY
    S2_API_KEY
    CONTACT_EMAIL
)

for var in "${required[@]}"; do
    if [[ -z "${!var:-}" ]]; then
        echo "ERROR: required environment variable $var is missing"
        exit 1
    fi
done

echo "Environment: required API variables are set"

# Force Python commands used by the pipeline into this virtual environment.
if [[ ! -x "$VENV/bin/python3" ]]; then
    echo "ERROR: $VENV/bin/python3 not found"
    exit 1
fi

export PATH="$VENV/bin:/usr/local/bin:/usr/bin:/bin"
export PYTHONUNBUFFERED=1

if [[ ! -x "$DAILY" ]]; then
    echo "ERROR: $DAILY does not exist or is not executable"
    exit 1
fi

echo "Python: $(command -v python3)"
echo "Daily runner: $DAILY"

set +e
"$DAILY"
rc=$?
set -e

if [[ $rc -eq 0 ]]; then
    echo "NCRC daily cron completed successfully: $(date --iso-8601=seconds)"
else
    echo "ERROR: NCRC daily cron failed with exit code $rc: $(date --iso-8601=seconds)"
fi

exit "$rc"
