#!/usr/bin/env bash
# Funkuino command dispatcher — the shell half.
#
# All it does is pick the interpreter that has our dependencies and hand over to
# scripts/cli.py, which is the actual dispatcher (and is also what the installed
# `funkuino` console script runs). Two copies of the command routing, one in
# bash and one in Python, would drift; this way a checkout, the macOS bundle and
# a pip install all execute the same code.
#
# Why the dispatcher exists rather than the plain ./sync, ./download … wrappers:
# the Studio agent's permission rules are TEXT patterns matched against the Bash
# command (studio_agent.py ALLOWED_TOOLS / ASK_RULES). Relative wrappers only
# match while the agent's cwd is the checkout — in a packaged app the code sits
# read-only inside the bundle and the data folder is elsewhere. Putting this
# directory on PATH keeps the invocation a bare, canonical `funkuino sync …`
# that the rules can match no matter where code and data live. A path handed to
# the agent in an environment variable would NOT work: `$FUNKUINO_HOME/sync`,
# "${FUNKUINO_HOME}/sync" and the expanded absolute path are all different
# strings, so an ask rule would be one spelling away from being bypassed.
set -euo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
# Packaged app: an interpreter with the dependencies ships next to the code.
# Checkout: the project venv. They never coexist, so the order is arbitrary.
if [[ -x "$ROOT/runtime/bin/python3" ]]; then
    PY="$ROOT/runtime/bin/python3"
else
    PY="$ROOT/.venv/bin/python"
fi

if [[ ! -x "$PY" ]]; then
    echo "Project venv missing. Create it with:" >&2
    echo "  python3 -m venv .venv && .venv/bin/pip install -r requirements.txt" >&2
    echo "(or install Funkuino with: pipx install funkuino)" >&2
    exit 1
fi

exec "$PY" -c 'import sys
sys.path.insert(0, sys.argv[1])
import cli
sys.exit(cli.main(sys.argv[2:]))' "$ROOT/scripts" "$@"
