#!/bin/bash
# Waits for enumeration to finish, then runs the full downstream pipeline.
LOG=/tmp/pipeline.log
exec >> "$LOG" 2>&1
echo "=== finish_pipeline START $(date +%H:%M:%S) ==="

# 1) wait for enumeration
while [ ! -f /tmp/enum_DONE ]; do sleep 60; done
echo "enum DONE detected $(date +%H:%M:%S)"

cd /tmp

# 2) fetch contacts (get_updated_patients) -- handles its own cooldown
echo "--- fetch_contacts ---"
python3 -u /tmp/fetch_contacts.py || echo "fetch_contacts FAILED (will fall back to 6/15 report)"

# 3) resolve 4 pending Sheet-1 candidates -- handles its own cooldown
echo "--- resolve_s1_pending ---"
python3 -u /tmp/resolve_s1_pending.py || echo "resolve_s1 FAILED"

# 4) compute Sheet 2 from day-files (+ updated_patients contacts merged in compute step)
echo "--- compute_s2_final ---"
python3 -u /tmp/compute_s2_final.py || { echo "compute FAILED, abort"; exit 1; }

# 5) build workbook in-place from current download
echo "--- build_final ---"
python3 -u /tmp/build_final.py || { echo "build FAILED, abort"; exit 1; }

# 6) refresh token + upload + verify
echo "--- refresh token + upload ---"
bash /tmp/refresh_token.sh
python3 -u /tmp/upload_verify.py || { echo "upload FAILED, abort"; exit 1; }

# 7) re-read uploaded workbook to verify Sheet 2 populated
echo "--- verify re-read ---"
bash /tmp/refresh_token.sh
python3 -u /tmp/verify_reread.py || echo "verify reread FAILED"

echo "=== finish_pipeline DONE $(date +%H:%M:%S) ==="
touch /tmp/pipeline_DONE
