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

DEPLOY="${OVERDECK_DEPLOY_DIR:-$HOME/.local/share/overdeck/deploy}"
REAL_PI="${OVERDECK_REAL_PI:-$HOME/.npm-global/bin/pi}"
AGENT_DIR="$DEPLOY/modules/workstation/pi/agent"

[[ -x "$REAL_PI" ]] || { printf 'pi: canonical executable missing: %s\n' "$REAL_PI" >&2; exit 1; }
[[ -x "$DEPLOY/bin/deckctl" ]] || { printf 'pi: canonical deckctl missing: %s\n' "$DEPLOY/bin/deckctl" >&2; exit 1; }
[[ -d "$AGENT_DIR" ]] || { printf 'pi: canonical agent directory missing: %s\n' "$AGENT_DIR" >&2; exit 1; }

rc=0
PI_CODING_AGENT_DIR="$AGENT_DIR" "$REAL_PI" "$@" || rc=$?
"$DEPLOY/bin/deckctl" sync pull pi \
  || { printf 'pi: settings persistence transaction failed\n' >&2; exit 1; }
exit "$rc"
