#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")/backend"
PYTHON=${PYTHON:-python3}
[ -d .venv ] || "$PYTHON" -m venv .venv
. .venv/bin/activate
python -m pip install --upgrade pip
python -m pip install -r requirements.txt
if [ ! -f .env.local ]; then
  SECRET=$(python -c 'import secrets; print(secrets.token_urlsafe(48))')
  cat > .env.local <<EOF
DJANGO_SECRET_KEY=$SECRET
DJANGO_DEBUG=True
DJANGO_ALLOWED_HOSTS=127.0.0.1,localhost
DB_ENGINE=sqlite
APP_TIME_ZONE=Asia/Dhaka
BACKUP_DIR=./backups
BACKUP_RETENTION_DAYS=30
LOGIN_MAX_FAILED_ATTEMPTS=5
LOGIN_LOCKOUT_MINUTES=15
EOF
fi

# Controlled migration rule: normal setup must consume reviewed/frozen migrations.
if ! find apps -path '*/migrations/*.py' ! -name '__init__.py' -type f -print -quit | grep -q .; then
  echo "Frozen migration files are missing. Run 00-freeze-migrations-linux.sh (or the Windows freeze tool) on the reviewed source first." >&2
  exit 1
fi
python manage.py makemigrations --check --dry-run
python manage.py migrate
python manage.py first_run_setup --with-demo-data
python manage.py check
python manage.py first_run_status
