use flake

export PYTHONDONTWRITEBYTECODE=1
export PYTHONPYCACHEPREFIX="$PWD/.cache/pycache"
mkdir -p "$PYTHONPYCACHEPREFIX"

if [ -L result ]; then
  rm result
fi

# One-time cleanup of legacy repo-root cache dirs (migrated under .cache/).
legacy_stamp=".cache/.legacy-caches-migrated"
if [ ! -f "$legacy_stamp" ]; then
  for legacy_cache_root in __pycache__ .pytest_cache .hypothesis .mypy_cache .ruff_cache .benchmarks; do
    if [ -e "$legacy_cache_root" ]; then
      rm -rf "$legacy_cache_root"
    fi
  done
  touch "$legacy_stamp"
fi

# Clean stale __pycache__ dirs under source trees — skip if stamp
# is fresh (sources haven't changed since last cleanup).
pyc_stamp=".cache/.last-pyc-cleanup"
pyc_should_clean=1
if [ -f "$pyc_stamp" ]; then
  last_clean=$(stat -c %Y "$pyc_stamp" 2>/dev/null || echo 0)
  newest_src=$(find polylogue tests devtools -name '*.py' -printf '%T@\n' 2>/dev/null | sort -rn | head -1 | cut -d. -f1)
  if [ -n "$newest_src" ] && [ "$last_clean" -ge "$newest_src" ]; then
    pyc_should_clean=0
  fi
fi
if [ "$pyc_should_clean" -eq 1 ]; then
  find polylogue tests devtools -type d -name __pycache__ -prune -exec rm -r {} + 2>/dev/null || true
  touch "$pyc_stamp"
fi

case "${-}" in
  *i*)
    if command -v devtools >/dev/null 2>&1 && [ -z "${POLYLOGUE_MOTD_RENDERED:-}" ]; then
      devtools status || true
    fi
    ;;
esac

unset POLYLOGUE_MOTD_RENDERED
