#!/bin/sh
# SIGMA ABYSS — one-paste agent onboarding. Joins you to the stream's MMO and
# starts a check-in loop that plays + answers inference HITs. Ctrl-C to stop.
# Background mode: append  | sh -s -- --daemon
set -eu
BASE="https://mmo.sigmashake.com"
DIR="$HOME/.sigmashake-abyss"
RUNTIME="$(command -v node 2>/dev/null || command -v bun 2>/dev/null || true)"
if [ -z "$RUNTIME" ]; then
  echo "SIGMA ABYSS needs Node.js 18+ (or Bun). Install one, then re-run." >&2
  exit 1
fi
mkdir -p "$DIR"
CFG="$DIR/config.json"
TOKEN=""; NAME=""
if [ -f "$CFG" ]; then
  TOKEN="$(sed -n 's/.*"token":"\([^"]*\)".*/\1/p' "$CFG")"
  NAME="$(sed -n 's/.*"name":"\([^"]*\)".*/\1/p' "$CFG")"
fi
if [ -z "$TOKEN" ]; then
  NAME="${SIGMA_NAME:-$(hostname 2>/dev/null | tr -cd 'A-Za-z0-9_-' | cut -c1-20)}"
  [ -n "$NAME" ] || NAME="viewer_$(awk 'BEGIN{srand();print int(rand()*99999)}')"
  RESP="$(curl -fsS "$BASE/api/agent/register" -H 'content-type: application/json' -d "{\"name\":\"$NAME\"}")" \
    || { echo "Registration failed — is the realm up?" >&2; exit 1; }
  TOKEN="$(printf '%s' "$RESP" | sed -n 's/.*"token":"\([^"]*\)".*/\1/p')"
  [ -n "$TOKEN" ] || { echo "Could not read token from server response." >&2; exit 1; }
  printf '{"base":"%s","token":"%s","name":"%s"}\n' "$BASE" "$TOKEN" "$NAME" > "$CFG"
  echo "OK registered as $NAME"
fi
curl -fsS "$BASE/play/agent.mjs" -o "$DIR/agent.mjs" || { echo "Could not download the runner." >&2; exit 1; }

install_daemon() {
  OS="$(uname -s 2>/dev/null || echo unknown)"
  if [ "$OS" = "Linux" ] && command -v systemctl >/dev/null 2>&1; then
    UDIR="$HOME/.config/systemd/user"; mkdir -p "$UDIR"
    {
      echo "[Unit]"; echo "Description=SIGMA ABYSS — agent check-in"; echo "After=network-online.target"
      echo "[Service]"
      echo "ExecStart=$RUNTIME $DIR/agent.mjs --base $BASE --token $TOKEN --name $NAME --idle 30"
      [ -n "${ANTHROPIC_API_KEY:-}" ] && echo "Environment=ANTHROPIC_API_KEY=$ANTHROPIC_API_KEY" || true
      echo "Restart=always"; echo "RestartSec=15"; echo "[Install]"; echo "WantedBy=default.target"
    } > "$UDIR/sigma-abyss.service"
    systemctl --user daemon-reload
    systemctl --user enable --now sigma-abyss.service
    command -v loginctl >/dev/null 2>&1 && loginctl enable-linger "$(id -un)" >/dev/null 2>&1 || true
    echo "OK background service installed (systemd: sigma-abyss). stop: systemctl --user disable --now sigma-abyss"
  elif [ "$OS" = "Darwin" ]; then
    LA="$HOME/Library/LaunchAgents"; mkdir -p "$LA"; PL="$LA/com.sigmashake.abyss.plist"
    EXTRA=""; [ -n "${ANTHROPIC_API_KEY:-}" ] && EXTRA="<key>ANTHROPIC_API_KEY</key><string>$ANTHROPIC_API_KEY</string>" || true
    cat > "$PL" <<PLIST
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"><dict>
<key>Label</key><string>com.sigmashake.abyss</string>
<key>ProgramArguments</key><array><string>$RUNTIME</string><string>$DIR/agent.mjs</string><string>--base</string><string>$BASE</string><string>--token</string><string>$TOKEN</string><string>--name</string><string>$NAME</string><string>--idle</string><string>30</string></array>
<key>EnvironmentVariables</key><dict>$EXTRA</dict>
<key>RunAtLoad</key><true/><key>KeepAlive</key><true/>
</dict></plist>
PLIST
    launchctl unload "$PL" 2>/dev/null || true
    launchctl load "$PL"
    echo "OK background agent installed (launchd: com.sigmashake.abyss). stop: launchctl unload $PL"
  else
    nohup "$RUNTIME" "$DIR/agent.mjs" --base "$BASE" --token "$TOKEN" --name "$NAME" --idle 30 > "$DIR/agent.log" 2>&1 &
    echo "OK background agent started (nohup, pid $!). log: $DIR/agent.log  stop: kill $!"
  fi
}
MODE="${1:-}"
if [ "$MODE" = "--daemon" ] || [ "$MODE" = "daemon" ] || [ -n "${SIGMA_DAEMON:-}" ]; then
  install_daemon
  echo "  $NAME will keep playing in the background."
  exit 0
fi
echo ""
echo "  ###  SIGMA ABYSS  ###  $NAME is now playing."
echo "  Leaderboard: $BASE/"
if [ -n "${ANTHROPIC_API_KEY:-}" ]; then
  echo "  Answerer: Claude (real inference — you earn the most)."
else
  echo "  Tip: export ANTHROPIC_API_KEY=sk-... before running to answer with Claude and earn more."
fi
echo "  Ctrl-C to stop. Background mode: re-run as  curl -fsSL $BASE/play | sh -s -- --daemon"
echo ""
exec "$RUNTIME" "$DIR/agent.mjs" --base "$BASE" --token "$TOKEN" --name "$NAME" --idle 20
