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

usage() {
  cat <<'EOF'
Usage: process_day.sh [YYYY-MM-DD]

Environment overrides:
  PROCESS_BIN   Processor command path (default: ./bin/twitter-process)
EOF
}

if [[ "${1:-}" == "-h" || "${1:-}" == "--help" ]]; then
  usage
  exit 0
fi

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
DATE_ISO="${1:-$(date +%F)}"
LOCK="/tmp/twitter-process-${DATE_ISO}.lock"
PROCESS_BIN="${PROCESS_BIN:-./bin/twitter-process}"
DAY_DIR="${ROOT}/PHASES/PHASE-01-INGEST/tweets/archive/${DATE_ISO}"
RAW_FILE="${DAY_DIR}/raw_feed.csv"

mkdir -p "${ROOT}/PHASES/PHASE-01-INGEST/logs/process" "${DAY_DIR}"

exec 9>"${LOCK}"
flock -n 9 || { echo "[process] already running date=${DATE_ISO}"; exit 0; }

cd "${ROOT}"
if [[ -f "${ROOT}/venv/bin/activate" ]]; then
  # shellcheck source=/dev/null
  source "${ROOT}/venv/bin/activate"
fi

if [[ ! -x "${PROCESS_BIN}" ]]; then
  echo "[process] ERROR: processor binary not executable: ${PROCESS_BIN}"
  exit 2
fi

if [[ ! -f "${RAW_FILE}" ]]; then
  echo "[process] ERROR: missing ${RAW_FILE}"
  exit 2
fi

echo "[process] start date=${DATE_ISO} time=$(date -Is)"
"${PROCESS_BIN}" "${DATE_ISO}"
echo "[process] done date=${DATE_ISO} time=$(date -Is)"
