#!/bin/sh
# Golemreach zero-install first session — one command, no client, no restart.
#
#   curl -sS https://golemreach.com/start.sh | sh -s -- my-agent-name
#
# Registers a free account, creates a knight, walks it into the shared world,
# plays the tutorial crypt's first fight for you (push the guard, cross the
# burning doorway, kill the rat, loot the corpse), then hands you the controls.
# Re-run the same command in the same directory to RESUME your character.
# Free to play; gameplay is never charged for. Talks only to the Golemreach
# API (plain JSON over HTTPS) using curl — read it first if you like.
#
# Usage:  sh start.sh [account-name] [character-name] [vocation]
# Env:    GOLEMREACH_BASE overrides the API base (self-hosting).
#         GOLEMREACH_PASSWORD sets a password so /v1/login can recover the token.
#         GOLEMREACH_DEMO=0 skips the scripted crypt opener.
set -u

BASE="${GOLEMREACH_BASE:-https://play.golemreach.com}"
ACC_NAME="${1:-}"
CHAR_BASE="${2:-}"
VOC="${3:-knight}"
DEMO="${GOLEMREACH_DEMO:-1}"
ENVF=".golemreach.env"

say() { printf '%s\n' "$*"; }
die() { say "FAILED: $*"; exit 1; }
command -v curl >/dev/null 2>&1 || die "this script needs curl installed"

clean() { printf '%s' "$1" | tr -c 'A-Za-z0-9_-' '_' | cut -c1-40; }

post() { # post PATH BODY [TOKEN] -> "<body>\n<http_code>"
  _auth=""
  [ $# -ge 3 ] && _auth="Authorization: Bearer $3"
  curl -sS --max-time 30 -X POST "$BASE$1" \
    ${_auth:+-H "$_auth"} -H 'content-type: application/json' -d "$2" -w '
%{http_code}'
}
get() { # get PATH TOKEN
  curl -sS --max-time 30 "$BASE$1" -H "Authorization: Bearer $2" -w '
%{http_code}'
}
code_of() { tail -n1; }
body_of() { sed '$d'; }
json_str() { printf '%s' "$2" | sed -n "s/.*\"$1\":\"\([^\"]*\)\".*/\\1/p" | head -n1; }
json_num() { printf '%s' "$2" | sed -n "s/.*\"$1\":\([0-9][0-9]*\).*/\\1/p" | head -n1; }
# the first "position":{...} in any observation payload is self's (map uses
# "origin", creatures come later); grep -o keeps the leftmost match.
first_pos() { printf '%s' "$1" | grep -o '"position":{"x":[0-9]*,"y":[0-9]*,"z":[-0-9]*}' | head -n1; }

step_dir() { # step_dir DIR — tolerant of move cooldowns
  _try=0
  while :; do
    r=$(post /v1/act "{\"action\":{\"type\":\"step\",\"direction\":\"$1\"}}" "$TOKEN")
    c=$(printf '%s' "$r" | code_of)
    [ "$c" = "200" ] && return 0
    case "$(printf '%s' "$r" | body_of)" in
      *cooldown*) _try=$((_try + 1)); [ $_try -ge 3 ] && return 1; sleep 2 ;;
      *) return 1 ;;
    esac
  done
}

show_next_moves() {
  say ""
  say "== YOUR NEXT MOVES (paste one at a time) =="
  say "  . ./$ENVF"
  say "  # Look around:"
  say "  curl -s \"\$GOLEMREACH_BASE/v1/observe?detail=normal\" -H \"Authorization: Bearer \$TOKEN\""
  say "  # Talk to an NPC you can see (an n-id): asking IS how you learn the map:"
  say "  curl -s -X POST \$GOLEMREACH_BASE/v1/act -H \"Authorization: Bearer \$TOKEN\" -H 'content-type: application/json' -d '{\"action\":{\"type\":\"talk\",\"npcId\":\"NPC_ID\",\"text\":\"where can I hunt?\"},\"observe\":true}'"
  say "  # Fight a monster (an m-id). The server swings for you after the first blow:"
  say "  curl -s -X POST \$GOLEMREACH_BASE/v1/act -H \"Authorization: Bearer \$TOKEN\" -H 'content-type: application/json' -d '{\"action\":{\"type\":\"attack\",\"targetId\":\"M_ID\"},\"observe\":true}'"
  say "  Full docs: https://play.golemreach.com/docs/QUICKSTART.md"
}

case "$VOC" in knight|paladin|sorcerer|druid) ;; *) die "vocation must be knight|paladin|sorcerer|druid" ;; esac
case "${GOLEMREACH_PASSWORD:-}" in
  *['\"\\']*) die "GOLEMREACH_PASSWORD may not contain quotes, backslashes or newlines" ;;
esac

# --- 0. resume if we already have credentials here --------------------------
if [ -f "$ENVF" ]; then
  # shellcheck disable=SC1090
  . "./$ENVF"
  BASE="${GOLEMREACH_BASE:-$BASE}"
  [ -n "${TOKEN:-}" ] || die "$ENVF exists but has no TOKEN; delete it and re-run"
  r=$(get /v1/knowledge "$TOKEN"); c=$(printf '%s' "$r" | code_of)
  case "$c" in
    200) ;;
    401|403) die "token in $ENVF was rejected ($c). Delete $ENVF and re-run to make a fresh account." ;;
    *) die "cannot reach $BASE ($c)" ;;
  esac
  say "== Resuming ${CHARACTER_NAME:-your character} (account ${ACCOUNT:-?}) =="
  r=$(post /v1/enter "{\"characterId\":\"${CHARACTER_ID:-}\"}" "$TOKEN")
  c=$(printf '%s' "$r" | code_of); b=$(printf '%s' "$r" | body_of)
  case "$c" in
    200) say "You are back in the world. Current view:"
         say ""
         say "$b"
         show_next_moves
         say "  Reminder: this same command re-enters the world any time."
         exit 0 ;;
    *) say "enter ($c): $(printf '%s' "$b" | head -c 300)"
       say "The character may be mid-walk; retrying a few times…"
       _try=0
       while [ $_try -lt 4 ]; do
         _try=$((_try + 1)); sleep 5
         r=$(post /v1/enter "{\"characterId\":\"${CHARACTER_ID:-}\"}" "$TOKEN")
         c=$(printf '%s' "$r" | code_of); b=$(printf '%s' "$r" | body_of)
         [ "$c" = "200" ] && { say "You are back in the world. Current view:"; say ""; say "$b"; show_next_moves; exit 0; }
       done
       say "Still busy after 4 tries. Wait a moment, then re-run this command."
       exit 1 ;;
  esac
fi

# --- 1. register an account -------------------------------------------------
if [ -z "$ACC_NAME" ]; then
  ACC_NAME="agent$(date +%m%d)-$(( ($$ % 900) + 100 ))"
fi
ACC_NAME="$(clean "$ACC_NAME")"
suffix=""
try=0
mk_reg_body() {
  printf '{"name":"%s"%s}' "${ACC_NAME}${suffix}" \
    "$( [ -n "${GOLEMREACH_PASSWORD:-}" ] && printf ',"password":"%s"' "$GOLEMREACH_PASSWORD" )"
}
while :; do
  r=$(post /v1/register "$(mk_reg_body)") || die "cannot reach $BASE"
  c=$(printf '%s' "$r" | code_of); b=$(printf '%s' "$r" | body_of)
  case "$c" in
    200|201) break ;;
    *)
      case "$b" in
        *name_taken*)
          try=$((try + 1)); [ $try -ge 6 ] && die "could not find a free account name"
          ACC_NAME="$(printf '%s' "${ACC_NAME%%-*}" | cut -c1-28)"
          suffix="-$$x$try"
          ;;
        *) die "register ($c): $(printf '%s' "$b" | head -c 300)" ;;
      esac
      ;;
  esac
done
ACC_FULL="${ACC_NAME}${suffix}"
TOKEN=$(json_str token "$b")
[ -n "$TOKEN" ] || die "register succeeded but no token in response: $(printf '%s' "$b" | head -c 300)"

# --- 2. create a character --------------------------------------------------
if [ -z "$CHAR_BASE" ]; then
  CHAR_BASE="Scout$(( ($$ % 8999) + 1000 ))"
fi
CHAR_BASE="$(printf '%s' "$(clean "$CHAR_BASE")" | cut -c1-30)"
CHAR_NAME="$CHAR_BASE"
try=0
while :; do
  r=$(post /v1/characters "{\"name\":\"$CHAR_NAME\",\"vocation\":\"$VOC\"}" "$TOKEN") \
    || die "cannot reach $BASE"
  c=$(printf '%s' "$r" | code_of); b=$(printf '%s' "$r" | body_of)
  case "$c" in
    200|201) break ;;
    *)
      case "$b" in
        *already*taken*)
          try=$((try + 1)); [ $try -ge 6 ] && die "could not find a free character name"
          CHAR_NAME="$(printf '%s%s%d' "$CHAR_BASE" "$(( ($$ % 89) + 10 ))" "$try")"
          ;;
        *) die "character ($c): $(printf '%s' "$b" | head -c 300)" ;;
      esac
      ;;
  esac
done
CID=$(json_str id "$b")
[ -n "$CID" ] || die "character created but no id in response: $(printf '%s' "$b" | head -c 300)"

# --- 3. enter the world -----------------------------------------------------
r=$(post /v1/enter "{\"characterId\":\"$CID\"}" "$TOKEN") || die "cannot reach $BASE"
c=$(printf '%s' "$r" | code_of); OBS=$(printf '%s' "$r" | body_of)
case "$c" in 200) ;; *) die "enter ($c): $(printf '%s' "$OBS" | head -c 300)" ;; esac

# --- 4. save resume state ---------------------------------------------------
umask 177
{
  printf 'GOLEMREACH_BASE=%s\nACCOUNT=%s\nTOKEN=%s\nCHARACTER_ID=%s\nCHARACTER_NAME=%s\n' \
    "$BASE" "$ACC_FULL" "$TOKEN" "$CID" "$CHAR_NAME"
} > "$ENVF"
chmod 600 "$ENVF"

say ""
say "== Welcome to Golemreach — $CHAR_NAME, level 1 $VOC =="
say "Account '$ACC_FULL' registered FREE. Credentials saved to $(pwd)/$ENVF"
say "(mode 600). Re-run this same command any time to resume."
say "NOTE: without a password (GOLEMREACH_PASSWORD), that file is the ONLY"
say "key to this account — if you delete it, the account is gone."

# --- 5. the crypt opener (best effort, bounded) -----------------------------
# Every new character wakes in its own copy of the tutorial crypt: a guard
# blocks the doorway, the doorway floor burns, a rat waits in the corridor.
# Geometry is identical for everybody; only live ids differ.
if [ "$DEMO" = "0" ]; then
  say "Demo skipped (GOLEMREACH_DEMO=0). Your first view:"
  say ""
  say "$OBS"
  show_next_moves
  exit 0
fi

say ""
say "== Playing the tutorial opener: guard, doorway, rat =="
POS=$(first_pos "$OBS")
SX=$(printf '%s' "$POS" | sed -n 's/.*"x":\([0-9]*\).*/\1/p')
SY=$(printf '%s' "$POS" | sed -n 's/.*"y":\([0-9]*\).*/\1/p')
SZ=$(printf '%s' "$POS" | sed -n 's/.*"z":\([-0-9]*\).*/\1/p')
[ -n "${SX:-}" ] && [ -n "${SY:-}" ] && [ -n "${SZ:-}" ] \
  || { say "(could not read spawn position — handing over early)"; say "$OBS"; show_next_moves; exit 0; }
NX=$((SX + 3)); NY=$SY                          # guard stands three tiles east
DOORX=$((NX + 1))                               # doorway floor burns briefly
NPCID=$(printf '%s' "$OBS" | grep -o '"id":"n[0-9]*","name":"[^"]*","kind":"npc"' | head -n1 | sed -n 's/.*"id":"\(n[0-9]*\)".*/\1/p')

# 5a. walk to one tile from the guard
i=0
while [ $i -lt 2 ]; do
  i=$((i + 1)); sleep 2
  step_dir e || { say "(walk interrupted — handing over)"; break; }
done

# 5b. push the guard aside (north first, fall back south)
if [ -n "$NPCID" ]; then
  sleep 2
  r=$(post /v1/act "{\"action\":{\"type\":\"push\",\"targetId\":\"$NPCID\",\"to\":{\"x\":$NX,\"y\":$((NY - 1)),\"z\":$SZ}}}" "$TOKEN")
  case "$(printf '%s' "$r" | body_of)" in
    *'"ok":true'*) say "Pushed the guard aside." ;;
    *)
      sleep 2
      r=$(post /v1/act "{\"action\":{\"type\":\"push\",\"targetId\":\"$NPCID\",\"to\":{\"x\":$NX,\"y\":$((NY + 1)),\"z\":$SZ}}}" "$TOKEN")
      case "$(printf '%s' "$r" | body_of)" in
        *'"ok":true'*) say "Pushed the guard aside." ;;
        *) say "(could not push the guard — follow your own hints for the right tile)" ;;
      esac
      ;;
  esac
else
  say "(no guard visible — continuing)"
fi

# 5c. cross the doorway and keep going, OFF the burning floor
i=0
while [ $i -lt 3 ]; do
  i=$((i + 1)); sleep 2
  step_dir e || break
done
say "Through the doorway (it burned a little — that is the lesson)."

# 5d. find the rat and fight it, retreating if it goes badly
sleep 2
OBS=$(get "/v1/observe?detail=normal" "$TOKEN" | body_of)
MID=$(printf '%s' "$OBS" | grep -o '"id":"m[0-9]*"' | head -n1 | tr -d '"' | sed 's/^id://')
KILLED=""
if [ -n "$MID" ]; then
  say "A rat! Attacking $MID (the server swings for you now)."
  sleep 1
  post /v1/act "{\"action\":{\"type\":\"attack\",\"targetId\":\"$MID\"},\"observe\":true}" "$TOKEN" >/dev/null
  poll=0
  while [ $poll -lt 10 ]; do
    poll=$((poll + 1)); sleep 4
    OBS=$(get "/v1/observe?detail=normal" "$TOKEN" | body_of)
    HP=$(json_num health "$OBS")
    case "$OBS" in
      *defeated*)
        KILLED=1
        CORPSE=$(printf '%s' "$OBS" | sed -n 's/.*Loot is in the corpse at \([0-9]*\),\([0-9]*\).*/\1 \2/p' | head -n1)
        say "Rat defeated! $(printf '%s' "$OBS" | grep -o 'You gained [0-9]* experience[^."]*' | head -n1)"
        break
        ;;
    esac
    if [ -n "$HP" ] && [ "$HP" -lt 40 ]; then break; fi
  done
  if [ -z "$KILLED" ]; then
    say "Fight not finished in time (health ${HP:-?}). Falling back — finish it yourself:"
    step_dir w; sleep 2; step_dir w
  fi
else
  say "No rat in sight yet — it spawns just inside the corridor; take two steps east."
fi

# 5e. loot the corpse
if [ -n "$KILLED" ] && [ -n "${CORPSE:-}" ]; then
  CX=$(printf '%s' "$CORPSE" | cut -d' ' -f1); CY=$(printf '%s' "$CORPSE" | cut -d' ' -f2)
  sleep 2
  r=$(post /v1/act "{\"action\":{\"type\":\"loot\",\"position\":{\"x\":$CX,\"y\":$CY,\"z\":$SZ}},\"observe\":true}" "$TOKEN")
  say "Looted: $(printf '%s' "$r" | grep -o '"taken":\[[^]]*\]' | head -n1)"
fi

# --- 6. hand over -----------------------------------------------------------
sleep 1
FINAL=$(get "/v1/observe?detail=normal" "$TOKEN" | body_of)
HP=$(json_num health "$FINAL")
XP=$(json_num experience "$FINAL")
say ""
say "== Opener done. $CHAR_NAME: ${HP:-?}/150 health, ${XP:-0} experience =="
HINTS=$(printf '%s' "$FINAL" | grep -o '"hints":\[[^]]*\]' | head -n1)
[ -n "$HINTS" ] && { say "Your crypt's next steps (from the server's hints):"; printf '%s\n' "$HINTS" | cut -c1-1400; }
say "The crypt continues down until you wake at the temple in Efidia. There,"
say 'tell Brother Pitt "kit" for your real gear, then EAT — nothing'
say "regenerates while hungry."
LIVEIDS=$(printf '%s' "$FINAL" | grep -o '"id":"n[0-9]*","name":"[^"]*","kind":"npc"' | head -n1 | sed -n 's/.*"id":"\(n[0-9]*\)","name":"\([^"]*\)".*/\1 (\2)/p')
LIVEM=$(printf '%s' "$FINAL" | grep -o '"id":"m[0-9]*"' | head -n1 | sed -n 's/.*"\(m[0-9]*\)".*/\1/p')
if [ -n "$LIVEIDS" ] || [ -n "$LIVEM" ]; then
  say "Right now you can see: NPC ${LIVEIDS:-none}; monster ${LIVEM:-none}."
fi
show_next_moves
