#!/usr/bin/env bash
# Run with bash, not source. Requires Bash, mktemp, cmp, and Codex on PATH.
# Tests a known answer/file in a fresh directory; leaves that directory for inspection.
set -u

if [[ $# -ne 1 || ( "$1" != output && "$1" != write ) ]]; then
  printf '%s\n' 'Usage: bash verify-new-output.sh output|write' >&2
  exit 2
fi

mode=$1
run_dir=$(mktemp -d ./codex-check.XXXXXXXX) || exit 1
cd "$run_dir" || exit 1
printf 'run directory: %s\n' "$PWD" >&2

if [[ "$mode" == output ]]; then
  target=last.txt
  expected=OK
  sandbox=read-only
  prompt='Reply with the single word OK.'
else
  target=hello.txt
  expected=hello
  sandbox=workspace-write
  prompt='Create hello.txt in the current directory with exactly these five UTF-8 bytes: "hello" (no quotes, period, BOM, or newline). Do not use any other directory. Reply DONE only if successful.'
fi

if codex exec --skip-git-repo-check --ephemeral -s "$sandbox" -o last.txt "$prompt" < /dev/null; then
  :
else
  status=$?
  printf 'codex failed: exit %s\n' "$status" >&2
  exit "$status"
fi

if [[ ! -f "$target" || -L "$target" ]]; then
  printf 'missing regular output file: %s\n' "$target" >&2
  exit 1
fi
if ! cmp -s "$target" <(printf '%s' "$expected"); then
  printf 'unexpected contents: %s\n' "$target" >&2
  exit 1
fi
printf 'verified: %s/%s\n' "$PWD" "$target"
