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

usage() {
  cat <<'EOF'
Usage:
  jupytext_convert.sh to-py      # Convert all *.ipynb -> nb_*.py (py:percent)
  jupytext_convert.sh to-ipynb   # Convert all nb_*.py -> *.ipynb

Notes:
  - Skips .ipynb_checkpoints.
  - Output .py files are prefixed with "nb_" so you can filter with nb_*.py.
  - Requires 'jupytext' in PATH (pip install jupytext).
EOF
}

require_jupytext() {
  if ! command -v jupytext >/dev/null 2>&1; then
    echo "Error: jupytext not found in PATH. Install with 'pip install jupytext'." >&2
    exit 1
  fi
}

to_py() {
  echo "Converting *.ipynb -> nb_*.py (py:percent)..."
  # Find notebooks, skip .ipynb_checkpoints
  find . -type f -name "*.ipynb" ! -path "*/.ipynb_checkpoints/*" ! -path "*/.venv/*" -print0 |
  while IFS= read -r -d '' nb; do
    dir=$(dirname "$nb")
    base=$(basename "$nb" .ipynb)
    out="$dir/nb_${base}.py"
    echo "  - $nb -> $out"
    jupytext --to py:percent -o "$out" "$nb"
  done
  echo "Done."
}

to_ipynb() {
  echo "Converting nb_*.py -> *.ipynb..."
  find . -type f -name "nb_*.py" ! -path "*/.venv/*" -print0 |
  while IFS= read -r -d '' py; do
    dir=$(dirname "$py")
    base=$(basename "$py" .py)
    # Strip the nb_ prefix when producing the .ipynb filename
    bare="${base#nb_}"
    out="$dir/${bare}.ipynb"
    echo "  - $py -> $out"
    jupytext --to ipynb -o "$out" "$py"
  done
  echo "Done."
}

main() {
  [[ $# -eq 1 ]] || { usage; exit 1; }
  require_jupytext
  case "$1" in
    py) to_py ;;
    nb) to_ipynb ;;
    -h|--help) usage ;;
    *) echo "Unknown command: $1"; usage; exit 1 ;;
  esac
}

main "$@"
