#!/usr/bin/env bash
# Wrapper for building study cards with automatic Nix shell entry
set -euo pipefail

TUFTE_PRESS_REPO="${TUFTE_PRESS_REPO:-$HOME/proj/tufte-press}"

if [[ ! -d "$TUFTE_PRESS_REPO" ]]; then
    echo "Error: tufte-press repository not found at: $TUFTE_PRESS_REPO" >&2
    echo "Set TUFTE_PRESS_REPO environment variable" >&2
    exit 1
fi

if [[ ! -f "$TUFTE_PRESS_REPO/flake.nix" ]]; then
    echo "Error: tufte-press flake.nix not found" >&2
    exit 1
fi

# Check if we're already in a Nix shell with the right tools
if command -v tectonic &>/dev/null && command -v python3 &>/dev/null; then
    # Already in dev environment, run directly
    exec "$TUFTE_PRESS_REPO/scripts/card-build.sh" "$@"
else
    # Enter Nix shell and run
    echo "Entering tufte-press development environment..." >&2
    cd "$TUFTE_PRESS_REPO"
    exec nix develop --accept-flake-config -c "$TUFTE_PRESS_REPO/scripts/card-build.sh" "$@"
fi
