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

MODE="${1:-reuse}"
repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)"
cd "$repo_root"

case "$MODE" in
  full|reuse|dry-run) ;;
  *)
    echo "Usage: $0 [full|reuse|dry-run]" >&2
    exit 1
    ;;
esac

export PARTY2D_RAW_DATA_DIR="${PARTY2D_RAW_DATA_DIR:-$repo_root/_local/raw}"
export TMPDIR="${TMPDIR:-$repo_root/_local/tmp}"
mkdir -p "$TMPDIR"

required_model_inputs=(
  "data/text_data.csv"
  "data/expert.csv"
  "data/lr_data.csv"
  "data/union_mapping.csv"
  "data/party_families.csv"
)

if [ "$MODE" = "dry-run" ]; then
  echo "Checking commands..."
  command -v bash >/dev/null
  command -v julia >/dev/null
  echo "Checking key files..."
  test -f Project.toml
  test -f Manifest.toml
  test -f models/stan_model_2dim_v6.stan
  for input in "${required_model_inputs[@]}"; do
    test -f "$input"
  done
  echo "Checking shell syntax..."
  bash -n scripts/01_prepare_data.sh
  bash -n scripts/02_fit_model.sh
  bash -n scripts/03_extract_estimates.sh
  bash -n scripts/04_enrich_estimates.sh
  bash -n scripts/05_validate_estimates.sh
  bash -n data-setup/run_data_setup.sh
  bash -n data-setup/check_raw_data.sh
  echo "Checking Julia project can instantiate without running model code..."
  julia --project=. -e 'import Pkg; Pkg.instantiate(); println("Julia project OK")'
  echo "Dry run passed. No model fitting was run."
  exit 0
fi

bash scripts/01_prepare_data.sh

if [ "$MODE" = "full" ]; then
  bash scripts/02_fit_model.sh
else
  echo "reuse: skipping Stan model fitting; using latest existing model output"
fi

bash scripts/03_extract_estimates.sh
bash scripts/04_enrich_estimates.sh
bash scripts/05_validate_estimates.sh
