#!/usr/bin/env bash
# GitHub Actions uses Checks API check-runs, not only legacy commit statuses.

set -u

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
WORK_DIR="${MOSAIC_TEST_WORK_DIR:-$PWD/.mosaic-test-work/ci-queue-wait-github-checks}"
REPO_DIR="$WORK_DIR/repo"
STUB_DIR="$WORK_DIR/stubs"
rm -rf "$WORK_DIR"
mkdir -p "$REPO_DIR" "$STUB_DIR"
git -C "$REPO_DIR" init -q
git -C "$REPO_DIR" checkout -q -b fix/github-checks
git -C "$REPO_DIR" remote add origin https://github.com/acme/widgets.git

cat > "$STUB_DIR/gh" <<'SH'
#!/usr/bin/env bash
set -euo pipefail
endpoint=""
for arg in "$@"; do
    [[ "$arg" == repos/* ]] && endpoint="$arg"
done
printf '%s\n' "$*" >> "${MOSAIC_GH_CALL_LOG:?}"
case "$endpoint" in
    repos/acme/widgets/branches/fix/github-checks)
        printf '%s\n' '0123456789abcdef0123456789abcdef01234567'
        ;;
    repos/acme/widgets/commits/*/statuses?per_page=100)
        printf '%s\n' '[[]]'
        ;;
    repos/acme/widgets/commits/*/check-runs?per_page=100\&filter=latest)
        case "${MOSAIC_GH_CHECK_MODE:?}" in
            success) printf '%s\n' '[{"total_count":1,"check_runs":[{"name":"ci","status":"completed","conclusion":"success"}]}]' ;;
            pending) printf '%s\n' '[{"total_count":1,"check_runs":[{"name":"ci","status":"in_progress","conclusion":null}]}]' ;;
            failure) printf '%s\n' '[{"total_count":1,"check_runs":[{"name":"ci","status":"completed","conclusion":"failure"}]}]' ;;
            late-failure) printf '%s\n' '[{"total_count":2,"check_runs":[{"name":"first-page","status":"completed","conclusion":"success"}]},{"total_count":2,"check_runs":[{"name":"later-page","status":"completed","conclusion":"failure"}]}]' ;;
            *) exit 2 ;;
        esac
        ;;
    *) echo "unexpected gh endpoint: $endpoint" >&2; exit 2 ;;
esac
SH
chmod +x "$STUB_DIR/gh"

run_guard() {
    local mode="$1" purpose="${2:-push}"
    (
        cd "$REPO_DIR" || exit
        export PATH="$STUB_DIR:$PATH"
        export MOSAIC_GH_CHECK_MODE="$mode"
        export MOSAIC_GH_CALL_LOG="$WORK_DIR/gh-calls.log"
        export MOSAIC_CI_QUEUE_AUDIT_LOG="$WORK_DIR/audit.jsonl"
        "$SCRIPT_DIR/ci-queue-wait.sh" --purpose "$purpose" -t 0 -i 0
    )
}

failures=0
assert_case() {
    local mode="$1" expected_rc="$2" expected_state="$3" purpose="${4:-push}" output rc
    set +e
    output=$(run_guard "$mode" "$purpose" 2>&1)
    rc=$?
    set -e
    if [[ "$expected_rc" == zero && "$rc" -ne 0 ]]; then
        echo "FAIL github-$mode: expected rc=0, got $rc" >&2
        failures=$((failures + 1))
    elif [[ "$expected_rc" == nonzero && "$rc" -eq 0 ]]; then
        echo "FAIL github-$mode: expected rc!=0, got 0" >&2
        failures=$((failures + 1))
    fi
    if [[ "$output" != *"state=$expected_state"* ]]; then
        echo "FAIL github-$mode: expected state=$expected_state, got:" >&2
        printf '%s\n' "$output" >&2
        failures=$((failures + 1))
    fi
}

set -e
: > "$WORK_DIR/gh-calls.log"
assert_case success zero terminal-success
assert_case pending nonzero pending
assert_case failure zero terminal-failure
assert_case late-failure zero terminal-failure
assert_case failure nonzero terminal-failure merge
assert_case late-failure nonzero terminal-failure merge

if [[ $(grep -c 'check-runs?per_page=100&filter=latest' "$WORK_DIR/gh-calls.log") -lt 6 ]]; then
    echo "FAIL: expected every case to query all Checks API pages" >&2
    failures=$((failures + 1))
fi

if [[ "$failures" -ne 0 ]]; then
    echo "GitHub check-runs regression failed ($failures assertions)" >&2
    exit 1
fi

echo "GitHub check-runs regression passed (6/6 purpose-aware cases, including later-page failure)"
