#!/bin/sh
set -eu

base_url=${WORKCELL_BASE_URL:-https://workcell-137.pages.dev/downloads}
release_id=1b0ca9254c500a7cf2efdcf65b3aed91a6aed82c89c1f2c8de56b95d6586b462

if ! command -v curl >/dev/null 2>&1; then
  echo "workcell demo: curl is required" >&2
  exit 1
fi

os=$(uname -s | tr '[:upper:]' '[:lower:]')
case "$os" in
  darwin|linux) ;;
  *)
    echo "workcell demo: unsupported operating system: $os" >&2
    exit 1
    ;;
esac

machine=$(uname -m)
case "$machine" in
  arm64|aarch64) arch=arm64 ;;
  x86_64|amd64) arch=amd64 ;;
  *)
    echo "workcell demo: unsupported architecture: $machine" >&2
    exit 1
    ;;
esac

asset="workcell-$os-$arch"
temporary_dir=$(mktemp -d)
trap 'rm -rf "$temporary_dir"' EXIT HUP INT TERM

echo "Downloading a temporary Workcell binary..." >&2
curl -fsSL "$base_url/$asset?release=$release_id" -o "$temporary_dir/workcell"
curl -fsSL "$base_url/SHA256SUMS?release=$release_id" -o "$temporary_dir/SHA256SUMS"

expected=$(awk -v asset="$asset" '$2 == asset { print $1 }' "$temporary_dir/SHA256SUMS")
if [ -z "$expected" ]; then
  echo "workcell demo: checksum missing for $asset" >&2
  exit 1
fi

if command -v shasum >/dev/null 2>&1; then
  actual=$(shasum -a 256 "$temporary_dir/workcell" | awk '{ print $1 }')
elif command -v sha256sum >/dev/null 2>&1; then
  actual=$(sha256sum "$temporary_dir/workcell" | awk '{ print $1 }')
else
  echo "workcell demo: shasum or sha256sum is required" >&2
  exit 1
fi

if [ "$actual" != "$expected" ]; then
  echo "workcell demo: checksum verification failed" >&2
  exit 1
fi

chmod 0755 "$temporary_dir/workcell"
workcell_bin="$temporary_dir/workcell"
state_dir="$temporary_dir/demo"
timeline="$state_dir/timeline"
overlaps="$state_dir/overlaps"
active_gpu="$state_dir/active-demo-gpu"
mkdir -p "$state_dir"

export WORKCELL_STATE_DIR="$state_dir/state"
export WORKCELL_DEMO_TIMELINE="$timeline"
export WORKCELL_DEMO_OVERLAPS="$overlaps"
export WORKCELL_DEMO_ACTIVE_GPU="$active_gpu"

run_job='agent=$1
resource=$2
duration=$3
guard_gpu=$4
if [ "$guard_gpu" = 1 ] && ! mkdir "$WORKCELL_DEMO_ACTIVE_GPU" 2>/dev/null; then
  echo "$agent overlapped $resource" >> "$WORKCELL_DEMO_OVERLAPS"
  exit 1
fi
echo "$agent entered $resource" >> "$WORKCELL_DEMO_TIMELINE"
sleep "$duration"
echo "$agent finished $resource" >> "$WORKCELL_DEMO_TIMELINE"
if [ "$guard_gpu" = 1 ]; then rmdir "$WORKCELL_DEMO_ACTIVE_GPU"; fi'

wait_for_owner() {
  resource=$1
  attempt=1
  while [ "$attempt" -le 100 ]; do
    if "$workcell_bin" status "$resource" --json 2>/dev/null | grep -q '"decision":"owned"'; then
      return
    fi
    sleep 0.02
    attempt=$((attempt + 1))
  done
  echo "workcell demo: owner did not acquire $resource" >&2
  exit 1
}

wait_for_queue_depth() {
  expected_depth=$1
  agent=$2
  attempt=1
  while [ "$attempt" -le 100 ]; do
    probe=$("$workcell_bin" run demo-gpu --session queue-probe --json -- true 2>/dev/null || true)
    if printf '%s' "$probe" | grep -q "\"queue_ahead\":$expected_depth"; then
      return
    fi
    sleep 0.02
    attempt=$((attempt + 1))
  done
  echo "workcell demo: $agent did not enter the queue" >&2
  exit 1
}

wait_for_timeline_line() {
  expected_line=$1
  attempt=1
  while [ "$attempt" -le 100 ]; do
    if grep -q "^$expected_line$" "$timeline" 2>/dev/null; then
      return
    fi
    sleep 0.02
    attempt=$((attempt + 1))
  done
  echo "workcell demo: missing timeline event: $expected_line" >&2
  exit 1
}

render_pane() {
  agent=$1
  resource=$2
  command=$3
  state=$4
  printf '+-- %-8s / %-12s ---------------------------------------+\n' "$agent" "$resource"
  printf '| %-68s |\n' "$command"
  printf '| STATUS  %-60s |\n' "$state"
  printf '+------------------------------------------------------------------------+\n'
}

render_dashboard() {
  state_a=$1
  state_b=$2
  state_c=$3
  state_d=$4
  event=$5
  if [ -t 1 ]; then printf '\033[2J\033[H'; fi
  printf 'WORKCELL LIVE QUEUE\n'
  printf 'Each pane is an agent invoking the actual CLI.\n\n'
  printf '%s\n\n' "$event"
  render_pane 'Agent A' 'demo-gpu' 'workcell run demo-gpu --session agent-a -- <job>' "$state_a"
  render_pane 'Agent B' 'demo-gpu' 'workcell run demo-gpu --wait --session agent-b -- <job>' "$state_b"
  render_pane 'Agent C' 'demo-gpu' 'workcell run demo-gpu --wait --session agent-c -- <job>' "$state_c"
  render_pane 'Agent D' 'demo-rig' 'workcell run demo-rig --session agent-d -- <job>' "$state_d"
}

"$workcell_bin" run demo-gpu --session agent-a -- sh -c "$run_job" sh A demo-gpu 4 1 >/dev/null &
agent_a_pid=$!
wait_for_owner demo-gpu

"$workcell_bin" run demo-gpu --wait --session agent-b -- sh -c "$run_job" sh B demo-gpu 1 1 >/dev/null &
agent_b_pid=$!
wait_for_queue_depth 1 "Agent B"

"$workcell_bin" run demo-gpu --wait --session agent-c -- sh -c "$run_job" sh C demo-gpu 1 1 >/dev/null &
agent_c_pid=$!
wait_for_queue_depth 2 "Agent C"

"$workcell_bin" run demo-rig --session agent-d -- sh -c "$run_job" sh D demo-rig 0.8 0 >/dev/null &
agent_d_pid=$!
wait_for_timeline_line "D entered demo-rig"

render_dashboard 'RUNNING' 'WAITING #1' 'WAITING #2' 'RUNNING' 'Agent A owns demo-gpu. Agent D starts immediately on demo-rig.'

wait "$agent_d_pid"
render_dashboard 'RUNNING' 'WAITING #1' 'WAITING #2' 'DONE - finished while demo-gpu stayed busy' 'Agent D is DONE. demo-gpu is still busy.'

wait "$agent_a_pid"
wait_for_timeline_line "B entered demo-gpu"
render_dashboard 'DONE' 'RUNNING' 'WAITING #1' 'DONE' 'NEXT. Agent B is now RUNNING.'

wait "$agent_b_pid"
wait_for_timeline_line "C entered demo-gpu"
render_dashboard 'DONE' 'DONE' 'RUNNING' 'DONE' 'NEXT. Agent C is now RUNNING.'

wait "$agent_c_pid"
render_dashboard 'DONE' 'DONE' 'DONE' 'DONE' 'All four jobs are DONE.'

line_number() {
  grep -n "^$1$" "$timeline" | cut -d: -f1
}

a_finished=$(line_number "A finished demo-gpu")
b_entered=$(line_number "B entered demo-gpu")
b_finished=$(line_number "B finished demo-gpu")
c_entered=$(line_number "C entered demo-gpu")
c_finished=$(line_number "C finished demo-gpu")
d_entered=$(line_number "D entered demo-rig")
d_finished=$(line_number "D finished demo-rig")

if [ -z "$a_finished" ] || [ -z "$b_entered" ] || [ -z "$b_finished" ] || [ -z "$c_entered" ] || [ -z "$c_finished" ] || [ -z "$d_entered" ] || [ -z "$d_finished" ]; then
  echo "workcell demo: timeline is incomplete" >&2
  exit 1
fi

if [ "$b_entered" -le "$a_finished" ] || [ "$c_entered" -le "$b_finished" ]; then
  echo "workcell demo: FIFO handoff failed" >&2
  exit 1
fi

if [ "$d_entered" -ge "$a_finished" ] || [ "$d_finished" -ge "$a_finished" ]; then
  echo "workcell demo: independent resource did not run concurrently" >&2
  exit 1
fi

if [ -s "$overlaps" ]; then
  echo "workcell demo: overlapping demo-gpu jobs detected" >&2
  exit 1
fi

printf '\nPROOF\n'
echo "3 CONTENDERS"
echo "1 ACTIVE demo-gpu JOB"
echo "1 INDEPENDENT demo-rig JOB"
echo "FIFO HANDOFF"
echo "0 OVERLAPS"
echo "demo-rig FINISHED WHILE demo-gpu WAS BUSY"
