#!/usr/bin/env bash
# Daemon smoke test — verifies the running daemon's health + each agent's
# binary + auth state. Run AFTER upgrading the daemon to 0.2.14+.
#
# Usage: bash scripts/smoke-test.sh

set -uo pipefail
LOCKFILE="${HOME}/.entities-runtime/runtime.json"

if [ ! -f "$LOCKFILE" ]; then
  echo "✗ No daemon lockfile at $LOCKFILE — daemon not running"
  exit 1
fi

PORT=$(python3 -c "import json; print(json.load(open('${LOCKFILE}'))['port'])")
echo "Daemon lockfile port: $PORT"

probe() {
  local ep="$1"
  local expect_field="$2"
  local body
  body=$(curl -s --max-time 3 "http://127.0.0.1:${PORT}${ep}")
  if [ -z "$body" ]; then
    echo "  ✗ $ep — no response"
    return 1
  fi
  if [ -n "$expect_field" ]; then
    if echo "$body" | python3 -c "import json,sys; d=json.load(sys.stdin); assert '$expect_field' in d or any('$expect_field' in str(v) for v in d.values())" 2>/dev/null; then
      echo "  ✓ $ep — $(echo "$body" | python3 -c "import json,sys; print(json.dumps(json.load(sys.stdin), separators=(',',':'))[:120])")"
    else
      echo "  ⚠ $ep — missing field '$expect_field': $body" | head -c 200
      echo
    fi
  else
    echo "  ✓ $ep — $(echo "$body" | head -c 100)"
  fi
}

echo
echo "=== Daemon control-server endpoints ==="
probe /status "version"
probe /self "runtime"
probe /stats "inflight"   # inflight field added in 0.2.11
probe /requests "requests"
probe /projects "projects"

echo
echo "=== Agent binary + auth checks ==="
check_agent() {
  local name="$1" bin="$2" auth_file="$3" env_var="$4"
  printf "  %s: " "$name"
  if ! command -v "$bin" >/dev/null 2>&1; then
    echo "✗ binary missing"
    return
  fi
  local ver
  ver=$("$bin" --version 2>&1 | head -1 | tr -d '\n')
  if [ -n "$env_var" ] && [ -n "${!env_var:-}" ]; then
    echo "✓ $ver — authed via \$$env_var"
    return
  fi
  if [ -f "$HOME/$auth_file" ] && [ "$(stat -f %z "$HOME/$auth_file" 2>/dev/null || stat -c %s "$HOME/$auth_file" 2>/dev/null)" -gt 16 ]; then
    echo "✓ $ver — authed via ~/$auth_file"
  else
    echo "⚠ $ver — NO AUTH (set $env_var or login)"
  fi
}
check_agent "claude" claude .claude/.credentials.json ANTHROPIC_API_KEY
check_agent "codex"  codex  .codex/auth.json OPENAI_API_KEY
check_agent "kimi"   kimi   .kimi/auth.toml KIMI_API_KEY
check_agent "gemini" gemini .gemini/oauth_creds.json GEMINI_API_KEY

echo
echo "=== Done ==="
