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

PORT="${MCP_PORT:-${PORT:-8550}}"
URL="${ATLAS_HEALTH_URL:-http://127.0.0.1:${PORT}/health}"
ENTITY_SUBJECT="${ATLAS_TEST_SUBJECT:-Joe Biden}"
DEBUG_PATH="${ATLAS_TEST_DEBUG_PATH:-/tmp/atlas-debug/${ENTITY_SUBJECT// /_}.ttl}"

log() {
  printf '\n[%s] %s\n' "$(date +'%H:%M:%S')" "$1"
}

if ! command -v curl >/dev/null 2>&1; then
  echo "curl is required for tests.sh"
  exit 1
fi

if ! command -v jq >/dev/null 2>&1; then
  echo "jq is required for tests.sh"
  exit 1
fi

if ! command -v mcporter >/dev/null 2>&1; then
  echo "mcporter is required for tests.sh"
  exit 1
fi

log "1) Checking Atlas health endpoint"
health_response="$(curl -fsS "$URL")"
echo "$health_response" | jq

if ! printf '%s' "$health_response" | grep -q '"status":"ok"'; then
  echo "Expected health status ok"
  exit 1
fi

if ! printf '%s' "$health_response" | grep -q '"tools"'; then
  echo "Expected tools in health response"
  exit 1
fi

if [[ -n "${CONFIG:-}" ]]; then
  log "2) Resolving a known entity via mcporter"
  resolve_out="$({ mcporter --config "$CONFIG" call atlas.resolve_entity subject="$ENTITY_SUBJECT" debug=true debug_path="$DEBUG_PATH"; } 2>&1)"
  printf '%s\n' "$resolve_out"

  if ! printf '%s' "$resolve_out" | grep -q '"canonical_label"'; then
    echo "Expected canonical_label in resolve output"
    exit 1
  fi

  if ! printf '%s' "$resolve_out" | grep -q '"wikidata_payload"'; then
    echo "Expected wikidata_payload in resolve output"
    exit 1
  fi

  if ! printf '%s' "$resolve_out" | grep -q '"raw_claims"'; then
    echo "Expected raw_claims in debug output"
    exit 1
  fi

  if ! printf '%s' "$resolve_out" | grep -q '"derived_claims"'; then
    echo "Expected derived_claims in debug output"
    exit 1
  fi

  if [[ -f "$DEBUG_PATH" ]]; then
    log "3) Debug Turtle dumped to $DEBUG_PATH"
    head -n 40 "$DEBUG_PATH"
  else
    echo "Expected debug Turtle at $DEBUG_PATH"
    exit 1
  fi
else
  log "2) CONFIG not set, skipping mcporter resolve smoke test"
fi

log "All Atlas checks passed."
