#!/bin/sh
# Record a snapshot of a tiny Textual app, compare the unchanged app against
# it, then change the app and check that the mismatch produces the snapshot
# report.
set -efu

fail() {
    echo "FAIL: $*" >&2
    exit 1
}

write_app() {
    cat > app.py <<EOF
from textual.app import App
from textual.widgets import Label


class SmokeApp(App):
    def compose(self):
        yield Label("$1")
EOF
}

cd "$AUTOPKGTEST_TMP"

cat > test_smoke.py <<'EOF'
def test_smoke(snap_compare):
    assert snap_compare("app.py", terminal_size=(20, 3))
EOF

for py in $(py3versions -s 2> /dev/null); do
    echo "=== $py ==="
    rm -rf __snapshots__ snapshot_report.html
    write_app hello

    echo "--- record"
    $py -m pytest --snapshot-update test_smoke.py
    # the snapshot must be stored as SVG, not with syrupy's default extension
    test -f __snapshots__/test_smoke/test_smoke.svg \
        || fail "snapshot not saved as __snapshots__/test_smoke/test_smoke.svg"

    echo "--- compare, unchanged app"
    $py -m pytest test_smoke.py

    echo "--- compare, changed app: the snapshot test is expected to fail"
    write_app world
    rc=0
    $py -m pytest test_smoke.py > pytest.log 2>&1 || rc=$?
    cat pytest.log
    test "$rc" -eq 1 || fail "pytest exited with $rc, expected 1"
    if grep -q FileNotFoundError pytest.log; then
        fail "FileNotFoundError while writing the snapshot report"
    fi
    test -f snapshot_report.html || fail "snapshot_report.html not written"
    grep -q test_smoke snapshot_report.html \
        || fail "snapshot_report.html does not mention test_smoke"
    echo "--- OK: the expected failure was reported in snapshot_report.html"
done
