#!/usr/bin/env bash

# A ScreencopyView only has content *after* capture. It is not a readiness
# signal, so an overview thumbnail must first wait for its enclosing layer
# surface to render a frame. This contract keeps that warning-prone boundary
# explicit without opening a QML test window.

set -uo pipefail

repo_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
thumbnail="$repo_dir/config/dot/quickshell/modules/overview/WindowThumbnail.qml"

fail() {
    printf 'overview thumbnail contract: %s\n' "$1" >&2
    exit 1
}

[[ -r "$thumbnail" ]] || fail 'WindowThumbnail.qml is missing'

grep -qF 'FrameAnimation {' "$thumbnail" \
    || fail 'capture has no frame-ready gate'
grep -qF 'property bool recordingReady: false' "$thumbnail" \
    || fail 'capture readiness is not tracked independently from captured content'
grep -qF 'if (!shot.recordingReady)' "$thumbnail" \
    || fail 'capture can start before the frame-ready gate'
grep -qF 'frameReady.restart();' "$thumbnail" \
    || fail 'a pending capture is not scheduled by the frame-ready gate'
grep -qF 'shot.recordingReady = true;' "$thumbnail" \
    || fail 'the frame-ready signal never releases capture'

capture_calls="$(grep -cF 'shot.captureFrame()' "$thumbnail")"
[[ "$capture_calls" -eq 1 ]] \
    || fail "capture must have one bounded attempt after readiness, found $capture_calls"
! grep -qF 'captureAttempts' "$thumbnail" \
    || fail 'blind capture retry state remains'
! grep -qF 'captureRetry' "$thumbnail" \
    || fail 'blind capture retry timer remains'

# The application icon remains visible until the one-shot capture succeeds.
grep -qF 'opacity: shotLoader.hasFrame ? 0 : 1' "$thumbnail" \
    || fail 'app-icon fallback no longer remains visible before a frame arrives'

printf 'overview thumbnail contract: PASS (frame-gated one-shot capture with icon fallback)\n'
