#!/bin/bash

# run_daily_rewards.sh
# 
# This script handles the daily execution of reward calculation and distribution.
# It determines the target date (Yesterday) and runs the dependent cron tasks.
#
# Usage: ./run_daily_rewards.sh [YYYY-MM-DD]
# If date is not provided, defaults to Yesterday.


# Ensure we are in the backend directory
# detailed path resolution to handle execution from anywhere
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
BACKEND_DIR="$(dirname "$SCRIPT_DIR")"
cd "$BACKEND_DIR"

# 1. Activate Virtual Environment
if [ -f "venv/bin/activate" ]; then
    source venv/bin/activate
else
    echo "Error: venv not found at $BACKEND_DIR/venv"
    exit 1
fi

# 2. Determine Target Date
# Pass argument 1 if present, otherwise calculate "Yesterday"
if [ -n "$1" ]; then
    TARGET_DATE="$1"
else
    # Use python -c directly to avoid manage.py shell banners/noise
    TARGET_DATE=$(python -c "import os, django; os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings'); django.setup(); from django.utils import timezone; from datetime import timedelta; print((timezone.localtime(timezone.now()) - timedelta(days=1)).date().isoformat())")
fi

echo "[$(date)] Starting Daily Reward Process for Date: $TARGET_DATE"

# 3. Run Phase 1: Calculate Rewards (R001)
echo "Running Phase 1: Calculate Rewards (R001)..."
python manage.py run_cron_task calculate-rewards "$TARGET_DATE"
EXIT_CODE=$?

if [ $EXIT_CODE -ne 0 ]; then
    echo "Error: Calculate Rewards task failed with exit code $EXIT_CODE. Aborting."
    exit $EXIT_CODE
fi

# 4. Run Phase 2: Distribute Rewards (D001)
# Note: Task D001 includes an internal dependency check on R001 success,
# but we also check exit code here for script robustness.
echo "Running Phase 2: Distribute Rewards (D001)..."
python manage.py run_cron_task distribute-rewards "$TARGET_DATE"
EXIT_CODE=$?

if [ $EXIT_CODE -ne 0 ]; then
    echo "Error: Distribute Rewards task failed with exit code $EXIT_CODE."
    exit $EXIT_CODE
fi

echo "[$(date)] Daily Reward Process Completed Successfully."
