#!/bin/bash
set -e

BAM="resources/hg38_no_alt.bam.sorted"
EXPECTED_SIZE=141726838805
CHECK_INTERVAL=120  # seconds between checks
STABLE_CHECKS=3     # require size unchanged for this many consecutive checks

echo "[$(date)] Waiting for download to complete (expected: $EXPECTED_SIZE bytes)..."

prev_size=0
stable_count=0

while true; do
    current_size=$(stat -c%s "$BAM" 2>/dev/null || echo 0)
    pct=$(echo "scale=1; $current_size * 100 / $EXPECTED_SIZE" | bc)
    echo "[$(date)] Size: $current_size / $EXPECTED_SIZE bytes (${pct}%)"

    if [ "$current_size" -eq "$EXPECTED_SIZE" ]; then
        if [ "$current_size" -eq "$prev_size" ]; then
            stable_count=$((stable_count + 1))
            echo "[$(date)] Stable check $stable_count/$STABLE_CHECKS"
            if [ "$stable_count" -ge "$STABLE_CHECKS" ]; then
                echo "[$(date)] Download confirmed complete."
                break
            fi
        else
            stable_count=1
        fi
    else
        stable_count=0
    fi

    prev_size=$current_size
    sleep $CHECK_INTERVAL
done

# Remove any stale index from the old file
rm -f "${BAM}.bai"

# Index the new file
echo "[$(date)] Running samtools index..."
module load samtools/1.16.1
samtools index "$BAM"
echo "[$(date)] Index created: ${BAM}.bai"

# Re-run off-target scoring
echo "[$(date)] Re-running off-target scoring step..."
conda run -n CRISPRDesigner2 snakemake \
    --configfile config/config.yaml \
    --cores 4 \
    --forcerun score_offtarget 2>&1

# Run validation tests
echo "[$(date)] Running validation tests..."
conda run -n CRISPRDesigner2 python -m pytest \
    tests/test_validation_GATA1PPIF.py -v 2>&1

echo "[$(date)] All done."
