#!/usr/bin/env bash
set -euo pipefail
ROOT="$(cd "$(dirname "$0")" && pwd)"
cd "$ROOT/backend"
PY=".venv/bin/python"
PYTHON=${PYTHON:-python3}
RESULT="$ROOT/MIGRATION-FREEZE-RESULT.txt"
: > "$RESULT"
log(){ echo "$*" | tee -a "$RESULT"; }
log "HRPAY Migration Freeze"
log "Project: HRPAY-BMD-20260911-01"
log "Version: v0.39.4-dev"
log "Started: $(date '+%Y-%m-%d %H:%M:%S')"
if [[ ! -x "$PY" ]]; then
  log "Python virtual environment not found; preparing migration-freeze environment..."
  "$PYTHON" -m venv .venv
fi
if ! "$PY" -c 'import django' >/dev/null 2>&1; then
  log "Django dependencies are missing/incomplete; installing project requirements..."
  if [[ -d "$ROOT/wheelhouse" ]] && find "$ROOT/wheelhouse" -maxdepth 1 -type f -print -quit | grep -q .; then
    "$PY" -m pip install --no-index --find-links "$ROOT/wheelhouse" -r requirements.txt
  else
    "$PY" -m pip install -r requirements.txt
  fi
fi
export DJANGO_DEBUG=True DJANGO_SECRET_KEY=migration-freeze-only-not-for-runtime DB_ENGINE=sqlite DJANGO_ALLOWED_HOSTS=127.0.0.1,localhost
log "Python: $($PY -c 'import sys; print(sys.version.split()[0])')"
log "Django: $($PY -c 'import django; print(django.get_version())')"
log "Running Django system check before migration generation..."
"$PY" manage.py check 2>&1 | tee -a "$RESULT"
log "Generating migration files from reviewed model state..."
"$PY" manage.py makemigrations --noinput 2>&1 | tee -a "$RESULT"
log "Checking migration drift..."
"$PY" manage.py makemigrations --check --dry-run 2>&1 | tee -a "$RESULT"
mapfile -t files < <(find apps -path '*/migrations/*.py' ! -name '__init__.py' -type f | sort)
if [[ ${#files[@]} -eq 0 ]]; then log "RESULT: FAIL - no frozen migration files produced"; exit 1; fi
log "Frozen migration files: ${#files[@]}"
for f in "${files[@]}"; do log "$(sha256sum "$f" | awk '{print $1}')  backend/$f"; done
log "Completed: $(date '+%Y-%m-%d %H:%M:%S')"
log "RESULT: PASS - migration snapshot generated and hashed."
