#!/usr/bin/env bash
# ca.sh wrapper.identity contract: write identity file on successful status probe;
# write nothing and still complete when the probe fails/times out/returns junk or
# when HARNESS_IDENTITY_FILE is unset.
set -euo pipefail

root="$(cd "$(dirname "$0")" && pwd)"
tmp="$(mktemp -d)"
trap 'rm -rf "$tmp"' EXIT
mkdir -p "$tmp/bin" "$tmp/home" "$tmp/ws" "$tmp/logs"

fail() { printf 'FAIL %s\n' "$1" >&2; exit 1; }

write_stub() {
  local mode="$1"
  cat >"$tmp/bin/cursor-agent" <<STUB
#!/usr/bin/env bash
set -eu
if [[ "\${1:-}" == "create-chat" ]]; then printf '%s\n' 'chat-identity'; exit 0; fi
if [[ "\${1:-}" == "status" ]]; then
  case "$mode" in
    ok)
      printf '%s\n' '{"status":"authenticated","isAuthenticated":true,"userInfo":{"email":"seat-runner@example.com","userId":"u1"}}'
      exit 0
      ;;
    junk)
      printf '%s\n' 'not-json-at-all'
      exit 0
      ;;
    missing)
      printf '%s\n' '{"status":"authenticated","isAuthenticated":true,"userInfo":{"userId":"u1"}}'
      exit 0
      ;;
    fail)
      printf '%s\n' '{"status":"error","message":"boom"}'
      exit 1
      ;;
    hang)
      sleep 60
      exit 0
      ;;
  esac
fi
printf '%s\n' '{"type":"result","detail":"done"}'
exit 0
STUB
  chmod +x "$tmp/bin/cursor-agent"
}

run_ca() {
  local stderr_file="$1"
  local identity_file="${2:-}"
  rm -rf "${tmp:?}/home/Projects" "$tmp/logs" "$tmp/identity.json" "$tmp/identity.json.tmp"
  mkdir -p "$tmp/logs"
  local -a env_args=(
    HOME="$tmp/home"
    PATH="$tmp/bin:/usr/local/bin:/usr/bin:/bin"
    HARNESS_SEAT_CONTAINER=1
    HARNESS_LOG_DIR="$tmp/logs"
  )
  if [[ -n "$identity_file" ]]; then
    env_args+=(HARNESS_IDENTITY_FILE="$identity_file")
  fi
  set +e
  env -i "${env_args[@]}" \
    bash "$root/ca.sh" \
      --workspace "$tmp/ws" \
      --trust 'identity fixture' \
      --task-slug caident \
      --model composer-2.5 \
      --timeout 30 \
      --profile ignored-profile \
      >"$tmp/stdout" 2>"$stderr_file"
  local rc=$?
  set -e
  return "$rc"
}

write_stub ok
rc=0; run_ca "$tmp/stderr-ok" "$tmp/identity.json" || rc=$?
[[ $rc -eq 0 ]] || fail "ok status: expected exit 0, got $rc"
[[ -f "$tmp/identity.json" ]] || fail "ok status: missing identity file"
grep -qx '{"kind":"wrapper.identity","account":"seat-runner@example.com"}' "$tmp/identity.json" \
  || fail "ok status: identity file contents wrong"
if grep -q '"kind":"wrapper.identity"' "$tmp/stderr-ok" "$tmp/stdout"; then
  fail "ok status: must not emit wrapper.identity on streams"
fi
grep -q 'notice: --profile=ignored-profile ignored' "$tmp/stderr-ok" \
  || fail "ok status: --profile ignore notice missing"
if grep -Eiq 'hasAccessToken|hasRefreshToken|refresh.?token|access.?token' "$tmp/stderr-ok" "$tmp/stdout" "$tmp/logs"/* "$tmp/identity.json" 2>/dev/null; then
  fail "ok status: credential material leaked"
fi

for mode in junk missing fail hang; do
  write_stub "$mode"
  rm -f "$tmp/identity.json"
  rc=0; run_ca "$tmp/stderr-$mode" "$tmp/identity.json" || rc=$?
  [[ $rc -eq 0 ]] || fail "$mode: expected exit 0, got $rc"
  if [[ -e "$tmp/identity.json" ]]; then
    fail "$mode: must not write identity file"
  fi
  if grep -q '"kind":"wrapper.identity"' "$tmp/stderr-$mode" "$tmp/stdout"; then
    fail "$mode: must not emit wrapper.identity on streams"
  fi
done

write_stub ok
rm -f "$tmp/identity.json"
rc=0; run_ca "$tmp/stderr-unset" || rc=$?
[[ $rc -eq 0 ]] || fail "unset sink: expected exit 0, got $rc"
if [[ -e "$tmp/identity.json" ]]; then
  fail "unset sink: must not write identity file"
fi
if grep -q '"kind":"wrapper.identity"' "$tmp/stderr-unset" "$tmp/stdout"; then
  fail "unset sink: must not emit wrapper.identity on streams"
fi

printf 'PASS ca.sh wrapper.identity file sink/fail-open\n'
