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

# Change to project root (where this script lives)
cd "$(dirname "$0")"

# Install system dependencies not covered by rv sysdeps
echo "Installing system dependencies..."
case "$(uname -s)" in
    Linux*)
        if command -v apt-get &> /dev/null; then
            sudo apt-get install -y libopenblas-dev
        else
            echo "Warning: apt-get not found. Please install OpenBLAS manually."
        fi
        ;;
    Darwin*)
        if command -v brew &> /dev/null; then
            brew install openblas
        else
            echo "Warning: Homebrew not found. Please install OpenBLAS manually."
        fi
        ;;
    *)
        echo "Warning: Unsupported OS '$(uname -s)'. Please install OpenBLAS manually."
        ;;
esac

# Check if rv is installed
if ! command -v rv &> /dev/null; then
    echo "Error: rv is not installed."
    echo "Install it from https://github.com/A2-ai/rv#installation"
    exit 1
fi

# Sync packages (rv handles the "nothing to do" case automatically)
echo "Syncing R packages..."
rv sync

# Activate if not already activated
if [ -f .Rprofile ] && grep -q "rv/scripts" .Rprofile 2>/dev/null; then
    echo "rv already activated."
else
    echo "Activating rv..."
    rv activate
fi

# Create output and log directories (gitignored, so not present after clone)
echo "Creating output directories..."
mkdir -p logs/similarity_exp logs/logo_exp
mkdir -p similarity_exp_replication/outputs/{figures,tables,h5-h6,tables/pnas-h6}
mkdir -p logo_exp_replication/outputs/{figures,tables,data}

echo ""
echo "Setup complete. You can now run any analysis script, e.g.:"
echo "  Rscript similarity_exp_replication/code/analysis/prereg_hypothesis1.R"
