#!/usr/bin/env bash
# Agent-facing probe for Space Browser.
#
# The browser never paints its own cursor, and the world->screen transform only
# exists inside the page. So every coordinate below is converted by the page
# itself (window.__game, see client/src/main.ts) and nothing here does the maths.
# A point this script prints is the point the game will act on.
#
#   ./tools/agent.sh open                 open the game (only if it is not already up)
#   ./tools/agent.sh reload               reload the page: a brand new player
#   ./tools/agent.sh state                you, held, camera, canvas, ships, bodies, ore
#   ./tools/agent.sh targets [kind]       every clickable thing, nearest first
#   ./tools/agent.sh move  --target ore:41 | --cell 60,30 | --world 120,-40 | --px 636,288
#   ./tools/agent.sh click --target ore:41
#   ./tools/agent.sh drag  --target ore:41 --to-cell 60,30
#   ./tools/agent.sh world                the same state straight from the server, no browser
#   ./tools/agent.sh shot  out.png        screenshot, plus the canvas box it was taken with
#   ./tools/agent.sh peer                 a second tab: a second player, for PvP
#   ./tools/agent.sh tab <n>              switch tab
set -euo pipefail

URL=${URL:-http://localhost:5173}
API=${API:-http://localhost:8090}
cd "$(dirname "$0")/.."

ab() { agent-browser "$@"; }
# eval prints the value as JSON: unwrap it so bash sees plain text.
js() {
  local out
  out=$(ab eval "$1")
  printf '%s\n' "$out" | jq -r . 2>/dev/null || printf '%s\n' "$out"
}

ready() { [ "$(ab eval 'typeof window.__game === "object" && window.__game.state ? 1 : 0' 2>/dev/null)" = "1" ]; }

ensure() {
  ready || ab open "$URL" >/dev/null 2>&1 || true
  for _ in $(seq 40); do
    ready && return 0
    sleep 0.25
  done
  echo "agent.sh: window.__game never appeared: is ./dev-start.sh running at $URL?" >&2
  exit 1
}

# Resolve one point to "px py", in page coordinates.
coords() {
  local t="" c="" w="" p=""
  while [ $# -gt 0 ]; do
    case "$1" in
      --target) t=$2; shift 2 ;;
      --cell) c=$2; shift 2 ;;
      --world) w=$2; shift 2 ;;
      --px) p=$2; shift 2 ;;
      *) echo "agent.sh: unknown flag $1" >&2; exit 2 ;;
    esac
  done
  [ -n "$t$c$w$p" ] || { echo "agent.sh: give --target, --cell, --world or --px" >&2; exit 2; }
  local out
  out=$(js "(() => {
    const g = window.__game, s = { t: '$t', c: '$c', w: '$w', p: '$p' };
    let px, py;
    if (s.t) {
      const [kind, id] = s.t.split(':');
      const h = g.targets().find((x) => x.kind === kind && x.id === Number(id));
      if (!h) return 'ERR nothing named ' + s.t + ' on screen; run: agent.sh targets';
      px = h.cellPx; py = h.cellPy; // the centre of its cell, not its exact pixel
    } else if (s.c) {
      const [x, y] = s.c.split(',').map(Number), r = g.canvas();
      px = r.left + (x + 0.5) * r.cell; py = r.top + (y + 0.5) * r.cell;
    } else if (s.w) {
      const [x, y] = s.w.split(',').map(Number), q = g.toScreen(x, y);
      px = q.px; py = q.py;
    } else {
      [px, py] = s.p.split(',').map(Number);
    }
    return Math.round(px) + ' ' + Math.round(py);
  })()")
  case "$out" in ERR*) echo "agent.sh: ${out#ERR }" >&2; exit 1 ;; esac
  echo "$out"
}

# point <spec...>: sets PX and PY, or dies with the reason.
point() {
  local p
  p=$(coords "$@")
  PX=${p% *}
  PY=${p#* }
}

cmd=${1:-help}
shift || true
case "$cmd" in
  open)
    ensure
    echo "open $(js 'location.href')"
    js "JSON.stringify(window.__game.canvas())"
    ;;
  reload)
    ab open "$URL" >/dev/null
    ensure
    echo "reloaded $URL"
    ;;
  state)
    ensure
    js "JSON.stringify({ you: __game.state.you, held: __game.state.held, cam: __game.cam, canvas: __game.canvas(), ships: __game.state.players, bodies: __game.state.bodies, ore: __game.state.ore, loose: __game.state.loose })"
    ;;
  targets)
    ensure
    js "JSON.stringify(__game.targets().filter((t) => !'${1:-}' || t.kind === '${1:-}').map((t) => ({ kind: t.kind, id: t.id, owner: t.owner, cell: t.cellX + ',' + t.cellY, px: Math.round(t.cellPx) + ',' + Math.round(t.cellPy), world: Math.round(t.x) + ',' + Math.round(t.y), d: Math.round(t.d) })))"
    ;;
  move)
    ensure
    point "$@"
    ab mouse move "$PX" "$PY" >/dev/null
    echo "moved to $PX $PY"
    ;;
  click)
    ensure
    point "$@"
    ab mouse move "$PX" "$PY" >/dev/null
    ab mouse down >/dev/null
    ab mouse up >/dev/null
    echo "clicked $PX $PY"
    ;;
  drag)
    ensure
    from=()
    to=()
    while [ $# -gt 0 ]; do
      case "$1" in
        --to-cell) to+=(--cell "$2"); shift 2 ;;
        --to-world) to+=(--world "$2"); shift 2 ;;
        --to-target) to+=(--target "$2"); shift 2 ;;
        --to-px) to+=(--px "$2"); shift 2 ;;
        *) from+=("$1"); shift ;;
      esac
    done
    [ ${#to[@]} -gt 0 ] || { echo "agent.sh: drag needs --to-cell, --to-world, --to-target or --to-px" >&2; exit 2; }
    point "${from[@]}"
    fx=$PX fy=$PY
    point "${to[@]}"
    tx=$PX ty=$PY
    ab mouse move "$fx" "$fy" >/dev/null
    ab mouse down >/dev/null
    for i in 1 2 3; do ab mouse move $((fx + (tx - fx) * i / 3)) $((fy + (ty - fy) * i / 3)) >/dev/null; done
    ab mouse up >/dev/null
    echo "dragged $fx $fy -> $tx $ty"
    ;;
  world)
    curl -sf "$API/debug/state" | jq -c .
    ;;
  shot)
    ensure
    # agent-browser resolves a relative path against its own cwd, so a shot lands
    # where the caller asked only when it is absolute.
    f=${1:-shot.png}
    case "$f" in /*) ;; *) f=$PWD/$f ;; esac
    ab screenshot "$f" >/dev/null
    echo "$f"
    js "JSON.stringify({ cam: __game.cam, canvas: __game.canvas() })"
    ;;
  peer)
    ab tab new "$URL" >/dev/null
    ensure
    echo "second player in a new tab"
    ab tab list
    ;;
  tab)
    id=$1
    case "$id" in ''|*[!0-9]*) ;; *) id=t$id ;; esac # 2 and t2 are the same tab
    ab tab "$id" >/dev/null
    ensure
    echo "tab $id"
    ;;
  *)
    sed -n '2,20p' "$0" | sed 's/^# \{0,1\}//'
    ;;
esac
