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

repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
latest_path="${SUPERTEST_LATEST:-$repo_root/.state/supertest/latest.json}"

usage() {
  cat <<'EOF'
Usage:
  scripts/supertest-legion node list --json
  scripts/supertest-legion node ssh <node> [-- <command>...]
  scripts/supertest-legion node rpc <node> -- <elixir-expression>
  scripts/supertest-legion ssh <node> [-- <command>...]
  scripts/supertest-legion rpc <node> <elixir-expression>

The helper reads .state/supertest/latest.json by default and reuses the
generated Legion state/cache from the most recent supertest run.
EOF
}

if [[ "${1:-}" == "-h" || "${1:-}" == "--help" ]]; then
  usage
  exit 0
fi

if [[ ! -f "$latest_path" ]]; then
  echo "No supertest run metadata found at $latest_path." >&2
  echo "Run a scenario first, or set SUPERTEST_LATEST=/path/to/latest.json." >&2
  exit 1
fi

if [[ -z "${LEGION_UNLOCK_PASSWORD:-}" ]]; then
  echo "LEGION_UNLOCK_PASSWORD is required for Legion ssh/rpc helpers." >&2
  exit 1
fi

eval "$(
  node -e '
    const fs = require("node:fs")
    const latest = JSON.parse(fs.readFileSync(process.argv[1], "utf8"))
    const required = [
      ["legionRepo", latest.legionRepo],
      ["legionStateDir", latest.legionStateDir],
      ["legionCacheDir", latest.legionCacheDir]
    ]
    for (const [key, value] of required) {
      if (!value) {
        throw new Error(`latest metadata is missing ${key}`)
      }
    }
    const sh = (value) => `"${String(value).replace(/(["\\$`])/g, "\\$1")}"`
    const emit = (key, value) => {
      if (value !== undefined && value !== null && value !== "") {
        console.log(`${key}=${sh(value)}`)
      }
    }
    emit("SUPERTEST_LEGION_REPO", latest.legionRepo)
    emit("SUPERTEST_LEGION_CLI_ENTRY", latest.legionCliEntry || "src/engine/cli-main.ts")
    emit("SUPERTEST_COMMAND_DIR", latest.commandDir)
    emit("LEGION_STATE_DIR", latest.legionStateDir)
    emit("LEGION_CACHE_DIR", latest.legionCacheDir)
    emit("LEGION_APP_ROOT", latest.legionRepo)
    emit("LEGION_TEST_CERT_MODE", latest.certMode || "self-signed")
  ' "$latest_path"
)"
export LEGION_STATE_DIR LEGION_CACHE_DIR LEGION_APP_ROOT LEGION_TEST_CERT_MODE

if [[ -z "${LEGION_DAEMON_TOKEN:-}" && -n "${SUPERTEST_COMMAND_DIR:-}" ]]; then
  daemon_start_stdout="$SUPERTEST_COMMAND_DIR/daemon-start.stdout.txt"
  if [[ -f "$daemon_start_stdout" ]]; then
    token="$(sed -n "s/^export LEGION_DAEMON_TOKEN='\([^']*\)'/\1/p" "$daemon_start_stdout" | tail -n 1)"
    if [[ -n "$token" ]]; then
      export LEGION_DAEMON_TOKEN="$token"
    fi
  fi
fi

if [[ $# -eq 0 ]]; then
  usage
  exit 1
fi

case "$1" in
  ssh)
    shift
    if [[ $# -lt 1 ]]; then
      echo "ssh requires a node reference." >&2
      exit 1
    fi
    set -- node ssh "$@"
    ;;
  rpc)
    shift
    if [[ $# -lt 2 ]]; then
      echo "rpc requires a node reference and an Elixir expression." >&2
      exit 1
    fi
    node="$1"
    shift
    [[ "${1:-}" == "--" ]] && shift
    if [[ $# -eq 0 ]]; then
      echo "rpc requires an Elixir expression." >&2
      exit 1
    fi
    expression="$*"
    set -- node rpc "$node" -- "$expression"
    ;;
esac

tsx_import="$(node -e 'console.log(require.resolve("tsx"))')"

cd "$SUPERTEST_LEGION_REPO"
exec node --import "$tsx_import" "$SUPERTEST_LEGION_CLI_ENTRY" "$@"
